intercept

package
v2.37.3 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: AGPL-3.0 Imports: 19 Imported by: 1 module, 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

Index

Constants

View Source
const (
	AuthHeaderXAPIKey       = "X-Api-Key" //nolint:gosec // G101 false positive: HTTP header name, not a credential.
	AuthHeaderAuthorization = "Authorization"
)

Auth header names shared by providers (which set them on resolved credentials) and interceptors (which present credentials under them).

View Source
const (
	OpenAIErrTypeError     = "error"
	OpenAIErrTypeAPI       = "api_error"
	OpenAIErrTypeRateLimit = "rate_limit_error"

	OpenAIErrCodeServer    = "server_error"
	OpenAIErrCodeRateLimit = "rate_limit_exceeded"
)

OpenAI error type and code constants used by the chatcompletions and responses interceptors. The OpenAI Go SDK does not expose these as typed constants, so we define our own. See https://platform.openai.com/docs/guides/error-codes.

Variables

This section is empty.

Functions

func ActorHeadersAsAnthropicOpts

func ActorHeadersAsAnthropicOpts(actor *context.Actor) []ant_option.RequestOption

ActorHeadersAsAnthropicOpts produces a slice of headers using Anthropic's RequestOption type.

func ActorHeadersAsOpenAIOpts

func ActorHeadersAsOpenAIOpts(actor *context.Actor) []oai_option.RequestOption

ActorHeadersAsOpenAIOpts produces a slice of headers using OpenAI's RequestOption type.

func ActorIDHeader

func ActorIDHeader() string

func ActorMetadataHeader

func ActorMetadataHeader(name string) string

func BuildUpstreamHeaders

func BuildUpstreamHeaders(sdkHeader http.Header, clientHeaders http.Header, authHeaderName string) http.Header

BuildUpstreamHeaders produces the header set for an upstream SDK request. It starts from the prepared client headers, then preserves specific headers from the SDK-built request that must not be overwritten.

func IsActorHeader

func IsActorHeader(name string) bool

func PrepareClientHeaders

func PrepareClientHeaders(clientHeaders http.Header) http.Header

PrepareClientHeaders returns a copy of the client headers with hop-by-hop, transport, auth, and proxy headers removed.

func WithCredentialInfo added in v2.35.0

func WithCredentialInfo(ctx context.Context, cred Credential) context.Context

WithCredentialInfo returns a context carrying the credential hint and length.

Types

type BYOK added in v2.35.0

type BYOK struct {
	Secret string
	Header string
}

BYOK authenticates with a single user-supplied secret.

func AsBYOK added in v2.35.0

func AsBYOK(c Credential) (BYOK, bool)

AsBYOK reports whether c is a BYOK credential and returns it if so.

func (BYOK) AuthHeader added in v2.35.0

func (b BYOK) AuthHeader() string

func (BYOK) Hint added in v2.35.0

func (b BYOK) Hint() string

func (BYOK) Kind added in v2.35.0

func (BYOK) Kind() CredentialKind

func (BYOK) Length added in v2.35.0

func (b BYOK) Length() int

type Bedrock added in v2.35.0

type Bedrock struct {
	AccessKey string
}

Bedrock authenticates with AWS Bedrock: requests are signed (so there is no auth header) using either static credentials (when an access key is set) or the AWS default credential chain. There is no key pool or failover.

func (Bedrock) AuthHeader added in v2.35.0

func (Bedrock) AuthHeader() string

func (Bedrock) Hint added in v2.35.0

func (b Bedrock) Hint() string

func (Bedrock) Kind added in v2.35.0

func (Bedrock) Kind() CredentialKind

func (Bedrock) Length added in v2.35.0

func (b Bedrock) Length() int

type CentralizedPool added in v2.35.0

type CentralizedPool struct {
	Pool   *keypool.Pool
	Header string
	// contains filtered or unexported fields
}

CentralizedPool authenticates with a provider-managed key pool and fails over across keys.

func AsCentralizedPool added in v2.35.0

func AsCentralizedPool(c Credential) (*CentralizedPool, bool)

AsCentralizedPool reports whether c is a key-pool credential that fails over, and returns it if so.

func (*CentralizedPool) AuthHeader added in v2.35.0

func (c *CentralizedPool) AuthHeader() string

func (*CentralizedPool) Hint added in v2.35.0

func (c *CentralizedPool) Hint() string

func (*CentralizedPool) Kind added in v2.35.0

func (*CentralizedPool) Length added in v2.35.0

func (c *CentralizedPool) Length() int

func (*CentralizedPool) NextKey added in v2.35.0

func (c *CentralizedPool) NextKey(w *keypool.Walker) (*keypool.Key, *keypool.Error)

NextKey advances the failover walker and records the selected key as the one in use.

type Config added in v2.35.0

