transform

package
v0.260409.1540 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2026 License: MPL-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlignToolMessagesForOpenAI

func AlignToolMessagesForOpenAI(req *openai.ChatCompletionNewParams)

AlignToolMessagesForOpenAI converts orphaned tool messages (those without a matching tool_call_id) to user messages. This prevents "role 'tool' must be a response to preceding message with 'tool_calls'" errors.

func SetRequest

func SetRequest[T RequestUnionConstraint](ctx *TransformContext, req T)

SetRequest updates the request in the context. Only types satisfying RequestUnionConstraint are accepted — passing any other type will result in a compile-time error.

Types

type BaseTransform

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

BaseTransform handles protocol conversion from original format to target API style This is the first transform in the chain, converting the request format before consistency normalization and vendor-specific adjustments.

func NewBaseTransform

func NewBaseTransform(targetType protocol.APIType) *BaseTransform

NewBaseTransform creates a new BaseTransform with the specified target API style

func (*BaseTransform) Apply

func (t *BaseTransform) Apply(ctx *TransformContext) error

Apply converts the request to the target API style This transform detects the original request type and applies the appropriate conversion. For OpenAI Chat target, it converts Anthropic v1/beta requests to OpenAI Chat format. For OpenAI Responses target, it converts Anthropic v1/beta requests to Responses format. For Anthropic targets, it converts OpenAI requests to Anthropic format. If the input type already matches the target type, no conversion is performed.

func (*BaseTransform) Name

func (t *BaseTransform) Name() string

Name returns the name of this transform

type ConsistencyTransform

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

ConsistencyTransform applies cross-provider normalization rules to requests. These rules apply to ALL providers, regardless of vendor.

Consistency Transform handles:

  • Tool Schema Normalization - Ensure type: "object", normalize properties
  • Scenario Flags - Disable stream usage, thinking mode if needed
  • Messages Normalization - Truncate tool_call_id to 40 chars
  • Validation - Check max_tokens, temperature ranges

func NewConsistencyTransform

func NewConsistencyTransform(targetAPIStyle protocol.APIType) *ConsistencyTransform

NewConsistencyTransform creates a new ConsistencyTransform for the given target API style.

func (*ConsistencyTransform) Apply

Apply executes the consistency normalization based on the target API style. Modifies ctx.Request in place and returns an error if transformation fails.

func (*ConsistencyTransform) Name

func (t *ConsistencyTransform) Name() string

Name returns the transform name for logging and tracking.

type RequestUnionConstraint

RequestUnionConstraint defines the exact set of request types accepted by the transform chain. This is a compile-time type constraint enforced via generic functions. Any attempt to pass a type not in this union will fail at compile time.

type Transform

type Transform interface {
	// Name returns the unique identifier for this transform
	Name() string

	// Apply applies the transformation to the context
	// Returns an error if the transformation fails
	Apply(ctx *TransformContext) error
}

Transform defines the interface for a single transformation step

type TransformChain

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

TransformChain manages an ordered sequence of transforms

func NewTransformChain

func NewTransformChain(transforms []Transform) *TransformChain

NewTransformChain creates a new TransformChain with the given transforms

func (*TransformChain) Add

func (c *TransformChain) Add(transform Transform)

Add appends a transform to the end of the chain

func (*TransformChain) Execute

Execute runs the transform chain on the provided context Transforms are executed in order, and each transform's name is recorded in TransformSteps. Returns the final TransformContext or an error if any transform fails with a descriptive error message.

func (*TransformChain) GetTransforms

func (c *TransformChain) GetTransforms() []Transform

GetTransforms returns a copy of the transforms in the chain

func (*TransformChain) Length

func (c *TransformChain) Length() int

Length returns the number of transforms in the chain

type TransformConfig added in v0.260402.2330

type TransformConfig struct {
	// MaxTokens is the maximum output tokens allowed for the request.
	// Used by base transform when converting between protocols.
	MaxTokens int64

	// UserID is the OAuth user ID for authenticated requests.
	UserID string

	// Device is the device identifier (e.g., Claude Code device ID).
	Device string

	// OpenAIConfig holds OpenAI-specific configuration populated during transforms.
	OpenAIConfig *protocol.OpenAIConfig

	// ResponsesConfig holds Responses API-specific configuration populated during transforms.
	ResponsesConfig *protocol.OpenAIConfig
}

