modelclient

package
v0.4.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package modelclient implements the shared HTTP wire client for Anthropic Messages and OpenAI-compatible Chat Completions endpoints used by both the editor's built-in agent and the agent evaluation harness.

Index

Constants

View Source
const (
	// FormatAnthropic selects the Anthropic Messages API (/v1/messages).
	FormatAnthropic = "anthropic"
	// FormatOpenAI selects the OpenAI-compatible Chat Completions API (/v1/chat/completions).
	FormatOpenAI = "openai"

	// DefaultAnthropicAPIVersion is the default anthropic-version request header.
	DefaultAnthropicAPIVersion = "2023-06-01"

	// DefaultMaxResponseBytes bounds the size of any single HTTP response body read from a model server.
	DefaultMaxResponseBytes int64 = 8 << 20
)

Variables

View Source
var (
	// ErrEndpointInsecure is returned when an endpoint URL is malformed, contains embedded credentials,
	// or uses plaintext http:// to a non-loopback host.
	ErrEndpointInsecure = errors.New("modelclient: endpoint must use https:// (or loopback http://)")

	// ErrFormatUnsupported is returned when an API format is neither anthropic nor openai.
	ErrFormatUnsupported = errors.New("modelclient: unsupported API format")

	// ErrResponseTooLarge is returned when a server response exceeds MaxResponseBytes.
	ErrResponseTooLarge = errors.New("modelclient: response exceeded maximum size")

	// ErrDecodeResponse is returned when a 2xx server response cannot be decoded as valid JSON.
	ErrDecodeResponse = errors.New("modelclient: decode response")
)

Functions

func CheckRedirect

func CheckRedirect(req *http.Request, via []*http.Request) error

CheckRedirect prevents credential leaks across hosts and https-to-http downgrades.

func DoWithRetry

func DoWithRetry[T any](ctx context.Context, maxRetries int, baseBackoff time.Duration, fn func(context.Context) (T, error)) (T, error)

DoWithRetry executes fn up to maxRetries+1 attempts, retrying transport errors and retryable HTTPError statuses with exponential backoff starting at baseBackoff (negative disables delay).

func IsLoopbackEndpoint

func IsLoopbackEndpoint(raw string) bool

IsLoopbackEndpoint reports whether raw parses as a URL targeting a loopback host.

func IsLoopbackHost

func IsLoopbackHost(host string) bool

IsLoopbackHost reports whether host is localhost or a loopback IP address.

func IsRetryableStatus

func IsRetryableStatus(statusCode int) bool

IsRetryableStatus reports whether statusCode is a transient error worth retrying (429, 5xx, 529 overloaded).

func ResolveBaseURL

func ResolveBaseURL(raw, format string) (string, error)

ResolveBaseURL parses a base or full endpoint URL without rejecting non-loopback http:// (for CLI harnesses that connect to local network proxies) and resolves the completion endpoint for format.

func ResolveEndpoint

func ResolveEndpoint(raw, format string) (string, error)

ResolveEndpoint validates raw and resolves it to the concrete request endpoint for format.

func ResolveModelsURL

func ResolveModelsURL(raw, format string) (string, error)

ResolveModelsURL validates raw and returns the model-listing URL (GET .../models) for format.

func ValidateEndpoint

func ValidateEndpoint(raw string) (*url.URL, error)

ValidateEndpoint parses raw and enforces https:// for remote hosts or http:// only for loopback hosts, refusing embedded credentials and missing hosts.

Types

type AnthropicCacheControl

type AnthropicCacheControl struct {
	Type string `json:"type"`
}

AnthropicCacheControl marks a prompt block or tool definition as cacheable by Anthropic Messages.

type AnthropicContentBlock

type AnthropicContentBlock struct {
	Type      string          `json:"type"`
	Text      string          `json:"text,omitempty"`
	ID        string          `json:"id,omitempty"`
	Name      string          `json:"name,omitempty"`
	Input     json.RawMessage `json:"input,omitempty"`
	ToolUseID string          `json:"tool_use_id,omitempty"`
	Content   string          `json:"content,omitempty"`
	IsError   bool            `json:"is_error,omitempty"`
}

AnthropicContentBlock is one block inside an Anthropic message or response.

type AnthropicMessage

type AnthropicMessage struct {
	Role    string `json:"role"`
	Content any    `json:"content"`
}

AnthropicMessage is one message turn in an Anthropic Messages request.

type AnthropicRequest

type AnthropicRequest struct {
	Model        string                 `json:"model"`
	MaxTokens    int                    `json:"max_tokens"`
	System       string                 `json:"-"`
	SystemBlocks []AnthropicSystemBlock `json:"-"`
	Tools        []AnthropicTool        `json:"tools,omitempty"`
	Messages     []AnthropicMessage     `json:"messages"`
}

AnthropicRequest is the JSON request body for POST /v1/messages. When SystemBlocks is non-empty, "system" is encoded as an array of AnthropicSystemBlock (supporting cache_control); otherwise System is encoded as a plain string when non-empty.

func (AnthropicRequest) MarshalJSON

func (r AnthropicRequest) MarshalJSON() ([]byte, error)

