api

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 45 Imported by: ? 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

pi: api/anthropic-messages.ts — the workload identity federation half of the createClient path (#10242). pi delegates the exchange to the Anthropic SDK's `config: {authentication: {type: "oidc_federation"}}` support; pig's adapter is hand-written HTTP, so the SDK's exchange, token parsing, and two-tier TokenCache are reproduced natively here against the same wire contract (POST {base}/v1/oauth/token, RFC 7523 jwt-bearer grant).

pi: api/anthropic-messages.ts.

The anthropic-messages wire adapter. It covers Anthropic and Anthropic-compatible endpoints (DeepSeek /anthropic, kimi-coding, minimax, fireworks claude routes, ...). The @anthropic-ai/sdk (beta messages namespace, HTTP transport, SSE event:/data: parsing) has no Go counterpart: the request body is built as a plain JSON map and the SSE response stream is parsed locally. The SDK's betas create-param travels as the anthropic-beta request header, exactly like the SDK sends it.

pi: api/anthropic-messages.ts (convertToolResult, convertMessages, insertThinkingLevelMessages, convertTools, mapStopReason). Same TS source file as anthropic_messages.go; split for readability, package api.

pi: api/azure-openai-responses.ts.

The azure-openai-responses wire adapter: the openai-responses event protocol over Azure's deployment/api-version URL conventions. The AzureOpenAI SDK has no Go counterpart: the request body is built as a plain JSON map, the api-key header replaces the SDK's auth, and the SSE stream is parsed locally (shared reducer: ProcessResponsesStream).

pi: api/bedrock-converse-stream.ts.

The AWS Bedrock Converse Stream wire adapter. pi goes through @aws-sdk/client-bedrock-runtime (BedrockRuntimeClient + ConverseStreamCommand); the SDK has no Go counterpart, so pig rewrites the exercised SDK surface natively on aws-sdk-go-v2 (C3/C4 "SDK rewrite" precedent):

  • transport: BedrockRuntimeClient.ConverseStream with SigV4 signing, the AWS credential chain, and the vnd.amazon.eventstream binary framing are carried by aws-sdk-go-v2. The client config pi puts into BedrockRuntimeClientConfig (profile / region / endpoint / static credentials / bearer token / proxy handler) is mirrored field-for-field into bedrockClientConfig; tests capture it through the bedrockNewClient seam exactly like pi's vi.mock of the SDK module.

  • region: ARN-embedded > explicit option/env > endpoint-derived > the us-east-1 fallback (pi's Node branch; the browser branch is unreachable in pig). Standard bedrock-runtime endpoints are only pinned when no region or ambient AWS_PROFILE is configured (pi #3402/#6957).

  • auth: bearer token (options.bearerToken / apiKey / AWS_BEARER_TOKEN_BEDROCK, httpBearerAuth), AWS_BEDROCK_SKIP_AUTH dummy credentials, static env keys, or the SDK default chain. A profile configured through pi (the profile option or scoped AWS_PROFILE) must beat ambient env keys (pi #6957); the Go SDK chain prefers env keys, so static-key profiles are re-resolved from the shared profile (role/SSO profiles fall back to the SDK chain — declared deviation, see bedrockProfileCredentialsProvider).

  • middleware: caller headers ride a Smithy build-step middleware (signed; reserved headers skipped); onResponse receives the raw Smithy response at the deserialize step, with the $metadata fallback pi implements.

  • retry: pi relies on the JS SDK's default retry mode (3 attempts); pig relies on the Go SDK's default retryer (3 attempts) — equal counts, no pi-level options.MaxRetries wiring (pi also ignores it for bedrock).

  • AWS_BEDROCK_FORCE_HTTP1 is accepted for parity but is a no-op: the Go SDK speaks HTTP/1.1 by default (pi forces NodeHttpHandler because the JS SDK switched to HTTP/2 in 3.798.0).

  • errors: the Go SDK folds the raw HTTP body into the smithy APIError message, so formatBedrockError always stays on the message path (pi's status:body branch reads $response.body, which the Go SDK does not retain on the error).

pi: api/cloudflare.ts — Cloudflare endpoint URL constants. The {CLOUDFLARE_ACCOUNT_ID} / {CLOUDFLARE_GATEWAY_ID} placeholders materialize from the resolved provider env (pi: providers/cloudflare-stream.ts resolveCloudflareModel, ported in ai/providers/cloudflare_stream.go).

pi: api/constrained-sampling.ts.

Package api will host the wire-protocol adapters (pi: src/api/*.ts, one file per API). They are a leaf above package ai: adapters implement ai.ProviderStreams against the exported ai API, so the subpackage can import ai without a cycle. api/lazy.ts is the one exception: models.go consumes it, so it lives in package ai as lazy.go.

pi: api/github-copilot-headers.ts.

pi: api/google-generative-ai.ts.

The Google Generative AI (Gemini API) wire adapter. pi goes through the @google/genai SDK (client.models.generateContentStream); the SDK has no Go counterpart, so the transport below is a native rewrite of the SDK surface pi exercises (pi: createClient + generateContentStream):

  • POST {baseUrl}[/{apiVersion}]/models/{model}:streamGenerateContent?alt=sse (pi: ApiClient.constructUrl + tModel — the model id is prefixed with "models/" unless it already starts with models/|tunedModels/, and the apiVersion segment is skipped when empty, which is how a model.baseUrl that already includes the version composes);
  • headers: x-goog-api-key from the apiKey (pi: ApiKeyAuth addAuthHeaders) plus the httpOptions.headers set (User-Agent + model headers + options headers) and Content-Type: application/json;
  • body: the mldev mapping of GenerateContentParameters (pi: generateContentParametersToMldev — contents pass through; config's systemInstruction/tools/toolConfig hoist to the top level, the rest go under generationConfig);
  • response: SSE data lines, each a GenerateContentResponse JSON chunk.

pi: api/google-shared.ts.

Shared utilities for the Google Generative AI adapter (and, later, the Google Vertex adapter). The @google/genai SDK types (Content, Part, FinishReason, FunctionCallingConfigMode) have no Go counterpart: the wire structs below mirror the SDK shapes the adapter reads and writes, and the enum values are the SDK's string values.

pi: api/google-vertex.ts.

The Google Vertex AI wire adapter. pi goes through the @google/genai SDK (client.models.generateContentStream with vertexai: true); the SDK has no Go counterpart, so the transport below is a native rewrite of the SDK surface pi exercises:

  • URL: the SDK's ApiClient constructor + constructUrl + shouldPrependVertexProjectPath. Default base URL by auth shape — express (apiKey) or location "global" → https://aiplatform.googleapis.com/, multi-regional us/eu → https://aiplatform.{location}.rep.googleapis.com/, otherwise https://{location}-aiplatform.googleapis.com/; a model.baseUrl that does not contain the {location} placeholder overrides it (pi: ResourceScope.COLLECTION — the project/location path prefix is then dropped). apiVersion is "v1" (pi: API_VERSION) unless the custom base URL already carries a v<digits>[beta] segment, in which case the version segment is skipped. The model path is the SDK's vertex tModel mapping: publishers/google/models/{id} for catalog ids.
  • headers: content-type: application/json, the httpOptions headers (User-Agent + model headers + options headers) and the auth header — x-goog-api-key for express API keys, Authorization: Bearer for ADC (pi: google-auth-library GoogleAuth with the cloud-platform scope). The SDK's x-goog-api-client telemetry header is not replicated (declared deviation; endpoints do not require it).
  • auth: ADC resolves GOOGLE_APPLICATION_CREDENTIALS (service account or authorized_user), then the gcloud well-known file ~/.config/gcloud/application_default_credentials.json, then the GCE metadata server (pi: google-auth-library's chain). Tokens are cached by credential until expiry (google-auth-library's client cache equivalent).
  • body: the vertex mapping of GenerateContentParameters — identical to the mldev mapping for the surface pi uses (contents pass through; config's systemInstruction/tools/toolConfig hoist to the top level, temperature/maxOutputTokens/thinkingConfig stay under generationConfig).
  • response: SSE data lines, each a GenerateContentResponse JSON chunk.

The SDK's internal pRetry fetch loop (5 attempts on 408/429/5xx) is not replicated: the pi-level retryGoogleRequest wrapping the request provides the equivalent policy at the adapter boundary (same declared deviation as the google-generative-ai transport).

pi: api/openai-codex-responses.ts.

The ChatGPT Codex Responses wire adapter: the openai-responses event protocol over chatgpt.com/backend-api with ChatGPT OAuth tokens, SSE + WebSocket transports, zstd request compression, and Codex-specific retry and fallback semantics. The request body is built as a plain JSON map and both transports are parsed locally (shared reducer: ProcessResponsesStream).

Transport deviations (declared):

  • pi constructs a runtime WebSocket via the global WebSocket class and stubs it in tests; pig dials via gorilla/websocket behind the codexDialWebSocket seam variable (tests override the var, the closest analog of stubbing a global).
  • pi's connectWebSocket deletes the "OpenAI-Beta" header from a lowercased headers record with a case-sensitive key — a no-op, so the header actually ships on the handshake. pig never deletes it.
  • "WebSocket transport is not available in this runtime" (pi: missing global WebSocket) is unreachable in Go; no counterpart.

pi: api/openai-completions.ts.

The openai-completions wire adapter. It covers openai, openrouter, deepseek, and any OpenAI-shaped endpoint. The openai npm SDK (chat completions request/response types, HTTP transport, SSE parsing) has no Go counterpart: the request body is built as a plain JSON map and the SSE response stream is parsed locally.

pi: api/openai-completions.ts (compatibility auto-detection + options resolution). Same TS source file as openai_completions.go; split for readability, package api.

pi: api/openai-completions.ts (message/tool conversion + usage parsing). Same TS source file as openai_completions.go; split for readability, package api.

pi: api/openai-completions.ts (stream, streamSimple helpers, buildParams, SSE chunk processing). Same TS source file as openai_completions.go; split for readability, package api.

pi: api/openai-prompt-cache.ts.

pi: api/openai-responses.ts.

The openai-responses wire adapter. It covers OpenAI, xAI, OpenRouter, proxies, and any Responses-shaped endpoint. The openai SDK (responses namespace, HTTP transport, SSE parsing) has no Go counterpart: the request body is built as a plain JSON map and the SSE response stream is parsed locally. Responses SSE frames are `event:`/`data:` pairs whose data JSON carries the discriminating `type` field, so the data line alone drives the reducer (shared with openai_completions' SSE framing).

pi: api/openai-responses-shared.ts.

Message/tool conversion and SSE event reduction shared by the openai-responses adapter (and reused by the Azure / Codex Responses variants as they arrive). The openai SDK's ResponseInput / ResponseStreamEvent types have no Go counterpart: input items are built as JSON maps and stream events are decoded locally. Reasoning items replay verbatim: the raw JSON received on output_item.done is stored as the thinking block's signature and pushed back into the input untouched (pi: JSON.parse(block.thinkingSignature) of JSON.stringify(item)).

The stream reducer mirrors pi's shared-array invariant via the same snapshot mechanism as openai_completions_stream.go (declared deviation: events carry a content snapshot at push time, not a live view).

pi: api/simple-options.ts.

pi: api/transform-messages.ts.

Index

Constants

View Source
const (
	// CloudflareWorkersAIBaseURL is the Workers AI direct endpoint.
	CloudflareWorkersAIBaseURL = "https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1"

	// CloudflareAIGatewayCompatBaseURL is the AI Gateway Unified API.
	// https://developers.cloudflare.com/ai-gateway/usage/unified-api/
	CloudflareAIGatewayCompatBaseURL = "https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/compat"

	// CloudflareAIGatewayOpenAIBaseURL is the AI Gateway → OpenAI passthrough.
	// Used until /compat supports /v1/responses.
	CloudflareAIGatewayOpenAIBaseURL = "https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai"

	// CloudflareAIGatewayAnthropicBaseURL is the AI Gateway → Anthropic
	// passthrough.
	CloudflareAIGatewayAnthropicBaseURL = "https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic"
)
View Source
const MinAnswerTokens = 1024

MinAnswerTokens is the tokens always left for the answer when a thinking budget shares the response ceiling (pi: MIN_ANSWER_TOKENS).

View Source
const OpenAIPromptCacheKeyMaxLength = 64

OpenAIPromptCacheKeyMaxLength is the maximum prompt_cache_key length (pi: OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH).

Variables

View Source
var UNSUPPORTED_STRICT_SCHEMA_KEYS = []string{
	"$ref", "$defs", "definitions", "allOf", "oneOf", "patternProperties",
	"dependentSchemas", "dependencies", "unevaluatedProperties", "propertyNames",
	"contains", "prefixItems", "not", "if", "then", "else",
}

Functions

func AdjustMaxTokensForThinking

func AdjustMaxTokensForThinking(baseMaxTokens *int64, modelMaxTokens int64, reasoningLevel types.ThinkingLevel, customBudgets *types.ThinkingBudgets) (maxTokens int64, thinkingBudget int64)

AdjustMaxTokensForThinking fits a thinking budget inside the response ceiling (pi: adjustMaxTokensForThinking). A nil baseMaxTokens means no explicit caller cap: use the model cap and fit thinking inside it.

func AppendGrammarToolInputJSONDelta

func AppendGrammarToolInputJSONDelta(buffer *GrammarToolInputJSONBuffer, inputProperty, nextInput string, close bool) (*string, error)

AppendGrammarToolInputJSONDelta appends the next streamed input, returning the JSON delta to emit (pi: appendGrammarToolInputJsonDelta). A nil return means no delta.

func BuildBaseOptions

func BuildBaseOptions(model *types.Model, context *types.TranscriptContext, options *types.SimpleStreamOptions, apiKey string) types.StreamOptions

BuildBaseOptions maps a SimpleStreamOptions into the StreamOptions shared by full streams (pi: buildBaseOptions). signal is intentionally absent (Go cancellation travels as context).

func BuildCopilotDynamicHeaders

func BuildCopilotDynamicHeaders(messages []types.Message, hasImages bool) map[string]string

BuildCopilotDynamicHeaders builds the Copilot-specific request headers (pi: buildCopilotDynamicHeaders).

func ClampMaxTokensToContext

func ClampMaxTokensToContext(model *types.Model, context *types.TranscriptContext, maxTokens int64) int64

ClampMaxTokensToContext caps max tokens to the context window minus the estimated context, keeping at least minMaxTokens (pi: clampMaxTokensToContext).

func ClampOpenAIPromptCacheKey

func ClampOpenAIPromptCacheKey(key string) string

ClampOpenAIPromptCacheKey truncates a prompt cache key to the maximum length, counting code points (pi: clampOpenAIPromptCacheKey).

func ClampReasoning

func ClampReasoning(effort types.ThinkingLevel) types.ThinkingLevel

ClampReasoning folds the two top reasoning levels into "high" (pi: clampReasoning).

func ClampThinkingBudgetToAnswerRoom

func ClampThinkingBudgetToAnswerRoom(thinkingBudget int64, ceiling int64) int64

ClampThinkingBudgetToAnswerRoom caps a thinking budget so at least MinAnswerTokens remain under a shared response ceiling (pi: clampThinkingBudgetToAnswerRoom).

func CloseOpenAICodexWebSocketSessions

func CloseOpenAICodexWebSocketSessions(sessionIDs ...string)

CloseOpenAICodexWebSocketSessions closes pooled sockets; with no argument it closes everything (pi: closeOpenAICodexWebSocketSessions).

func ConvertGoogleMessages

func ConvertGoogleMessages(model *types.Model, llmContext *types.TranscriptContext) []googleContent

ConvertGoogleMessages converts internal messages to Gemini Content[] format (pi: convertMessages).

func ConvertGoogleTools

func ConvertGoogleTools(tools []types.Tool, useParameters bool, supportsStrictMode bool) ([]googleToolWrapper, error)

ConvertGoogleTools converts tools to Gemini function declarations format (pi: convertTools). By default uses `parametersJsonSchema` which supports full JSON Schema (including anyOf, oneOf, const, etc.); useParameters=true switches to the legacy `parameters` field (OpenAPI 3.03 Schema). This is needed for Cloud Code Assist with Claude models, where the API translates `parameters` into Anthropic's `input_schema`.

func ConvertResponsesMessages

func ConvertResponsesMessages(model *types.Model, llmContext *types.TranscriptContext, allowedToolCallProviders map[string]struct{}, options *ConvertResponsesMessagesOptions) []any

ConvertResponsesMessages converts the LLM context into Responses API input items (pi: convertResponsesMessages). AllowedToolCallProviders carries the provider ids whose tool-call ids keep their call_id|item_id pair shape.

func ConvertResponsesTools

func ConvertResponsesTools(tools []types.Tool, options *ConvertResponsesToolsOptions) []any

ConvertResponsesTools converts tool definitions into Responses API tool objects: custom grammar tools or function tools (pi: convertResponsesTools).

func CreateGrammarToolInputProperties

func CreateGrammarToolInputProperties(tools []types.Tool, supportsOpenAIGrammarTools bool) map[string]string

CreateGrammarToolInputProperties maps each grammar-constrained tool name to its input property (pi: createGrammarToolInputProperties).

func DefaultThinkingBudgets

func DefaultThinkingBudgets() types.ThinkingBudgets

DefaultThinkingBudgets is the token budget per thinking level (pi: DEFAULT_THINKING_BUDGETS).

func GetDisabledGoogleThinkingConfig added in v0.86.0

func GetDisabledGoogleThinkingConfig(model *types.Model) *googleThinkingConfig

GetDisabledGoogleThinkingConfig builds the thinking config used when thinking is disabled: level-based models fall back to the lowest supported level from their thinkingLevelMap; budget-based models disable via thinkingBudget 0 (pi: getDisabledGoogleThinkingConfig, v0.86.0 — "avoid unsupported Gemini thinking levels").

func GetGrammarToolInput

func GetGrammarToolInput(toolName string, arguments map[string]any, inputProperty string) (string, error)

GetGrammarToolInput extracts the grammar tool's string argument (pi: getGrammarToolInput).

func GetJSONSchemaToolParameters

func GetJSONSchemaToolParameters(tool *types.Tool, strict bool) (json.RawMessage, error)

GetJSONSchemaToolParameters returns the tool parameters, made strict when strict is true (pi: getJsonSchemaToolParameters).

func HasCopilotVisionInput

func HasCopilotVisionInput(messages []types.Message) bool

HasCopilotVisionInput reports whether the messages include images (pi: hasCopilotVisionInput); Copilot requires the Copilot-Vision-Request header then.

func InferCopilotInitiator

func InferCopilotInitiator(messages []types.Message) string

InferCopilotInitiator reports whether the request is user-initiated or agent-initiated (pi: inferCopilotInitiator). Copilot expects X-Initiator to indicate it: a trailing non-user message marks an agent-initiated follow-up.

func IsThinkingPart

func IsThinkingPart(part *googlePart) bool

IsThinkingPart determines whether a streamed Gemini part should be treated as "thinking" (pi: isThinkingPart). thought === true is the definitive marker for thinking content (thought summaries); thoughtSignature is an encrypted representation of the model's internal thought process used to preserve reasoning context across multi-turn interactions, and it can appear on ANY part type (text, functionCall, ...) without making the part thinking content. See: https://ai.google.dev/gemini-api/docs/thought-signatures

func MakeStrictJSONSchema

func MakeStrictJSONSchema(schema json.RawMessage, isUnsupportedKeyword UnsupportedStrictSchemaKeywordCheck) (map[string]any, error)

MakeStrictJSONSchema converts a tool schema to the strict subset expected by provider constrained sampling (pi: makeStrictJsonSchema). Property order follows the schema document (pi: Object.keys).

func MapGoogleStopReason

func MapGoogleStopReason(reason string) (types.StopReason, error)

MapGoogleStopReason maps a Gemini FinishReason to our StopReason (pi: mapStopReason). An unhandled reason mirrors pi's exhaustive-switch throw, which the adapter's catch turns into the stream error.

func MapGoogleStopReasonString

func MapGoogleStopReasonString(reason string) types.StopReason

MapGoogleStopReasonString maps a string finish reason to our StopReason for raw API responses (pi: mapStopReasonString).

func ProcessResponsesStream

func ProcessResponsesStream(events iter.Seq[*responsesStreamEvent], output *types.AssistantMessage, stream *types.AssistantMessageEventStream, model *types.Model, options *OpenAIResponsesStreamOptions) error

ProcessResponsesStream reduces the Responses SSE event sequence into AssistantMessageEvents (pi: processResponsesStream). events yields decoded events in wire order.

func RequiresToolCallId

func RequiresToolCallId(modelID string) bool

RequiresToolCallId reports whether a model via Google APIs requires explicit tool call IDs in function calls/responses (pi: requiresToolCallId).

func ResetOpenAICodexWebSocketDebugStats

func ResetOpenAICodexWebSocketDebugStats(sessionIDs ...string)

ResetOpenAICodexWebSocketDebugStats clears debug stats and SSE-fallback markers; with no argument it clears everything (pi: resetOpenAICodexWebSocketDebugStats).

func ResolveGoogleFunctionCallingMode

func ResolveGoogleFunctionCallingMode(tools []types.Tool, toolChoice string, supportsStrictMode bool) (string, error)

ResolveGoogleFunctionCallingMode resolves the tool config mode (pi: resolveGoogleFunctionCallingMode). The error mirrors pi's resolveJsonSchemaStrictSampling throw for strict tools on non-strict models.

func ResolveGoogleThinkingLevel

func ResolveGoogleThinkingLevel(model *types.Model, level types.ModelThinkingLevel) (types.ModelThinkingLevel, error)

ResolveGoogleThinkingLevel resolves a supported pi level or model-specific Google mapping to a standard Google level (pi: resolveGoogleThinkingLevel). The returned level is one of minimal/low/medium/high. The "off" level is handled by the callers (v0.86.0: they disable thinking explicitly instead of silently mapping off → high).

func ResolveJSONSchemaStrictSampling

func ResolveJSONSchemaStrictSampling(tool *types.Tool, supportsStrictMode bool, isUnsupportedKeyword UnsupportedStrictSchemaKeywordCheck) (*bool, error)

ResolveJSONSchemaStrictSampling decides whether a tool's json_schema constrained sampling must be strict (pi: resolveJsonSchemaStrictSampling). A nil result means no strict constraint; an error means the tool requires strict sampling the provider cannot offer (pi throws in both cases). isUnsupportedKeyword lets a provider reject extra keywords its strict mode does not accept, so "prefer" tools fall back to non-strict.

func ResolveSamplingParams added in v1.0.2

func ResolveSamplingParams(model *types.Model, thinkingLevel types.ModelThinkingLevel, requestParams map[string]any) map[string]any

ResolveSamplingParams merges model defaults, the effective thinking level's overrides, and request-level params (later wins per key). thinkingLevel is clamped to the model's supported levels first; "" means off (pi: resolveSamplingParams, v1.0.2 #9776).

func RetainThoughtSignature

func RetainThoughtSignature(existing string, incoming string) string

RetainThoughtSignature retains thought signatures during streaming (pi: retainThoughtSignature): some backends only send the signature on the first delta for a given part/block; later deltas may omit it. This helper preserves the last non-empty signature for the current block without merging or moving signatures across distinct response parts.

func RetryGoogleRequest

func RetryGoogleRequest[T any](request func() (T, error), options GoogleRetryOptions) (T, error)

RetryGoogleRequest runs a Google request with the shared provider retry policy (pi: retryGoogleRequest — 408/409/429/5xx with backoff, honoring retry-after), mirroring how the Anthropic and OpenAI adapters wrap their initial request in retryProviderRequest. pi normalizes the SDK's headers-less ApiError by adding a missing `headers` field so retryProviderRequest classifies it; pig's transport already returns *utils.ProviderHTTPError (Headers may be nil, which the classifier accepts), so the wrapper is a direct pass-through.

func SupportsGoogleStrictToolSampling

func SupportsGoogleStrictToolSampling(modelID string) bool

SupportsGoogleStrictToolSampling reports whether Gemini 3+ enforces required function parameters in validated tool-calling modes (pi: supportsGoogleStrictToolSampling).

func ThinkingBudgetForLevel

func ThinkingBudgetForLevel(reasoningLevel types.ThinkingLevel, customBudgets *types.ThinkingBudgets) int64

ThinkingBudgetForLevel returns the token budget for a reasoning level, merging customBudgets over the defaults (pi: thinkingBudgetForLevel).

func TransformMessages

func TransformMessages(messages []types.Message, model *types.Model, normalizeToolCallID NormalizeToolCallIDFn) []types.Message

TransformMessages normalizes a message list for replay: downgrades unsupported images, converts thinking blocks, normalizes tool call ids, and inserts synthetic empty tool results for orphaned tool calls (pi: transformMessages).

func UsesGoogleThinkingLevel added in v0.86.0

func UsesGoogleThinkingLevel(model *types.Model) bool

UsesGoogleThinkingLevel reports whether this model uses Gemini's discrete thinkingLevel control instead of the token-based thinkingBudget control. Supported levels come from the model's thinkingLevelMap; this only selects the Google wire format (pi: usesGoogleThinkingLevel).

Types

type AnthropicEffort

type AnthropicEffort string

AnthropicEffort is the effort level of adaptive thinking models (pi: AnthropicEffort).

const (
	AnthropicEffortLow    AnthropicEffort = "low"
	AnthropicEffortMedium AnthropicEffort = "medium"
	AnthropicEffortHigh   AnthropicEffort = "high"
	AnthropicEffortXHigh  AnthropicEffort = "xhigh"
	AnthropicEffortMax    AnthropicEffort = "max"
)

type AnthropicMessages

type AnthropicMessages struct{}

AnthropicMessages implements ProviderStreams for the anthropic-messages API (pi: the { stream, streamSimple } module object).

func (AnthropicMessages) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation; pi passes options.signal into the SDK request options and the retry helper (pig: AbortSignal → context rule).

func (AnthropicMessages) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple).

type AnthropicOptions

type AnthropicOptions struct {
	types.StreamOptions
	// ThinkingEnabled enables extended thinking. For adaptive thinking
	// models: the model decides when/how much to think. For older models:
	// uses budget-based thinking with ThinkingBudgetTokens. Default: nil
	// (thinking is omitted unless StreamSimple maps a simple reasoning level
	// to it, or callers set it explicitly).
	ThinkingEnabled *bool
	// ThinkingBudgetTokens is the token budget for extended thinking (older
	// models only). Ignored for adaptive thinking models. Default: 1024
	// when ThinkingEnabled is true and no budget is provided.
	ThinkingBudgetTokens *int64
	// Effort is the effort level for adaptive thinking models:
	// "max" (Opus 4.6 only), "xhigh" (Opus 4.7+, Fable 5), "high" (always
	// thinks, deep reasoning), "medium" (may skip for simple queries),
	// "low" (minimal thinking). Ignored for older models. Default: empty =
	// omitted unless StreamSimple maps a reasoning level to it.
	Effort AnthropicEffort
	// ThinkingDisplay controls how thinking content is returned:
	// "summarized" (default when thinking is enabled) or "omitted" (empty
	// thinking text, faster time-to-first-text-token).
	ThinkingDisplay AnthropicThinkingDisplay
	// InterleavedThinking requests the interleaved thinking beta header for
	// non-adaptive thinking models. Adaptive thinking models have it built
	// in, so the header is skipped for them regardless. Default: true.
	InterleavedThinking *bool
	// ToolChoice is Anthropic tool choice behavior. Default: nil (provider
	// default, currently equivalent to auto).
	ToolChoice *AnthropicToolChoice
}

AnthropicOptions are the anthropic-messages request options (pi: AnthropicOptions extends StreamOptions).

type AnthropicThinkingDisplay

type AnthropicThinkingDisplay string

AnthropicThinkingDisplay controls how thinking content is returned (pi: AnthropicThinkingDisplay).

const (
	// AnthropicThinkingDisplaySummarized: thinking blocks carry summarized
	// thinking text.
	AnthropicThinkingDisplaySummarized AnthropicThinkingDisplay = "summarized"
	// AnthropicThinkingDisplayOmitted: thinking text is empty; the signature
	// still travels back for multi-turn continuity.
	AnthropicThinkingDisplayOmitted AnthropicThinkingDisplay = "omitted"
)

type AnthropicToolChoice

type AnthropicToolChoice struct {
	Type string `json:"type"` // "auto" | "any" | "none" | "tool"
	Name string `json:"name,omitempty"`
}

AnthropicToolChoice is Anthropic tool-choice behavior (pi: the "auto" | "any" | "none" | { type: "tool", name } union — string choices are modeled as Type with an empty Name).

type AzureOpenAIResponses

type AzureOpenAIResponses struct{}

AzureOpenAIResponses implements ProviderStreams for the azure-openai-responses API (pi: the { stream, streamSimple } module object).

func (AzureOpenAIResponses) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation (pi: options.signal).

func (AzureOpenAIResponses) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple).

type AzureOpenAIResponsesOptions

type AzureOpenAIResponsesOptions struct {
	types.StreamOptions
	// ReasoningEffort is the reasoning effort level. Empty means unset.
	ReasoningEffort types.ModelThinkingLevel
	// ToolChoice is the tool_choice request value (string choice or
	// per-tool object); nil means unset.
	ToolChoice any
	// ReasoningSummary is the reasoning summary mode; pi also allows null,
	// which pig folds into "" (both default to "auto").
	ReasoningSummary string
	// AzureAPIVersion overrides the api-version query param. Default: env
	// AZURE_OPENAI_API_VERSION, else "v1".
	AzureAPIVersion string
	// AzureResourceName builds https://<name>.openai.azure.com/openai/v1
	// when no explicit base URL is available.
	AzureResourceName string
	// AzureBaseURL overrides the model's base URL.
	AzureBaseURL string
	// AzureDeploymentName overrides the deployment name (default: model id,
	// or the AZURE_OPENAI_DEPLOYMENT_NAME_MAP entry).
	AzureDeploymentName string
}

AzureOpenAIResponsesOptions are the azure-openai-responses request options (pi: AzureOpenAIResponsesOptions extends StreamOptions).

type BedrockConverseStream

type BedrockConverseStream struct{}

BedrockConverseStream implements ProviderStreams for the bedrock-converse-stream API (pi: the { stream, streamSimple } module object).

func (BedrockConverseStream) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation (pi: options.signal into client.send).

func (BedrockConverseStream) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple).

type BedrockOptions

type BedrockOptions struct {
	types.StreamOptions
	// Region is the AWS region for the request; falls back to AWS_REGION /
	// AWS_DEFAULT_REGION / the model endpoint / the SDK default chain.
	Region string
	// Profile selects a shared-config profile; also settable through the
	// scoped AWS_PROFILE (pi: profile).
	Profile string
	// ToolChoice is "auto", "any", "none", or a named tool.
	ToolChoice *BedrockToolChoice
	// Reasoning requests thinking for models that support it (pi: reasoning).
	// See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html
	// for supported models.
	Reasoning types.ThinkingLevel
	// ThinkingBudgets are custom token budgets per thinking level; overrides
	// the default budgets (pi: thinkingBudgets).
	ThinkingBudgets *types.ThinkingBudgets
	// InterleavedThinking requests the interleaved-thinking beta for
	// non-adaptive Claude thinking. Only supported by Claude 4.x models, see
	// https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-extended-thinking.html#claude-messages-extended-thinking-tool-use-interleaved.
	// Default: true.
	InterleavedThinking *bool
	// ThinkingDisplay controls how Claude's thinking content is returned (pi:
	// thinkingDisplay). Default: "summarized".
	ThinkingDisplay BedrockThinkingDisplay
	// RequestMetadata attaches key-value pairs to the inference request for
	// cost allocation tagging. Keys: max 64 chars, no `aws:` prefix. Values:
	// max 256 chars. Max 50 pairs. Tags appear in AWS Cost Explorer split
	// cost allocation data.
	// @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html
	RequestMetadata map[string]string
	// BearerToken is the Bedrock API key for bearer authentication. When set,
	// SigV4 signing is bypassed and Authorization: Bearer <token> is sent
	// instead; requires `bedrock:CallWithBearerToken` IAM permission on the
	// token's identity. Set via AWS_BEARER_TOKEN_BEDROCK env var or passed
	// directly.
	// @see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html
	BearerToken string
}

BedrockOptions are the bedrock-converse-stream request options (pi: BedrockOptions extends StreamOptions).

type BedrockThinkingDisplay

type BedrockThinkingDisplay string

BedrockThinkingDisplay controls how Claude thinking content is returned (pi: BedrockThinkingDisplay):

  • "summarized": thinking blocks contain summarized thinking text (default).
  • "omitted": thinking is redacted but the signature still travels back for multi-turn continuity, reducing time-to-first-text-token.

pi's note carries over: Anthropic's API default for Claude Opus 4.8 and Mythos Preview is "omitted"; pi defaults to "summarized" for consistency with older Claude 4 models. Only applies to Claude models on Bedrock.

const (
	BedrockThinkingDisplaySummarized BedrockThinkingDisplay = "summarized"
	BedrockThinkingDisplayOmitted    BedrockThinkingDisplay = "omitted"
)

type BedrockToolChoice

type BedrockToolChoice struct {
	Type string `json:"type"` // "auto" | "any" | "none" | "tool"
	Name string `json:"name,omitempty"`
}

BedrockToolChoice is the bedrock tool-choice behavior (pi: BedrockOptions toolChoice, the "auto" | "any" | "none" | { type: "tool", name } union — string choices are modeled as Type with an empty Name).

type CodexWebSocketDebugStats

type CodexWebSocketDebugStats struct {
	Requests                int
	ConnectionsCreated      int
	ConnectionsReused       int
	CachedContextRequests   int
	StoreTrueRequests       int
	FullContextRequests     int
	DeltaRequests           int
	LastInputItems          int
	LastDeltaInputItems     *int
	LastPreviousResponseID  *string
	WebSocketFailures       int
	SSEFallbacks            int
	WebsocketFallbackActive *bool
	LastWebSocketError      *string
}

CodexWebSocketDebugStats are the per-session WebSocket debug counters (pi: OpenAICodexWebSocketDebugStats).

func GetOpenAICodexWebSocketDebugStats

func GetOpenAICodexWebSocketDebugStats(sessionID string) *CodexWebSocketDebugStats

GetOpenAICodexWebSocketDebugStats returns a copy of the session's debug stats, or nil (pi: getOpenAICodexWebSocketDebugStats).

type ConvertCompletionsMessagesOptions

type ConvertCompletionsMessagesOptions struct {
	GrammarToolInputProperties map[string]string
}

ConvertCompletionsMessagesOptions are the convertMessages extras (pi: ConvertCompletionsMessagesOptions).

type ConvertResponsesMessagesOptions

type ConvertResponsesMessagesOptions struct {
	IncludeSystemPrompt        *bool
	GrammarToolInputProperties map[string]string
	// SupportsMidConvoSystemMessages: whether later system messages are sent
	// in place; otherwise they are folded into the leading prompt.
	SupportsMidConvoSystemMessages *bool
	SupportsAdditionalTools        *bool
	SupportsToolSearch             *bool
	ToolOptions                    *ConvertResponsesToolsOptions
}

ConvertResponsesMessagesOptions are the message-conversion options (pi: ConvertResponsesMessagesOptions).

type ConvertResponsesToolsOptions

type ConvertResponsesToolsOptions struct {
	Strict *bool
	// StrictNull expresses pi's strict: null: the default strict value is
	// null, serialized as JSON null on tools without constrained sampling
	// (constrained sampling still overrides with a boolean). Mutually
	// exclusive with Strict.
	StrictNull                 bool
	SupportsStrictMode         *bool
	SupportsOpenAIGrammarTools *bool
	ToolSearchResult           bool
}

ConvertResponsesToolsOptions are the tool-conversion options (pi: ConvertResponsesToolsOptions). pi's strict member is boolean|null; the openai-responses adapters never pass it (nil resolves to false, pi's undefined path); the Codex adapter passes null via StrictNull.

type GoogleApiThinkingLevel

type GoogleApiThinkingLevel string

GoogleApiThinkingLevel is the thinking level for Gemini 3 models (pi: GoogleApiThinkingLevel — mirrors Google's ThinkingLevel enum values).

const (
	GoogleThinkingLevelUnspecified GoogleApiThinkingLevel = "THINKING_LEVEL_UNSPECIFIED"
	GoogleThinkingLevelMinimal     GoogleApiThinkingLevel = "MINIMAL"
	GoogleThinkingLevelLow         GoogleApiThinkingLevel = "LOW"
	GoogleThinkingLevelMedium      GoogleApiThinkingLevel = "MEDIUM"
	GoogleThinkingLevelHigh        GoogleApiThinkingLevel = "HIGH"
)

func ToGoogleThinkingLevel added in v0.86.0

func ToGoogleThinkingLevel(level types.ModelThinkingLevel) GoogleApiThinkingLevel

ToGoogleThinkingLevel maps a resolved pi level to the Google API level (pi: toGoogleThinkingLevel).

type GoogleGenerativeAI

type GoogleGenerativeAI struct{}

GoogleGenerativeAI implements ProviderStreams for the google-generative-ai API (pi: the { stream, streamSimple } module object).

func (GoogleGenerativeAI) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation (pi: options.signal into the SDK request and the retry helper).

func (GoogleGenerativeAI) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple).

type GoogleOptions

type GoogleOptions struct {
	types.StreamOptions
	// ToolChoice is "auto", "none", or "any".
	ToolChoice string
	// Thinking configures thinking; BudgetTokens is -1 for dynamic, 0 to
	// disable; Level mirrors Google's ThinkingLevel enum values.
	Thinking *GoogleThinkingOptions
}

GoogleOptions are the google-generative-ai request options (pi: GoogleOptions extends StreamOptions).

type GoogleRetryOptions

type GoogleRetryOptions struct {
	MaxRetries      int
	MaxRetryDelayMs *int64
	Ctx             context.Context
}

GoogleRetryOptions are RetryGoogleRequest's knobs (pi: the Pick<StreamOptions, "maxRetries" | "maxRetryDelayMs" | "signal"> shape; signal → ctx).

type GoogleThinkingOptions

type GoogleThinkingOptions struct {
	Enabled      bool
	BudgetTokens *int64
	Level        GoogleApiThinkingLevel
}

GoogleThinkingOptions is the thinking member of GoogleOptions (pi: the inline thinking object).

type GoogleVertex

type GoogleVertex struct{}

GoogleVertex implements ProviderStreams for the google-vertex API (pi: the { stream, streamSimple } module object).

func (GoogleVertex) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation (pi: options.signal into the SDK request, buildParams pre-check and the retry helper).

func (GoogleVertex) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple). Unlike the google-generative-ai adapter there is no "no API key" throw: an absent key selects the ADC client.

type GoogleVertexOptions

type GoogleVertexOptions struct {
	types.StreamOptions
	// ToolChoice is "auto", "none", or "any".
	ToolChoice string
	// Thinking configures thinking; BudgetTokens is -1 for dynamic, 0 to
	// disable; Level mirrors Google's ThinkingLevel enum values.
	Thinking *GoogleThinkingOptions
	// Project is the GCP project ID; falls back to
	// GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT.
	Project string
	// Location is the GCP location; falls back to GOOGLE_CLOUD_LOCATION.
	Location string
}

GoogleVertexOptions are the google-vertex request options (pi: GoogleVertexOptions extends StreamOptions).

type GrammarConstrainedSampling

type GrammarConstrainedSampling struct {
	Format        string
	Definition    string
	InputProperty string
}

GrammarConstrainedSampling is the resolved grammar constraint of one tool (pi: GrammarConstrainedSampling).

func ResolveGrammarConstrainedSampling

func ResolveGrammarConstrainedSampling(tool *types.Tool, supportsOpenAIGrammarTools bool) (*GrammarConstrainedSampling, error)

ResolveGrammarConstrainedSampling resolves a tool's grammar constrained sampling, or nil when the provider cannot offer it (pi: resolveGrammarConstrainedSampling).

type GrammarToolInputJSONBuffer

type GrammarToolInputJSONBuffer struct {
	Input   string
	Started bool
	Closed  bool
}

GrammarToolInputJSONBuffer accumulates the streamed grammar tool input (pi: GrammarToolInputJsonBuffer).

type NormalizeToolCallIDFn

type NormalizeToolCallIDFn func(id string, model *types.Model, source *types.AssistantMessage) string

NormalizeToolCallIDFn normalizes a tool call id for cross-provider compatibility (pi: the optional normalizeToolCallId callback; OpenAI Responses API generates 450+ char ids with `|` separators that Anthropic APIs reject).

type OpenAICodexResponses

type OpenAICodexResponses struct{}

OpenAICodexResponses implements ProviderStreams for the openai-codex-responses API (pi: the { stream, streamSimple } module object).

func (OpenAICodexResponses) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation (pi: options.signal).

func (OpenAICodexResponses) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple).

type OpenAICodexResponsesOptions

type OpenAICodexResponsesOptions struct {
	types.StreamOptions
	// ReasoningEffort is the reasoning effort level (pi allows none through
	// max; "none" maps via thinkingLevelMap.off). Empty means unset.
	ReasoningEffort types.ModelThinkingLevel
	// ReasoningSummary is the reasoning summary mode; pi also allows null,
	// which pig folds into "" (both default to "auto").
	ReasoningSummary string
	// ServiceTier is the service_tier request value; empty means unset.
	ServiceTier string
	// TextVerbosity is the text.verbosity request value; empty defaults to
	// "low" (pi: options?.textVerbosity || "low").
	TextVerbosity string
	// ToolChoice is the tool_choice request value ("auto" | "none" |
	// "required"); defaults to "auto" (pi: options?.toolChoice ?? "auto").
	ToolChoice string
}

OpenAICodexResponsesOptions are the openai-codex-responses request options (pi: OpenAICodexResponsesOptions extends StreamOptions).

type OpenAICompletions

type OpenAICompletions struct{}

OpenAICompletions implements ProviderStreams for the openai-completions API (pi: the { stream, streamSimple } module object).

func (OpenAICompletions) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation; pi passes options.signal into the SDK request options and the retry helper (pig: AbortSignal → context rule, README §3.4).

func (OpenAICompletions) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple).

type OpenAICompletionsOptions

type OpenAICompletionsOptions struct {
	types.StreamOptions
	ToolChoice types.ToolChoice
	// ReasoningEffort is a model thinking level other than "off" (pi: the
	// Exclude<ModelThinkingLevel, "off"> union). Empty means unset.
	ReasoningEffort types.ModelThinkingLevel
	// ThinkingBudgets are token budgets per thinking level; used when compat
	// thinkingTokenBudgetField is set, or by { "$var": "thinking.budget" }.
	ThinkingBudgets *types.ThinkingBudgets
}

OpenAICompletionsOptions are the openai-completions request options (pi: OpenAICompletionsOptions extends StreamOptions).

type OpenAIResponses

type OpenAIResponses struct{}

OpenAIResponses implements ProviderStreams for the openai-responses API (pi: the { stream, streamSimple } module object).

func (OpenAIResponses) Stream

Stream dispatches one streaming request (pi: stream). ctx carries the caller's cancellation; pi passes options.signal into the SDK request options and the retry helper (pig: AbortSignal → context rule).

func (OpenAIResponses) StreamSimple

StreamSimple dispatches one simple streaming request (pi: streamSimple).

type OpenAIResponsesOptions

type OpenAIResponsesOptions struct {
	types.StreamOptions
	// ReasoningEffort is the reasoning effort level. Empty means unset.
	ReasoningEffort types.ModelThinkingLevel
	// ReasoningSummary is the reasoning summary mode ("auto" | "detailed" |
	// "concise"); pi also allows null, which pig folds into "" (both take
	// the else-if branch / default to "auto").
	ReasoningSummary string
	// ServiceTier is the service_tier request value ("auto" | "default" |
	// "flex" | "priority" | ...); empty means unset (pi: undefined).
	ServiceTier string
	// ToolChoice is the tool_choice request value: a string choice or a
	// per-tool object (pi: ResponseCreateParamsStreaming["tool_choice"]).
	ToolChoice any
}

OpenAIResponsesOptions are the openai-responses request options (pi: OpenAIResponsesOptions extends StreamOptions).

type OpenAIResponsesStreamOptions

type OpenAIResponsesStreamOptions struct {
	ServiceTier string
	// GrammarToolInputProperties maps grammar-constrained tool names to
	// their string input property (pi: grammarToolInputProperties).
	GrammarToolInputProperties map[string]string
	// ResolveServiceTier lets callers override the service tier applied to
	// pricing; nil uses the response tier, falling back to the request tier.
	ResolveServiceTier func(responseServiceTier, requestServiceTier string) string
	// ApplyServiceTierPricing adjusts usage cost for the served tier.
	ApplyServiceTierPricing func(usage *types.Usage, serviceTier string)
}

OpenAIResponsesStreamOptions are the stream-reduction options (pi: OpenAIResponsesStreamOptions). ServiceTier is the request's service_tier value ("flex" | "priority" | ...).

type ServerSentEvent

type ServerSentEvent struct {
	Event string
	Data  string
	Raw   []string
}

ServerSentEvent is one decoded SSE event (pi: ServerSentEvent). Event is empty when the frame carried no event line (pi: null).

type UnsupportedStrictJSONSchemaError

type UnsupportedStrictJSONSchemaError struct{ Message string }

UnsupportedStrictJSONSchemaError marks a schema that the strict subset cannot represent (pi: UnsupportedStrictJsonSchemaError).

func (*UnsupportedStrictJSONSchemaError) Error

type UnsupportedStrictSchemaKeywordCheck added in v1.0.0

type UnsupportedStrictSchemaKeywordCheck func(key string, value any) bool

UnsupportedStrictSchemaKeywordCheck returns true when a provider's strict mode rejects this schema keyword with this value (pi: UnsupportedStrictSchemaKeywordCheck).

Jump to

Keyboard shortcuts

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