anthropic

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2025 License: MIT Imports: 19 Imported by: 1

README

anthropic-go

Extracted and refactored code for working with Anthropic API from https://github.com/diveagents/dive

Documentation

Index

Constants

View Source
const ProviderName = "anthropic"

Variables

View Source
var (
	DefaultModel         = "claude-sonnet-4-20250514"
	DefaultEndpoint      = "https://api.anthropic.com/v1/messages"
	DefaultMaxTokens     = 4096
	DefaultClient        = &http.Client{Timeout: 300 * time.Second}
	DefaultMaxRetries    = 6
	DefaultRetryBaseWait = 2 * time.Second
	DefaultVersion       = "2023-06-01"
)
View Source
var ToolChoiceAny = &ToolChoice{Type: ToolChoiceTypeAny}

ToolChoiceAny is a ToolChoice with type "any".

View Source
var ToolChoiceAuto = &ToolChoice{Type: ToolChoiceTypeAuto}

ToolChoiceAuto is a ToolChoice with type "auto".

View Source
var ToolChoiceNone = &ToolChoice{Type: ToolChoiceTypeNone}

ToolChoiceNone is a ToolChoice with type "none".

Functions

func ShouldRetry

func ShouldRetry(statusCode int) bool

ShouldRetry determines if the given status code should trigger a retry

Types

type CacheControl

type CacheControl struct {
	Type CacheControlType `json:"type"`
}

CacheControl is used to control caching of content blocks.

type CacheControlSetter

type CacheControlSetter interface {
	SetCacheControl(cacheControl *CacheControl)
}

CacheControlSetter is an interface that allows setting the cache control for a content block.

type CacheControlType

type CacheControlType string
const (
	CacheControlTypeEphemeral  CacheControlType = "ephemeral"
	CacheControlTypePersistent CacheControlType = "persistent"
)

func (CacheControlType) String

func (c CacheControlType) String() string

type CharLocation

type CharLocation struct {
	Type           string `json:"type"` // "char_location"
	CitedText      string `json:"cited_text,omitempty"`
	DocumentIndex  int    `json:"document_index,omitempty"`
	DocumentTitle  string `json:"document_title,omitempty"`
	StartCharIndex int    `json:"start_char_index,omitempty"`
	EndCharIndex   int    `json:"end_char_index,omitempty"`
}

CharLocation is a citation to a specific part of a document.

func (*CharLocation) IsCitation

func (c *CharLocation) IsCitation() bool

type Citation

type Citation interface {
	IsCitation() bool
}

type CitationSettings

type CitationSettings struct {
	Enabled bool `json:"enabled"`
}

CitationSettings contains settings for citations in a message.

type CitationType

type CitationType string
const (
	CitationTypeCharLocation            CitationType = "char_location"
	CitationTypeWebSearchResultLocation CitationType = "web_search_result_location"
	CitationTypeURLCitation             CitationType = "url_citation"
)

type Client