MarshalJSON encodes AnthropicRequest with "system" formatted either as structured SystemBlocks (when non-empty) or as a plain System string.

type AnthropicResponse

type AnthropicResponse struct {
	ID         string                  `json:"id"`
	Model      string                  `json:"model"`
	StopReason string                  `json:"stop_reason"`
	Content    []AnthropicContentBlock `json:"content"`
	Usage      AnthropicUsage          `json:"usage"`
}

AnthropicResponse is the decoded response from POST /v1/messages.

type AnthropicSystemBlock

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

AnthropicSystemBlock is one structured system prompt block in an Anthropic Messages request.

type AnthropicTool

type AnthropicTool struct {
	Name         string                 `json:"name"`
	Description  string                 `json:"description,omitempty"`
	InputSchema  json.RawMessage        `json:"input_schema"`
	CacheControl *AnthropicCacheControl `json:"cache_control,omitempty"`
}

AnthropicTool describes a tool for the Anthropic Messages API.

type AnthropicUsage

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

AnthropicUsage reports token counts returned by Anthropic Messages.

type Client

type Client struct {
	HTTPClient       *http.Client
	MaxResponseBytes int64
	AnthropicVersion string
}

Client sends Anthropic Messages, OpenAI Chat Completions, and model-listing HTTP requests.

func (*Client) DoAnthropic

func (c *Client) DoAnthropic(ctx context.Context, endpoint, apiKey string, payload AnthropicRequest) (*AnthropicResponse, error)

DoAnthropic sends one Anthropic Messages request to endpoint.

func (*Client) DoOpenAI

func (c *Client) DoOpenAI(ctx context.Context, endpoint, apiKey string, payload OpenAIRequest) (*OpenAIResponse, error)

DoOpenAI sends one OpenAI-compatible Chat Completions request to endpoint.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context, format, endpoint, apiKey string) ([]string, error)

ListModels queries the server's /models endpoint and returns the sorted unique model IDs it advertises.

type HTTPError

type HTTPError struct {
	StatusCode int
	ErrType    string
	Message    string
	Retryable  bool
}

HTTPError represents a non-2xx HTTP status returned by a model endpoint.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type OpenAIChoice

type OpenAIChoice struct {
	Message      OpenAIChoiceMessage `json:"message"`
	FinishReason string              `json:"finish_reason"`
}

OpenAIChoice is one choice returned by OpenAI Chat Completions.

type OpenAIChoiceMessage

type OpenAIChoiceMessage struct {
	Role      string           `json:"role"`
	Content   string           `json:"content"`
	ToolCalls []OpenAIToolCall `json:"tool_calls"`
}

OpenAIChoiceMessage holds the assistant message inside a completion choice.

type OpenAIFunctionCall

type OpenAIFunctionCall struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

OpenAIFunctionCall holds the tool name and JSON-encoded arguments string.

type OpenAIFunctionSpec

type OpenAIFunctionSpec struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Parameters  json.RawMessage `json:"parameters"`
}

OpenAIFunctionSpec describes a function name, description, and JSON Schema parameters.

type OpenAIMessage

type OpenAIMessage struct {
	Role       string           `json:"role"`
	Content    any              `json:"content,omitempty"`
	ToolCalls  []OpenAIToolCall `json:"tool_calls,omitempty"`
	ToolCallID string           `json:"tool_call_id,omitempty"`
}

OpenAIMessage is one message turn in an OpenAI Chat Completions request.

type OpenAIPromptTokensDetails

type OpenAIPromptTokensDetails struct {
	CachedTokens int `json:"cached_tokens,omitempty"`
}

OpenAIPromptTokensDetails reports optional cached-token counts inside OpenAI prompt_tokens.

type OpenAIRequest

type OpenAIRequest struct {
	Model     string          `json:"model"`
	MaxTokens int             `json:"max_tokens,omitempty"`
	Messages  []OpenAIMessage `json:"messages"`
	Tools     []OpenAITool    `json:"tools,omitempty"`
}

OpenAIRequest is the JSON request body for POST /v1/chat/completions.

type OpenAIResponse

type OpenAIResponse struct {
	Choices []OpenAIChoice `json:"choices"`
	Usage   OpenAIUsage    `json:"usage"`
}

OpenAIResponse is the decoded response from POST /v1/chat/completions.

type OpenAITool

type OpenAITool struct {
	Type     string             `json:"type"`
	Function OpenAIFunctionSpec `json:"function"`
}

OpenAITool describes a function tool for the OpenAI Chat Completions API.

type OpenAIToolCall

type OpenAIToolCall struct {
	ID       string             `json:"id"`
	Type     string             `json:"type"`
	Function OpenAIFunctionCall `json:"function"`
}

OpenAIToolCall describes one function call returned by an assistant message.

type OpenAIUsage

type OpenAIUsage struct {
	PromptTokens        int                        `json:"prompt_tokens"`
	CompletionTokens    int                        `json:"completion_tokens"`
	PromptTokensDetails *OpenAIPromptTokensDetails `json:"prompt_tokens_details,omitempty"`
}

OpenAIUsage reports token counts returned by OpenAI Chat Completions.

Jump to

Keyboard shortcuts

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