TransformConfig holds structured, type-safe configuration for the transform chain. Use With* option constructors to set these values.

type TransformContext

type TransformContext struct {
	SourceAPI protocol.APIType
	TargetAPI protocol.APIType

	RequestModel  string
	ResponseModel string

	// Request is the request being transformed.
	// Use SetRequest[T]() to update — only types satisfying RequestUnionConstraint are accepted.
	Request interface{}

	// ProviderURL identifies the provider (e.g., "api.deepseek.com")
	ProviderURL string

	// ProviderType identifies the OAuth provider type (e.g., "claude_code", "codex")
	// This is used for provider-specific model filtering
	ProviderType string

	// ScenarioFlags contains configuration flags for the scenario
	ScenarioFlags *typ.ScenarioFlags

	// IsStreaming indicates if this is a streaming request
	IsStreaming bool

	// OriginalRequest stores the original request before any transformations
	OriginalRequest interface{}

	// TransformSteps records the names of transforms that have been applied
	TransformSteps []string

	// Config holds structured, type-safe configuration for the transform chain.
	Config TransformConfig

	// Extra allows transforms to pass arbitrary data through the chain
	Extra map[string]interface{}
}

TransformContext carries state through the transform chain

func NewTransformContext

func NewTransformContext[T RequestUnionConstraint](request T, opts ...TransformOption) *TransformContext

NewTransformContext creates a TransformContext with type-safe request validation. The generic type parameter T is constrained to RequestUnionConstraint, ensuring only valid request types can be used. Invalid types will cause a compile-time error.

Example:

ctx := transform.NewTransformContext(&anthropicReq,
    transform.WithProviderURL("api.deepseek.com"),
    transform.WithStreaming(true),
)

type TransformOption

type TransformOption func(*TransformContext)

TransformOption configures a TransformContext

func WithDevice added in v0.260402.2330

func WithDevice(device string) TransformOption

WithDevice sets the device identifier in the transform config.

func WithExtra

func WithExtra(extra map[string]interface{}) TransformOption

WithExtra sets initial extra data in the transform context.

func WithMaxTokens added in v0.260402.2330

func WithMaxTokens(maxTokens int64) TransformOption

WithMaxTokens sets the maximum output tokens in the transform config.

func WithProviderType

func WithProviderType(providerType string) TransformOption

WithProviderType sets the provider type (e.g., "claude_code", "codex") in the transform context.

func WithProviderURL

func WithProviderURL(url string) TransformOption

WithProviderURL sets the provider URL in the transform context.

func WithScenarioFlags

func WithScenarioFlags(flags *typ.ScenarioFlags) TransformOption

WithScenarioFlags sets the scenario flags in the transform context.

func WithStreaming

func WithStreaming(isStreaming bool) TransformOption

WithStreaming sets the streaming flag in the transform context.

func WithUserID added in v0.260402.2330

func WithUserID(userID string) TransformOption

WithUserID sets the OAuth user ID in the transform config.

type ValidationError

type ValidationError struct {
	Field   string      `json:"field"`
	Message string      `json:"message"`
	Value   interface{} `json:"value,omitempty"`
}

ValidationError represents a validation error for request parameters.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type VendorTransform

type VendorTransform struct {
	ProviderURL string // e.g., "api.deepseek.com", "api.moonshot.cn"
}

VendorTransform applies provider-specific adjustments to requests This wraps the existing transformer package functionality

func NewVendorTransform

func NewVendorTransform(providerURL string) *VendorTransform

NewVendorTransform creates a new vendor transform for the given provider URL

func (*VendorTransform) Apply

func (t *VendorTransform) Apply(ctx *TransformContext) error

Apply applies vendor-specific transformations to the request

func (*VendorTransform) Name

func (t *VendorTransform) Name() string

Name returns the transform name

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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