type Client struct {
	SystemPrompt       string                   `json:"system_prompt,omitempty"`
	Tools              []ToolInterface          `json:"tools,omitempty"`
	ToolChoice         *ToolChoice              `json:"tool_choice,omitempty"`
	ParallelToolCalls  *bool                    `json:"parallel_tool_calls,omitempty"`
	MCPServers         []MCPServerConfig        `json:"mcp_servers,omitempty"`
	Prefill            string                   `json:"prefill,omitempty"`
	PrefillClosingTag  string                   `json:"prefill_closing_tag,omitempty"`
	MaxTokens          *int                     `json:"max_tokens,omitempty"`
	Temperature        *float64                 `json:"temperature,omitempty"`
	PresencePenalty    *float64                 `json:"presence_penalty,omitempty"`
	FrequencyPenalty   *float64                 `json:"frequency_penalty,omitempty"`
	ReasoningBudget    *int                     `json:"reasoning_budget,omitempty"`
	ReasoningEffort    ReasoningEffort          `json:"reasoning_effort,omitempty"`
	Features           []string                 `json:"features,omitempty"`
	RequestHeaders     http.Header              `json:"request_headers,omitempty"`
	Caching            *bool                    `json:"caching,omitempty"`
	PreviousResponseID string                   `json:"previous_response_id,omitempty"`
	ServiceTier        string                   `json:"service_tier,omitempty"`
	ClientOptions      map[string]interface{}   `json:"client_options,omitempty"`
	ResponseFormat     *ResponseFormat          `json:"response_format,omitempty"`
	Messages           Messages                 `json:"messages"`
	Client             *http.Client             `json:"-"`
	SSECallback        ServerSentEventsCallback `json:"-"`
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Client

func (*Client) Apply

func (c *Client) Apply(opts ...Option)

Apply applies the given options to the config.

func (*Client) Generate

func (p *Client) Generate(ctx context.Context, messages Messages) (*Response, error)

func (*Client) Name

func (p *Client) Name() string

func (*Client) Stream

func (p *Client) Stream(ctx context.Context, messages Messages) (*StreamIterator, error)

type ClientError

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

func NewError

func NewError(statusCode int, body string) *ClientError

func (*ClientError) Error

func (e *ClientError) Error() string

func (*ClientError) IsRecoverable

func (e *ClientError) IsRecoverable() bool

func (*ClientError) StatusCode

func (e *ClientError) StatusCode() int

type CodeExecutionResult

type CodeExecutionResult struct {
	Type       string `json:"type"`
	Stdout     string `json:"stdout"`
	Stderr     string `json:"stderr"`
	ReturnCode int    `json:"return_code"`
}

type CodeExecutionTool

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

CodeExecutionTool is a tool that allows Claude to execute code. This is provided by Anthropic as a server-side tool. Learn more: https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/code-execution-tool

func NewCodeExecutionTool

func NewCodeExecutionTool(opts CodeExecutionToolOptions) *CodeExecutionTool

NewCodeExecutionTool creates a new CodeExecutionTool with the given options.

func (*CodeExecutionTool) Annotations

func (t *CodeExecutionTool) Annotations() *ToolAnnotations

func (*CodeExecutionTool) Call

func (t *CodeExecutionTool) Call(ctx context.Context, input any) (*ToolResult, error)

func (*CodeExecutionTool) Description

func (t *CodeExecutionTool) Description() string

func (*CodeExecutionTool) Name

func (t *CodeExecutionTool) Name() string

func (*CodeExecutionTool) Schema

func (t *CodeExecutionTool) Schema() *Schema

func (*CodeExecutionTool) ToolConfiguration

func (t *CodeExecutionTool) ToolConfiguration(providerName string) map[string]any

type CodeExecutionToolOptions

type CodeExecutionToolOptions struct {
	Type string
}

CodeExecutionToolOptions are the options used to configure a CodeExecutionTool.

type CodeExecutionToolResultContent

type CodeExecutionToolResultContent struct {
	ToolUseID string              `json:"tool_use_id"`
	Content   CodeExecutionResult `json:"content"`
}

func (*CodeExecutionToolResultContent) MarshalJSON

func (c *CodeExecutionToolResultContent) MarshalJSON() ([]byte, error)

func (*CodeExecutionToolResultContent) Type

type Content

type Content interface {
	Type() ContentType
}

Content is a single block of content in a message. A message may contain multiple content blocks of varying types.

func UnmarshalContent

func UnmarshalContent(data []byte) (Content, error)

UnmarshalContent unmarshals the JSON of one content block into the appropriate concrete Content type.

type ContentChunk

type ContentChunk struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

ContentChunk is used within a Content block to pass chunks of content.

type ContentSource

type ContentSource struct {
	// Type is the type of the content source ("base64", "url", "text", or "file")
	Type ContentSourceType `json:"type"`

	// MediaType is the media type of the content. E.g. "image/jpeg", "application/pdf"
	MediaType string `json:"media_type,omitempty"`

	// Data is base64 encoded data (used with ContentSourceTypeBase64)
	Data string `json:"data,omitempty"`

	// URL is the URL of the content (used with ContentSourceTypeURL)
	URL string `json:"url,omitempty"`

	// FileID is the file ID from the Files API (used with ContentSourceTypeFile)
	FileID string `json:"file_id,omitempty"`

	// Chunks of content. Only use if chunking on the client side, for use
	// within a DocumentContent block.
	Content []*ContentChunk `json:"content,omitempty"`

	// GenerationID is an ID associated with the generation of this content,
	// if any. This may be set on content returned from image generation, for
	// example. Used for OpenAI image generation results.
	GenerationID string `json:"generation_id,omitempty"`

	// GenerationStatus is the status of the generation of this content,
	// if any. This may be set on content returned from image generation, for
	// example. Used for OpenAI image generation results.
	GenerationStatus string `json:"generation_status,omitempty"`
}

ContentSource conveys information about media content in a message.

func ContentURL

func ContentURL(url string) *ContentSource

ContentURL creates a content source with the given URL.

func EncodedData

func EncodedData(mediaType, base64Data string) *ContentSource

EncodedData creates a content source with the given media type and base64-encoded data.

func FileID

func FileID(id string) *ContentSource

FileID creates a content source with the given file ID.

func RawData

func RawData(mediaType string, data []byte) *ContentSource

RawData creates a content source with the given media type and raw data. Automatically base64 encodes the provided data.

func (*ContentSource) DecodedData

func (c *ContentSource) DecodedData() ([]byte, error)

DecodedData returns the decoded data if this content carries base64 encoded data.

type ContentSourceType

type ContentSourceType string

ContentSourceType indicates the location of the media content.

const (
	ContentSourceTypeBase64 ContentSourceType = "base64"
	ContentSourceTypeURL    ContentSourceType = "url"
	ContentSourceTypeText   ContentSourceType = "text"
	ContentSourceTypeFile   ContentSourceType = "file"
)

func (ContentSourceType) String

func (c ContentSourceType) String() string

type ContentType

type ContentType string

ContentType indicates the type of a content block in a message

const (
	ContentTypeText                    ContentType = "text"
	ContentTypeImage                   ContentType = "image"
	ContentTypeDocument                ContentType = "document"
	ContentTypeFile                    ContentType = "file"
	ContentTypeToolUse                 ContentType = "tool_use"
	ContentTypeToolResult              ContentType = "tool_result"
	ContentTypeThinking                ContentType = "thinking"
	ContentTypeRedactedThinking        ContentType = "redacted_thinking"
	ContentTypeServerToolUse           ContentType = "server_tool_use"
	ContentTypeWebSearchToolResult     ContentType = "web_search_tool_result"
	ContentTypeMCPToolUse              ContentType = "mcp_tool_use"
	ContentTypeMCPToolResult           ContentType = "mcp_tool_result"
	ContentTypeMCPListTools            ContentType = "mcp_list_tools"
	ContentTypeMCPApprovalRequest      ContentType = "mcp_approval_request"
	ContentTypeMCPApprovalResponse     ContentType = "mcp_approval_response"
	ContentTypeCodeExecutionToolResult ContentType = "code_execution_tool_result"
	ContentTypeRefusal                 ContentType = "refusal"
)

type DocumentContent

type DocumentContent struct {
	Source       *ContentSource    `json:"source"`
	Title        string            `json:"title,omitempty"`
	Context      string            `json:"context,omitempty"`
	Citations    *CitationSettings `json:"citations,omitempty"`
	CacheControl *CacheControl     `json:"cache_control,omitempty"`
}

func NewDocumentContent

func NewDocumentContent(source *ContentSource) *DocumentContent

NewDocumentContent creates a document content block with the given content source.

func (*DocumentContent) MarshalJSON

func (c *DocumentContent) MarshalJSON() ([]byte, error)

func (*DocumentContent) SetCacheControl

func (c *DocumentContent) SetCacheControl(cacheControl *CacheControl)

func (*DocumentContent) Type

func (c *DocumentContent) Type() ContentType

type Event

type Event struct {
	Type         EventType          `json:"type"`
	Index        *int               `json:"index,omitempty"`
	Message      *Response          `json:"message,omitempty"`
	ContentBlock *EventContentBlock `json:"content_block,omitempty"`
	Delta        *EventDelta        `json:"delta,omitempty"`
	Usage        *Usage             `json:"usage,omitempty"`
}

Event represents a single streaming event from the LLM. A successfully run stream will end with a final message containing the complete Response.

type EventContentBlock

type EventContentBlock struct {
	Type      ContentType     `json:"type"`
	Text      string          `json:"text,omitempty"`
	ID        string          `json:"id,omitempty"`
	Name      string          `json:"name,omitempty"`
	Input     json.RawMessage `json:"input,omitempty"`
	Thinking  string          `json:"thinking,omitempty"`
	Signature string          `json:"signature,omitempty"`
}

EventContentBlock carries the start of a content block in an LLM event.

type EventDelta

type EventDelta struct {
	Type         EventDeltaType `json:"type,omitempty"`
	Text         string         `json:"text,omitempty"`
	Index        int            `json:"index,omitempty"`
	StopReason   string         `json:"stop_reason,omitempty"`
	StopSequence string         `json:"stop_sequence,omitempty"`
	PartialJSON  string         `json:"partial_json,omitempty"`
	Thinking     string         `json:"thinking,omitempty"`
	Signature    string         `json:"signature,omitempty"`
}

EventDelta carries a portion of an LLM response.

type EventDeltaType

type EventDeltaType string

EventDeltaType indicates the type of delta in an LLM event.

const (
	EventDeltaTypeText      EventDeltaType = "text_delta"
	EventDeltaTypeInputJSON EventDeltaType = "input_json_delta"
	EventDeltaTypeThinking  EventDeltaType = "thinking_delta"
	EventDeltaTypeSignature EventDeltaType = "signature_delta"
	EventDeltaTypeCitations EventDeltaType = "citations_delta"
)

func (EventDeltaType) String

func (e EventDeltaType) String() string

type EventType

type EventType string

EventType represents the type of streaming event

const (
	EventTypePing              EventType = "ping"
	EventTypeMessageStart      EventType = "message_start"
	EventTypeMessageDelta      EventType = "message_delta"
	EventTypeMessageStop       EventType = "message_stop"
	EventTypeContentBlockStart EventType = "content_block_start"
	EventTypeContentBlockDelta EventType = "content_block_delta"
	EventTypeContentBlockStop  EventType = "content_block_stop"
)

func (EventType) String

func (e EventType) String() string

type ImageContent

type ImageContent struct {
	Source       *ContentSource `json:"source"`
	CacheControl *CacheControl  `json:"cache_control,omitempty"`
}

func (*ImageContent) Image

func (c *ImageContent) Image() (image.Image, error)

Image returns the image content as an image.Image.

func (*ImageContent) MarshalJSON

func (c *ImageContent) MarshalJSON() ([]byte, error)

func (*ImageContent) SetCacheControl

func (c *ImageContent) SetCacheControl(cacheControl *CacheControl)

func (*ImageContent) Type

func (c *ImageContent) Type() ContentType

type ImageSource

type ImageSource struct {
	Type      string `json:"type"`
	MediaType string `json:"media_type"`
	Data      string `json:"data"`
}

type MCPApprovalRequestContent

type MCPApprovalRequestContent struct {
	ID          string `json:"id"`
	Arguments   string `json:"arguments"`
	Name        string `json:"name"`
	ServerLabel string `json:"server_label"`
}

func (*MCPApprovalRequestContent) MarshalJSON

func (c *MCPApprovalRequestContent) MarshalJSON() ([]byte, error)

func (*MCPApprovalRequestContent) Type

type MCPApprovalResponseContent

type MCPApprovalResponseContent struct {
	ApprovalRequestID string `json:"approval_request_id"`
	Approve           bool   `json:"approve"`
	Reason            string `json:"reason,omitempty"`
}

func (*MCPApprovalResponseContent) MarshalJSON

func (c *MCPApprovalResponseContent) MarshalJSON() ([]byte, error)

func (*MCPApprovalResponseContent) Type

type MCPListToolsContent

type MCPListToolsContent struct {
	ServerLabel string               `json:"server_label"`
	Tools       []*MCPToolDefinition `json:"tools"`
}

func (*MCPListToolsContent) MarshalJSON

func (c *MCPListToolsContent) MarshalJSON() ([]byte, error)

func (*MCPListToolsContent) Type

func (c *MCPListToolsContent) Type() ContentType

type MCPServerConfig

type MCPServerConfig struct {
	Type               string                 `json:"type"`
	URL                string                 `json:"url"`
	Name               string                 `json:"name,omitempty"`
	AuthorizationToken string                 `json:"authorization_token,omitempty"`
	ToolConfiguration  *MCPToolConfiguration  `json:"tool_configuration,omitempty"`
	Headers            map[string]string      `json:"headers,omitempty"`
	ToolApproval       string                 `json:"tool_approval,omitempty"`
	ToolApprovalFilter *MCPToolApprovalFilter `json:"tool_approval_filter,omitempty"`
}

MCPServerConfig is used to configure an MCP server. Corresponds to this Anthropic feature: https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector#using-the-mcp-connector-in-the-messages-api And OpenAI's Remote MCP feature: https://platform.openai.com/docs/guides/tools-remote-mcp#page-top

type MCPToolApprovalFilter

type MCPToolApprovalFilter struct {
	Always []string `json:"always,omitempty"`
	Never  []string `json:"never,omitempty"`
}

MCPToolApprovalFilter is used to configure the approval filter for MCP tools. The Always and Never fields should contain the names of tools whose calls should have customized approvals.

type MCPToolConfiguration

type MCPToolConfiguration struct {
	Enabled      bool     `json:"enabled"`
	AllowedTools []string `json:"allowed_tools,omitempty"`
}

type MCPToolDefinition

type MCPToolDefinition struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	InputSchema map[string]interface{} `json:"input_schema,omitempty"`
}