type Config struct {
	// ProviderName is the provider instance name, used for recording,
	// logging, and API dumps.
	ProviderName string
	// BaseURL is the upstream provider's API base URL.
	BaseURL string
	// APIDumpDir is the directory for dumping API requests and responses,
	// or empty when API dumping is disabled.
	APIDumpDir string
	// SendActorHeaders reports whether actor identity headers should be
	// forwarded to the upstream provider.
	SendActorHeaders bool
}

Config is the per-request configuration an interceptor needs to process an interception, independent of which provider produced it. Providers resolve it in CreateInterceptor and hand it to the API-format interceptor.

type Credential added in v2.35.0

type Credential interface {
	Kind() CredentialKind
	// AuthHeader is the header carrying this request's credential, or empty when
	// the credential is not carried in a header.
	AuthHeader() string
	// Hint is a masked, identifiable fragment of the credential.
	Hint() string
	// Length is the length of the credential value.
	Length() int
}

Credential is the per-request upstream authentication for an interception:

  • BYOK: a user-supplied secret.
  • Bedrock: AWS Bedrock credentials, used to sign requests.
  • CentralizedPool: a provider-managed key pool with failover.

type CredentialKind

type CredentialKind string

CredentialKind identifies how a request was authenticated. Keep in sync with the credential_kind enum in coderd's database.

const (
	CredentialKindCentralized CredentialKind = "centralized"
	CredentialKindBYOK        CredentialKind = "byok"
)

type Interceptor

type Interceptor interface {
	// ID returns the unique identifier for this interception.
	ID() uuid.UUID
	// Setup injects some required dependencies. This MUST be called before using the interceptor
	// to process requests.
	Setup(logger slog.Logger, rec recorder.Recorder, mcpProxy mcp.ServerProxier)
	// Model returns the model in use for this [Interceptor].
	Model() string
	// ProcessRequest handles the HTTP request.
	ProcessRequest(w http.ResponseWriter, r *http.Request) error
	// Specifies whether an interceptor handles streaming or not.
	Streaming() bool
	// TraceAttributes returns tracing attributes for this [Interceptor]
	TraceAttributes(*http.Request) []attribute.KeyValue
	// Credential returns the credential resolved for this interception. Its
	// Hint/Length reflect the key in use (the last failover key for a pool
	// credential, otherwise the static credential), for logs and records.
	Credential() Credential
	// CorrelatingToolCallID returns the ID of a tool call result submitted
	// in the request, if present. This is used to correlate the current
	// interception back to the previous interception that issued those tool
	// calls. If multiple tool use results are present, we use the last one
	// (most recent). Both Anthropic's /v1/messages and OpenAI's /v1/responses
	// require that ALL tool results are submitted for tool choices returned
	// by the model, so any single tool call ID is sufficient to identify the
	// parent interception.
	CorrelatingToolCallID() *string
}

Interceptor describes a (potentially) stateful interaction with an AI provider.

type ResponseError added in v2.34.0

type ResponseError struct {
	ErrorObject *shared.ErrorObject `json:"error"`
	StatusCode  int                 `json:"-"`
	RetryAfter  time.Duration       `json:"-"`
}

ResponseError is the OpenAI-shaped error envelope returned to clients. StatusCode and RetryAfter map to HTTP headers, not JSON fields. The chatcompletions and responses interceptors both use the same response error format.

func NewResponseError added in v2.34.0

func NewResponseError(msg, errType, code string, status int, retryAfter time.Duration) *ResponseError

NewResponseError builds a ResponseError with the OpenAI-shaped envelope. errType and code should be one of the OpenAIErrType* and OpenAIErrCode* constants defined above.

func ResponseErrorFromAPIError added in v2.34.0

func ResponseErrorFromAPIError(err error) *ResponseError

ResponseErrorFromAPIError converts an OpenAI SDK error into a ResponseError. Returns nil if err is not an *openai.Error.

func ResponseErrorFromKeyPool added in v2.34.0

func ResponseErrorFromKeyPool(keyPoolErr *keypool.Error) *ResponseError

ResponseErrorFromKeyPool translates a *keypool.Error into a developer-facing ResponseError shaped for the OpenAI API.

func (*ResponseError) Error added in v2.34.0

func (e *ResponseError) Error() string

func (*ResponseError) ToResponse added in v2.34.0

func (e *ResponseError) ToResponse() *http.Response

ToResponse marshals e into an *http.Response shaped for the OpenAI API.

Directories

Path Synopsis
Package bedrocksig holds the shared AWS SigV4 signing and Bedrock Mantle routing helpers used by both the anthropic-go and openai-go interceptors.
Package bedrocksig holds the shared AWS SigV4 signing and Bedrock Mantle routing helpers used by both the anthropic-go and openai-go interceptors.

Jump to

Keyboard shortcuts

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