chat

package
v1.22.3 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package chat provides a client for the stateless Chat API.

The Chat API is a pure function: f(messages, context) → stream of blocks. It doesn't read or write messages to any database. The client sends the full conversation history on every request and receives a streamed response.

Message persistence is handled separately by the caller.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func UserFacingStreamError added in v1.22.1

func UserFacingStreamError(err error) string

UserFacingStreamError returns concise error copy suitable for toast UI.

Types

type Client

type Client interface {
	// StreamSnapshots sends the conversation to the Chat API and streams normalized snapshots.
	// Each snapshot includes scoped progress metadata (conversation/turn/seq/status).
	StreamSnapshots(ctx context.Context, req Request, onSnapshot func(StreamSnapshot)) (*StreamResult, error)

	// Stream sends the conversation to the Chat API and streams the response.
	// The onMessage callback is called each time the message is updated with new content.
	// The returned StreamResult contains the final message and any metadata.
	Stream(ctx context.Context, req Request, onMessage func(*domain.Message)) (*StreamResult, error)

	// SetAccountID sets the account ID for requests.
	SetAccountID(accountID domain.AccountID)
	// WithAccountID returns a new client scoped to accountID.
	WithAccountID(accountID domain.AccountID) Client
}

Client sends messages to the Chat API and streams responses.

func NewClient

func NewClient(endpoint string, authService auth.Auth, scope log.Scope, globalTools []Tool) Client

NewClient creates a new Chat API client. - globalTools are included in every request automatically - Retries transient errors (connection reset, 502/503/504) up to 3 times with backoff - Gets a fresh token via auth.GetAccessToken before each request

func NewClientWithHTTP

func NewClientWithHTTP(endpoint string, authService auth.Auth, httpClient HTTPDoer, scope log.Scope, globalTools []Tool) Client

NewClientWithHTTP creates a new Chat API client with a custom HTTP client (for testing).

type EventType

type EventType string

EventType identifies the kind of SSE event from the Chat API.

const (
	EventTypeMessageStart     EventType = "message_start"
	EventTypeTextDelta        EventType = "text_delta"
	EventTypeThinkingDelta    EventType = "thinking_delta"
	EventTypeToolUse          EventType = "tool_use"
	EventTypeToolInputDelta   EventType = "tool_input_delta"
	EventTypeContentBlockStop EventType = "content_block_stop"
	EventTypeMessageStop      EventType = "message_stop"
	EventTypeMetadataUpdate   EventType = "metadata_update"
)

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer is the interface for making HTTP requests.

type Items

type Items struct {
	Type  string `json:"type,omitempty"`
	Items *Items `json:"items,omitempty"`
}

Items defines the schema for array items.

type Property

type Property struct {
	Type        string   `json:"type,omitempty"`
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
	Items       *Items   `json:"items,omitempty"`
}

Property defines a single property in a JSON Schema.

type Request

type Request struct {
	ConversationID  string                 `json:"conversation_id"`
	Messages        []domain.Message       `json:"messages"`
	ContextEntities []domain.ContextEntity `json:"context_entities,omitempty"`
	Tools           []Tool                 `json:"tools"`
}

Request is the input to the Chat API. The client sends the full conversation history on every request.

type Schema

type Schema struct {
	Type       string              `json:"type"`
	Properties map[string]Property `json:"properties"` // Always required by Anthropic API
	Required   []string            `json:"required,omitempty"`
}

Schema defines the JSON Schema for tool input.

func NewObjectSchema

func NewObjectSchema(properties map[string]Property, required []string) Schema

NewObjectSchema creates an object schema with the given properties.

func (Schema) MarshalJSON

func (s Schema) MarshalJSON() ([]byte, error)

MarshalJSON ensures Properties is never null (Anthropic API requires it).

type Session added in v1.22.3

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

Session owns in-memory message history for one active chat loop. Persistence is handled separately by callers.

func NewSession added in v1.22.3

func NewSession(conversationID domain.ConversationID, initial []domain.Message) *Session

NewSession creates a session with an initial history snapshot.

func (*Session) AppendMessage added in v1.22.3

func (s *Session) AppendMessage(message domain.Message)

AppendMessage appends a message to history.

func (*Session) AppendUserTextMessage added in v1.22.3

func (s *Session) AppendUserTextMessage(messageID domain.MessageID, text string) domain.Message

AppendUserTextMessage appends a user text message and returns it.

func (*Session) AppendUserToolResultsMessage added in v1.22.3

func (s *Session) AppendUserToolResultsMessage(messageID domain.MessageID, results []domain.ToolResult) domain.Message

AppendUserToolResultsMessage appends a user tool_result message and returns it.

func (*Session) Messages added in v1.22.3

func (s *Session) Messages() []domain.Message

Messages returns a defensive copy of the current history.

func (*Session) RecordAssistantMessage added in v1.22.3

func (s *Session) RecordAssistantMessage(message domain.Message)

RecordAssistantMessage upserts an assistant message in history by message ID.

func (*Session) RemoveMessagesByID added in v1.22.3

func (s *Session) RemoveMessagesByID(ids []domain.MessageID)

RemoveMessagesByID removes all messages whose IDs are in ids.

type StreamErrorClass added in v1.22.1

type StreamErrorClass string

StreamErrorClass is a normalized category for stream failures.

const (
	StreamErrorClassCancelled StreamErrorClass = "cancelled"
	StreamErrorClassTimeout   StreamErrorClass = "timeout"
	StreamErrorClassProtocol  StreamErrorClass = "protocol_error"
	StreamErrorClassRequest   StreamErrorClass = "request_error"
	StreamErrorClassServer    StreamErrorClass = "server_error"
	StreamErrorClassUnknown   StreamErrorClass = "unknown"
)

func ClassifyStreamError added in v1.22.1

func ClassifyStreamError(err error) StreamErrorClass

ClassifyStreamError maps raw stream errors into stable operational buckets.

type StreamMetadata

type StreamMetadata struct {
	Title         string // AI-generated conversation title, set after first exchange
	ContextWindow int    // Model's max token capacity (from message_start)
	InputTokens   int    // Tokens consumed by input this turn (from message_stop)
	OutputTokens  int    // Tokens generated by output this turn (from message_stop)
}

StreamMetadata contains post-stream metadata from the Chat API.

type StreamResult

type StreamResult struct {
	Message  *domain.Message
	Metadata *StreamMetadata // nil if no metadata_update event was received
}

StreamResult captures everything the stream produced.

type StreamSnapshot added in v1.22.1

type StreamSnapshot struct {
	ConversationID string
	TurnID         string
	Seq            int
	Status         StreamStatus
	AbortReason    string
	Done           bool
	Message        *domain.Message
	Metadata       *StreamMetadata
}

type StreamStatus added in v1.22.1

type StreamStatus string
const (
	StreamStatusStreaming StreamStatus = "streaming"
	StreamStatusCompleted StreamStatus = "completed"
	StreamStatusToolUse   StreamStatus = "tool_use"
	StreamStatusAborted   StreamStatus = "aborted"
)

type Tool

type Tool struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	InputSchema Schema `json:"input_schema"`
}

Tool defines a tool the AI can call. This is the wire format sent to the Chat API.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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