type MCPToolResultContent

type MCPToolResultContent struct {
	ToolUseID string          `json:"tool_use_id"`
	IsError   bool            `json:"is_error,omitempty"`
	Content   []*ContentChunk `json:"content,omitempty"`
}

func (*MCPToolResultContent) MarshalJSON

func (c *MCPToolResultContent) MarshalJSON() ([]byte, error)

func (*MCPToolResultContent) Type

type MCPToolUseContent

type MCPToolUseContent struct {
	ID         string          `json:"id"`
	Name       string          `json:"name"`
	ServerName string          `json:"server_name"`
	Input      json.RawMessage `json:"input"`
}

func (*MCPToolUseContent) MarshalJSON

func (c *MCPToolUseContent) MarshalJSON() ([]byte, error)

func (*MCPToolUseContent) Type

func (c *MCPToolUseContent) Type() ContentType

type Message

type Message struct {
	ID      string    `json:"id,omitempty"`
	Role    Role      `json:"role"`
	Content []Content `json:"content"`
}

Message containing content passed to or from an LLM.

func NewAssistantMessage

func NewAssistantMessage(content ...Content) *Message

NewAssistantMessage creates an assistant message with the given content.

func NewAssistantTextMessage

func NewAssistantTextMessage(text string) *Message

NewAssistantTextMessage creates an assistant message with a single text content block.

func NewMessage

func NewMessage(role Role, content []Content) *Message

NewMessage creates a message with the given role and content blocks.

func NewToolResultMessage

func NewToolResultMessage(outputs ...*ToolResultContent) *Message

NewToolResultMessage creates a message with the user role and a list of tool outputs. Used to pass the results of tool calls back to an LLM.

func NewUserMessage

func NewUserMessage(content ...Content) *Message

NewUserMessage creates a user message with the given content blocks.

func NewUserTextMessage

func NewUserTextMessage(text string) *Message

NewUserTextMessage creates a user message with a single text content block.

func (*Message) DecodeInto

func (m *Message) DecodeInto(v any) error

DecodeInto decodes the last text content in the message as JSON into a given Go object. This pairs with the WithResponseFormat request option.

func (*Message) ImageContent

func (m *Message) ImageContent() (*ImageContent, bool)

ImageContent returns the first image content in the message, if any.

func (*Message) LastText

func (m *Message) LastText() string

LastText returns the last text content in the message.

func (*Message) Text

func (m *Message) Text() string

Text returns a concatenated text from all message content. If there were multiple text contents, they are separated by two newlines.

func (*Message) ThinkingContent

func (m *Message) ThinkingContent() (*ThinkingContent, bool)

ThinkingContent returns the first thinking content in the message, if any.

func (*Message) WithContent

func (m *Message) WithContent(content ...Content) *Message

WithContent appends content block(s) to the message.

func (*Message) WithText

func (m *Message) WithText(text ...string) *Message

WithText appends text content block(s) to the message.

type Messages

type Messages []*Message

Messages is shorthand for a slice of messages.

type Option

type Option func(*Client)

Option is a function that is used to adjust LLM configuration.

func WithAPIKey

func WithAPIKey(apiKey string) Option

func WithBaseWait

func WithBaseWait(baseWait time.Duration) Option

func WithClient

func WithClient(client *http.Client) Option

func WithEndpoint

func WithEndpoint(endpoint string) Option

func WithMaxRetries

func WithMaxRetries(maxRetries int) Option

func WithMaxTokens

func WithMaxTokens(maxTokens int) Option

func WithModel

func WithModel(model string) Option

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt sets the system prompt for the client.

func WithToolChoice

func WithToolChoice(choice *ToolChoice) Option

WithToolChoice sets the tool choice strategy for the client.

func WithTools

func WithTools(tools ...ToolInterface) Option

WithTools sets the tools available to the client.

func WithVersion

func WithVersion(version string) Option

type Property

type Property struct {
	Type                 SchemaType           `json:"type,omitempty"`
	Description          string               `json:"description,omitempty"`
	Enum                 []string             `json:"enum,omitempty"`
	Items                *Property            `json:"items,omitempty"`
	Required             []string             `json:"required,omitempty"`
	Properties           map[string]*Property `json:"properties,omitempty"`
	AdditionalProperties *bool                `json:"additionalProperties,omitempty"`
	Nullable             *bool                `json:"nullable,omitempty"`
	Pattern              *string              `json:"pattern,omitempty"`
	Format               *string              `json:"format,omitempty"`
	MinItems             *int                 `json:"minItems,omitempty"`
	MaxItems             *int                 `json:"maxItems,omitempty"`
	MinLength            *int                 `json:"minLength,omitempty"`
	MaxLength            *int                 `json:"maxLength,omitempty"`
	Minimum              *float64             `json:"minimum,omitempty"`
	Maximum              *float64             `json:"maximum,omitempty"`
}

Property of a schema.

type ReasoningEffort

type ReasoningEffort string

ReasoningEffort defines the effort level for reasoning aka extended thinking.

const (
	ReasoningEffortLow    ReasoningEffort = "low"
	ReasoningEffortMedium ReasoningEffort = "medium"
	ReasoningEffortHigh   ReasoningEffort = "high"
)

func (ReasoningEffort) IsValid

func (r ReasoningEffort) IsValid() bool

IsValid returns true if the reasoning effort is a known, valid value.

type RedactedThinkingContent

type RedactedThinkingContent struct {
	Data string `json:"data"`
}

RedactedThinkingContent is a content block that contains encrypted thinking, due to being flagged by the provider's safety systems. These are decrypted when passed back to the LLM, so that it can continue the thought process.

func (*RedactedThinkingContent) MarshalJSON

func (c *RedactedThinkingContent) MarshalJSON() ([]byte, error)

func (*RedactedThinkingContent) Type

type RefusalContent

type RefusalContent struct {
	Text         string        `json:"text"`
	CacheControl *CacheControl `json:"cache_control,omitempty"`
}

func (*RefusalContent) MarshalJSON

func (c *RefusalContent) MarshalJSON() ([]byte, error)

func (*RefusalContent) SetCacheControl

func (c *RefusalContent) SetCacheControl(cacheControl *CacheControl)

func (*RefusalContent) Type

func (c *RefusalContent) Type() ContentType

type Request

type Request struct {
	Model       string            `json:"model"`
	Messages    []*Message        `json:"messages"`
	MaxTokens   *int              `json:"max_tokens,omitempty"`
	Temperature *float64          `json:"temperature,omitempty"`
	System      string            `json:"system,omitempty"`
	Stream      bool              `json:"stream,omitempty"`
	Tools       []map[string]any  `json:"tools,omitempty"`
	ToolChoice  *ToolChoice       `json:"tool_choice,omitempty"`
	Thinking    *Thinking         `json:"thinking,omitempty"`
	MCPServers  []MCPServerConfig `json:"mcp_servers,omitempty"`
}

type Response

type Response struct {
	ID           string    `json:"id"`
	Model        string    `json:"model"`
	Role         Role      `json:"role"`
	Content      []Content `json:"content"`
	StopReason   string    `json:"stop_reason"`
	StopSequence *string   `json:"stop_sequence,omitempty"`
	Type         string    `json:"type"`
	Usage        Usage     `json:"usage"`
}

Response is the generated response from an LLM. Matches the Anthropic response format documented here: https://docs.anthropic.com/en/api/messages#response-content

func (*Response) Message

func (r *Response) Message() *Message

Message extracts and returns the message from the response.

func (*Response) ToolCalls

func (r *Response) ToolCalls() []*ToolUseContent

ToolCalls extracts and returns all tool calls from the response.

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshaling for Response to properly handle the polymorphic Content field.

type ResponseAccumulator

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

ResponseAccumulator builds up a complete response from a stream of events.

func NewResponseAccumulator

func NewResponseAccumulator() *ResponseAccumulator

NewResponseAccumulator creates a new ResponseAccumulator.

func (*ResponseAccumulator) AddEvent

func (r *ResponseAccumulator) AddEvent(event *Event) error

AddEvent adds an event to the ResponseAccumulator.

func (*ResponseAccumulator) IsComplete

func (r *ResponseAccumulator) IsComplete() bool

func (*ResponseAccumulator) Response

func (r *ResponseAccumulator) Response() *Response

func (*ResponseAccumulator) Usage

func (r *ResponseAccumulator) Usage() *Usage

type ResponseFormat

type ResponseFormat struct {
	// Type indicates the format type ("text", "json_object", or "json_schema")
	Type ResponseFormatType `json:"type"`

	// Schema provides a JSON schema to guide the model's output
	Schema *Schema `json:"schema,omitempty"`

	// Name provides a name for the output to guide the model
	Name string `json:"name,omitempty"`

	// Description provides additional context to guide the model
	Description string `json:"description,omitempty"`
}

ResponseFormat guides an LLM's response format.

type ResponseFormatType

type ResponseFormatType string
const (
	ResponseFormatTypeText       ResponseFormatType = "text"
	ResponseFormatTypeJSON       ResponseFormatType = "json_object"
	ResponseFormatTypeJSONSchema ResponseFormatType = "json_schema"
)

type Role

type Role string

Role indicates the role of a message in a conversation. Either "user", "assistant", or "system".

const (
	User      Role = "user"
	Assistant Role = "assistant"
	System    Role = "system"
)

func (Role) String

func (r Role) String() string

type Schema

type Schema struct {
	Type                 SchemaType           `json:"type"`
	Properties           map[string]*Property `json:"properties"`
	Required             []string             `json:"required,omitempty"`
	AdditionalProperties *bool                `json:"additionalProperties,omitempty"`
}

Schema describes the structure of a JSON object.

func (*Schema) AsMap

func (s *Schema) AsMap() map[string]any

AsMap converts the schema to a map[string]any.

type SchemaType

type SchemaType string

SchemaType represents the type of a JSON schema.

const (
	Array   SchemaType = "array"
	Boolean SchemaType = "boolean"
	Integer SchemaType = "integer"
	Null    SchemaType = "null"
	Number  SchemaType = "number"
	Object  SchemaType = "object"
	String  SchemaType = "string"
)

type ServerSentEventsCallback

type ServerSentEventsCallback func(line string) error

ServerSentEventsCallback is a callback that is called for each line of the server-sent events stream.

type ServerSentEventsReader

type ServerSentEventsReader[T any] struct {
	// contains filtered or unexported fields
}

ServerSentEventsReader reads SSE events from a reader a decodes them into the parameter type T.

func NewServerSentEventsReader

func NewServerSentEventsReader[T any](stream io.ReadCloser) *ServerSentEventsReader[T]

NewServerSentEventsReader creates a new ServerSentEventsReader.

func (*ServerSentEventsReader[T]) Err

func (s *ServerSentEventsReader[T]) Err() error

Err returns the error that occurred while reading the SSE stream.

func (*ServerSentEventsReader[T]) Next

func (s *ServerSentEventsReader[T]) Next() (T, bool)

Next reads the next event from the SSE stream.

func (*ServerSentEventsReader[T]) WithSSECallback

func (s *ServerSentEventsReader[T]) WithSSECallback(callback ServerSentEventsCallback) *ServerSentEventsReader[T]

WithSSECallback sets an optional callback that is called for each line of the server-sent events stream.

type ServerToolUseContent

type ServerToolUseContent struct {
	ID    string         `json:"id"`
	Name  string         `json:"name"`
	Input map[string]any `json:"input"`
}

func (*ServerToolUseContent) MarshalJSON

func (c *ServerToolUseContent) MarshalJSON() ([]byte, error)

func (*ServerToolUseContent) Type

type StreamIterator

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

StreamIterator implements the StreamIterator interface

func (*StreamIterator) Close

func (s *StreamIterator) Close() error

func (*StreamIterator) Err

func (s *StreamIterator) Err() error

func (*StreamIterator) Event

func (s *StreamIterator) Event() *Event

Event returns the current event. Should only be called after a successful Next().

func (*StreamIterator) Next

func (s *StreamIterator) Next() bool

Next advances to the next event in the stream. Returns true if an event was successfully read, false when the stream is complete or an error occurs.

type TextContent

type TextContent struct {
	Text         string        `json:"text"`
	CacheControl *CacheControl `json:"cache_control,omitempty"`
	Citations    []Citation    `json:"citations,omitempty"`
}

func NewTextContent

func NewTextContent(text string) *TextContent

NewTextContent creates a text content block with the given text.

func (*TextContent) MarshalJSON

func (c *TextContent) MarshalJSON() ([]byte, error)

func (*TextContent) SetCacheControl

func (c *TextContent) SetCacheControl(cacheControl *CacheControl)

func (*TextContent) Type

func (c *TextContent) Type() ContentType

type Thinking

type Thinking struct {
	Type         string `json:"type"` // "enabled"
	BudgetTokens int    `json:"budget_tokens"`
}

type ThinkingContent

type ThinkingContent struct {
	ID        string `json:"id,omitempty"`
	Thinking  string `json:"thinking"`
	Signature string `json:"signature,omitempty"`
}

ThinkingContent is a content block that contains the LLM's internal thought process. The provider may use the signature to verify that the content was generated by the LLM.

Per Anthropic's documentation: It is only strictly necessary to send back thinking blocks when using tool use with extended thinking. Otherwise you can omit thinking blocks from previous turns, or let the API strip them for you if you pass them back.

func (*ThinkingContent) MarshalJSON

func (c *ThinkingContent) MarshalJSON() ([]byte, error)

func (*ThinkingContent) Type

func (c *ThinkingContent) Type() ContentType

type Tool

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

type ToolAnnotations

type ToolAnnotations struct {
	Title           string         `json:"title,omitempty"`
	ReadOnlyHint    bool           `json:"readOnlyHint,omitempty"`
	DestructiveHint bool           `json:"destructiveHint,omitempty"`
	IdempotentHint  bool           `json:"idempotentHint,omitempty"`
	OpenWorldHint   bool           `json:"openWorldHint,omitempty"`
	Extra           map[string]any `json:"extra,omitempty"`
}

func (*ToolAnnotations) MarshalJSON

func (a *ToolAnnotations) MarshalJSON() ([]byte, error)

func (*ToolAnnotations) UnmarshalJSON

func (a *ToolAnnotations) UnmarshalJSON(data []byte) error

type ToolCallResult

type ToolCallResult struct {
	ID     string
	Name   string
	Input  any
	Result *ToolUseResult
	Error  error
}

ToolCallResult is a tool call that has been made. This is used to understand what calls have happened during an LLM interaction.

type ToolChoice

type ToolChoice struct {
	Type                   ToolChoiceType `json:"type"`
	Name                   string         `json:"name,omitempty"`
	DisableParallelToolUse bool           `json:"disable_parallel_tool_use,omitempty"`
}

ToolChoice influences the behavior of the LLM when choosing which tool to use.

type ToolChoiceType

type ToolChoiceType string

ToolChoiceType is used to guide the LLM's choice of which tool to use.

const (
	ToolChoiceTypeAuto ToolChoiceType = "auto"
	ToolChoiceTypeAny  ToolChoiceType = "any"
	ToolChoiceTypeTool ToolChoiceType = "tool"
	ToolChoiceTypeNone ToolChoiceType = "none"
)

func (ToolChoiceType) IsValid

func (t ToolChoiceType) IsValid() bool

IsValid returns true if the ToolChoiceType is a known, valid value.

type ToolConfiguration

type ToolConfiguration interface {
	// ToolConfiguration returns a map of configuration for the tool, when used
	// with the given provider.
	ToolConfiguration(providerName string) map[string]any
}

ToolConfiguration is an interface that may be implemented by a Tool to provide explicit JSON configuration to pass to the LLM provider.

type ToolDefinition

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

ToolDefinition is a concrete implementation of the Tool interface. Note this does not provide a mechanism for calling the tool, but only for describing what the tool does so the LLM can understand it. You might not use this implementation if you use a full dive.Tool implementation in your app.

func NewToolDefinition

func NewToolDefinition() *ToolDefinition

NewToolDefinition creates a new ToolDefinition.

func (*ToolDefinition) Description

func (t *ToolDefinition) Description() string

Description returns the description of the tool, per the Tool interface.

func (*ToolDefinition) Name

func (t *ToolDefinition) Name() string

Name returns the name of the tool, per the Tool interface.

func (*ToolDefinition) Schema

func (t *ToolDefinition) Schema() *Schema

Schema returns the schema of the tool, per the Tool interface.

func (*ToolDefinition) WithDescription

func (t *ToolDefinition) WithDescription(description string) *ToolDefinition

WithDescription sets the description of the tool.

func (*ToolDefinition) WithName

func (t *ToolDefinition) WithName(name string) *ToolDefinition

WithName sets the name of the tool.

func (*ToolDefinition) WithSchema

func (t *ToolDefinition) WithSchema(schema *Schema) *ToolDefinition

WithSchema sets the schema of the tool.

type ToolInterface

type ToolInterface interface {
	// Name of the tool.
	Name() string

	// Description of the tool.
	Description() string

	// Schema describes the parameters used to call the tool.
	Schema() *Schema
}

ToolInterface is an interface that defines a tool that can be called by an LLM.

type ToolResult

type ToolResult struct {
	Content []*ToolResultContents `json:"content"`
	IsError bool                  `json:"isError,omitempty"`
}

ToolResult is the output from a tool call.

func NewToolResult

func NewToolResult(content ...*ToolResultContents) *ToolResult

NewToolResult creates a new ToolResult with the given content.

func NewToolResultError

func NewToolResultError(text string) *ToolResult

NewToolResultError creates a new ToolResult containing an error message.

func NewToolResultText

func NewToolResultText(text string) *ToolResult

NewToolResultText creates a new ToolResult with the given text content.

type ToolResultContent

type ToolResultContent struct {
	ToolUseID    string        `json:"tool_use_id"`
	Content      any           `json:"content"`
	IsError      bool          `json:"is_error,omitempty"`
	CacheControl *CacheControl `json:"cache_control,omitempty"`
}

func (*ToolResultContent) MarshalJSON

func (c *ToolResultContent) MarshalJSON() ([]byte, error)

func (*ToolResultContent) SetCacheControl

func (c *ToolResultContent) SetCacheControl(cacheControl *CacheControl)

func (*ToolResultContent) Type

func (c *ToolResultContent) Type() ContentType

type ToolResultContentType

type ToolResultContentType string
const (
	ToolResultContentTypeText  ToolResultContentType = "text"
	ToolResultContentTypeImage ToolResultContentType = "image"
	ToolResultContentTypeAudio ToolResultContentType = "audio"
)

func (ToolResultContentType) String

func (t ToolResultContentType) String() string

type ToolResultContents

type ToolResultContents struct {
	Type        ToolResultContentType `json:"type"`
	Text        string                `json:"text,omitempty"`
	Data        string                `json:"data,omitempty"`
	MimeType    string                `json:"mimeType,omitempty"`
	Annotations map[string]any        `json:"annotations,omitempty"`
}

type ToolUseContent

type ToolUseContent struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

func (*ToolUseContent) MarshalJSON

func (c *ToolUseContent) MarshalJSON() ([]byte, error)

func (*ToolUseContent) Type

func (c *ToolUseContent) Type() ContentType

type ToolUseResult

type ToolUseResult struct {
	ToolUseID string `json:"tool_use_id"`
	Output    string `json:"output,omitempty"`
	Error     error  `json:"error,omitempty"`
}

ToolUseResult contains the result of a tool call

type TypedTool

type TypedTool[T any] interface {
	// Name of the tool.
	Name() string

	// Description of the tool.
	Description() string

	// Schema describes the parameters used to call the tool.
	Schema() *Schema

	// Annotations returns optional properties that describe tool behavior.
	Annotations() *ToolAnnotations

	// Call is the function that is called to use the tool.
	Call(ctx context.Context, input T) (*ToolResult, error)
}

TypedTool is a tool that can be called with a specific type of input.

type TypedToolAdapter

type TypedToolAdapter[T any] struct {
	// contains filtered or unexported fields
}

TypedToolAdapter is an adapter that allows a TypedTool to be used as a regular Tool. Specifically the Call method accepts `input any` and then internally unmarshals the input to the correct type and passes it to the TypedTool.

func ToolAdapter

func ToolAdapter[T any](tool TypedTool[T]) *TypedToolAdapter[T]

ToolAdapter creates a new TypedToolAdapter for the given tool.

func (*TypedToolAdapter[T]) Annotations

func (t *TypedToolAdapter[T]) Annotations() *ToolAnnotations

func (*TypedToolAdapter[T]) Call

func (t *TypedToolAdapter[T]) Call(ctx context.Context, input any) (*ToolResult, error)

func (*TypedToolAdapter[T]) Description

func (t *TypedToolAdapter[T]) Description() string

func (*TypedToolAdapter[T]) Name

func (t *TypedToolAdapter[T]) Name() string

func (*TypedToolAdapter[T]) Schema

func (t *TypedToolAdapter[T]) Schema() *Schema

func (*TypedToolAdapter[T]) ToolConfiguration

func (t *TypedToolAdapter[T]) ToolConfiguration(providerName string) map[string]any

func (*TypedToolAdapter[T]) Unwrap

func (t *TypedToolAdapter[T]) Unwrap() TypedTool[T]

Unwrap returns the underlying TypedTool.

type Usage

type Usage struct {
	InputTokens              int `json:"input_tokens"`
	OutputTokens             int `json:"output_tokens"`
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens,omitempty"`
}

Usage contains token usage information for an LLM response.

func (*Usage) Add

func (u *Usage) Add(other *Usage)

Add incremental usage to this usage object.

func (*Usage) Copy

func (u *Usage) Copy() *Usage

Copy returns a deep copy of the usage data.

type UserLocation

type UserLocation struct {
	Type     string `json:"type"`     // "approximate"
	City     string `json:"city"`     // "San Francisco"
	Region   string `json:"region"`   // "California"
	Country  string `json:"country"`  // "US"
	Timezone string `json:"timezone"` // "America/Los_Angeles"
}

UserLocation conveys the user's location to the web search tool.

type WebSearchResult

type WebSearchResult struct {
	Type             string `json:"type"`
	URL              string `json:"url"`
	Title            string `json:"title"`
	EncryptedContent string `json:"encrypted_content"`
	PageAge          string `json:"page_age"`
}

type WebSearchResultLocation

type WebSearchResultLocation struct {
	Type           string `json:"type"` // "web_search_result_location"
	URL            string `json:"url"`
	Title          string `json:"title"`
	EncryptedIndex string `json:"encrypted_index,omitempty"`
	CitedText      string `json:"cited_text,omitempty"`
}

WebSearchResultLocation is a citation to a specific part of a web page.

func (*WebSearchResultLocation) IsCitation

func (c *WebSearchResultLocation) IsCitation() bool

type WebSearchTool

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

WebSearchTool is a tool that allows Claude to search the web. This is provided by Anthropic as a server-side tool. Learn more: https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/web-search-tool

func NewWebSearchTool

func NewWebSearchTool(opts WebSearchToolOptions) *WebSearchTool

NewWebSearchTool creates a new WebSearchTool with the given options.

func (*WebSearchTool) Annotations

func (t *WebSearchTool) Annotations() *ToolAnnotations

func (*WebSearchTool) Call

func (t *WebSearchTool) Call(ctx context.Context, input any) (*ToolResult, error)

func (*WebSearchTool) Description

func (t *WebSearchTool) Description() string

func (*WebSearchTool) Name

func (t *WebSearchTool) Name() string

func (*WebSearchTool) Schema

func (t *WebSearchTool) Schema() *Schema

func (*WebSearchTool) ToolConfiguration

func (t *WebSearchTool) ToolConfiguration(providerName string) map[string]any

type WebSearchToolOptions

type WebSearchToolOptions struct {
	Type           string
	MaxUses        int
	AllowedDomains []string
	BlockedDomains []string
	UserLocation   *UserLocation
}

WebSearchToolOptions are the options used to configure a WebSearchTool.

type WebSearchToolResultContent

type WebSearchToolResultContent struct {
	ToolUseID string             `json:"tool_use_id"`
	Content   []*WebSearchResult `json:"content"`
	ErrorCode string             `json:"error_code,omitempty"`
}

func (*WebSearchToolResultContent) MarshalJSON

func (c *WebSearchToolResultContent) MarshalJSON() ([]byte, error)

func (*WebSearchToolResultContent) Type

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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