1
import type { TelemetryContext } from "@earendil-works/pi-telemetry";2
import type { AnthropicOptions } from "./api/anthropic-messages.ts";3
import type { AzureOpenAIResponsesOptions } from "./api/azure-openai-responses.ts";4
import type { BedrockOptions } from "./api/bedrock-converse-stream.ts";5
import type { GoogleOptions } from "./api/google-generative-ai.ts";6
import type { GoogleVertexOptions } from "./api/google-vertex.ts";7
import type { MistralOptions } from "./api/mistral-conversations.ts";8
import type { OpenAICodexResponsesOptions } from "./api/openai-codex-responses.ts";9
import type { OpenAICompletionsOptions } from "./api/openai-completions.ts";10
import type { OpenAIResponsesOptions } from "./api/openai-responses.ts";11
import type { PiMessagesOptions } from "./api/pi-messages.ts";12
import type {13
AnthropicMessagesCompat,14
BedrockCompat,15
MistralConversationsCompat,16
OpenAICompletionsCompat,17
OpenAIResponsesCompat,18
} from "./providers/compat-schema.ts";19
import type {20
CacheRetention,21
ModelCost,22
ModelInputLimits,23
ModelInputModality,24
ModelPromptCache,25
ModelThinkingLevel,26
ThinkingLevel,27
ThinkingLevelMap,28
} from "./providers/model-schema.ts";29
import type { AssistantMessageDiagnostic } from "./utils/diagnostics.ts";30
import type { AssistantMessageEventStream } from "./utils/event-stream.ts";32
export type {33
AnthropicAllowedFallbackModel,34
AnthropicMessagesCompat,35
BedrockCompat,36
ChatTemplateKwargValue,37
MistralConversationsCompat,38
OpenAICompletionsCompat,39
OpenAIResponsesCompat,40
OpenRouterRouting,41
SessionAffinityFormat,42
ThinkingTokenBudgetField,43
VercelGatewayRouting,44
} from "./providers/compat-schema.ts";45
export type {46
CacheRetention,47
ModelCost,48
ModelCostRates,49
ModelCostTier,50
ModelImageInputLimits,51
ModelImageResizeOptions,52
ModelInputLimits,53
ModelInputModality,54
ModelPromptCache,55
ModelThinkingLevel,56
ThinkingLevel,57
ThinkingLevelMap,58
} from "./providers/model-schema.ts";59
export type { AssistantMessageEventStream } from "./utils/event-stream.ts";61
export type KnownApi =62
| "openai-completions"63
| "mistral-conversations"64
| "openai-responses"65
| "azure-openai-responses"66
| "openai-codex-responses"67
| "anthropic-messages"68
| "bedrock-converse-stream"69
| "google-generative-ai"70
| "google-vertex"71
| "pi-messages";73
export type Api = KnownApi | (string & {});75
export type KnownImageApi = "openrouter-images";77
export type ImageApi = KnownImageApi | (string & {});79
export type KnownClassifierApi =80
| "typesafe-system-one"81
| "cloudflare-workers-ai-system-one"82
| "llama-cpp-classify"83
| "openai-decisions";85
export type ClassifierApi = KnownClassifierApi | (string & {});87
export type KnownProvider =88
| "amazon-bedrock"89
| "ant-ling"90
| "anthropic"91
| "google"92
| "google-vertex"93
| "openai"94
| "azure"95
| "openai-codex"96
| "radius"97
| "typesafe"98
| "nvidia"99
| "deepseek"100
| "github-copilot"101
| "xai"102
| "groq"103
| "cerebras"104
| "openrouter"105
| "vercel-ai-gateway"106
| "zai"107
| "zai-coding-cn"108
| "mistral"109
| "minimax"110
| "minimax-cn"111
| "moonshotai"112
| "moonshotai-cn"113
| "huggingface"114
| "fireworks"115
| "together"116
| "baseten"117
| "opencode"118
| "opencode-go"119
| "kimi-coding"120
| "meta"121
| "cloudflare-workers-ai"122
| "cloudflare-ai-gateway"123
| "qwen-token-plan"124
| "qwen-token-plan-cn"125
| "qwen-token-plan-individual"126
| "xiaomi"127
| "xiaomi-token-plan-cn"128
| "xiaomi-token-plan-ams"129
| "xiaomi-token-plan-sgp";130
export type ProviderId = KnownProvider | string;132
export type ToolChoice = "auto" | "none";133
export type SamplingParams = Record<string, unknown>;134
export type SamplingParamsByThinkingLevel = Partial<Record<ModelThinkingLevel, SamplingParams>>;135
/** Token budgets for each thinking level (token-based providers only) */136
export interface ThinkingBudgets {137
minimal?: number;138
low?: number;139
medium?: number;140
high?: number;141
}143
// Base options all providers share144
export type Transport = "sse" | "websocket" | "websocket-cached" | "auto";146
/** Provider-scoped environment overrides. Values take precedence over process.env. */147
export type ProviderEnv = Record<string, string>;148
export type ProviderHeaders = Record<string, string | null>;149
export type FetchFunction = typeof globalThis.fetch;151
export interface ProviderResponse {152
status: number;153
headers: Record<string, string>;154
}156
/** Authentication, HTTP transport, and lifecycle callbacks shared by provider requests. */157
export interface ProviderRequestOptions<TModel = Model<Api>> {158
signal?: AbortSignal;159
/** Explicit parent context for telemetry produced by this logical request. */160
telemetryContext?: TelemetryContext;161
apiKey?: string;162
/**163
* Optional fetch implementation for provider HTTP requests.164
* Defaults to `globalThis.fetch`. Provider adapters that cannot inject a custom implementation may reject it.165
* This does not affect WebSocket transports.166
*/167
fetch?: FetchFunction;168
/**169
* Provider-scoped environment values. These take precedence over process.env for170
* provider configuration such as regional settings, endpoint placeholders, and171
* proxy variables.172
*/173
env?: ProviderEnv;174
/**175
* Optional callback for inspecting or replacing provider payloads before sending.176
* Return undefined to keep the payload unchanged.177
*/178
onPayload?: (payload: unknown, model: TModel) => unknown | undefined | Promise<unknown | undefined>;179
/**180
* Optional callback invoked after an HTTP response is received.181
*/182
onResponse?: (response: ProviderResponse, model: TModel) => void | Promise<void>;183
/**184
* Optional custom HTTP headers to include in API requests.185
* Merged with provider defaults; caller values override default headers.186
* On AWS Bedrock these are injected via a Smithy `build`-step middleware so187
* they are covered by SigV4 signing; reserved headers (`x-amz-*`,188
* `authorization`, `host`) are silently ignored to preserve SigV4 / bearer auth.189
* A null value suppresses a provider/API default header with the same name.190
*/191
headers?: ProviderHeaders;192
/**193
* HTTP request timeout in milliseconds for providers/SDKs that support it.194
* For example, OpenAI and Anthropic SDK clients default to 10 minutes.195
*/196
timeoutMs?: number;197
/**198
* Maximum retry attempts for providers/SDKs that support client-side retries.199
* For example, OpenAI and Anthropic SDK clients default to 2.200
*/201
maxRetries?: number;202
/**203
* Maximum delay in milliseconds to wait for a retry when the server requests a long wait.204
* If the server's requested delay exceeds this value, the request fails immediately205
* with an error containing the requested delay, allowing higher-level retry logic206
* to handle it with user visibility.207
* Default: 60000 (60 seconds). Set to 0 to disable the cap.208
*/209
maxRetryDelayMs?: number;210
}212
export interface StreamOptions extends ProviderRequestOptions<Model<Api>> {213
/**214
* Optional callback invoked after an HTTP response is received and before215
* its body stream is consumed.216
*/217
onResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;218
/**219
* Optional observer for each parsed provider stream event before Pi normalization.220
* Event data is adapter-owned and must be treated as read-only.221
* Adapter support is explicit; unsupported adapters do not invoke it.222
*/223
onProviderStreamEvent?: (data: unknown, model: Model<Api>) => void | Promise<void>;224
temperature?: number;225
/**226
* Arbitrary sampling parameters merged into the request body as-is, after the named request227
* fields, so keys here override them. Lets custom OpenAI-compatible servers (llama.cpp, vLLM,228
* SGLang, ...) receive parameters pi does not model, e.g. `top_p`, `top_k`, `min_p`,229
* `repetition_penalty`. Merged over `Model.samplingParams` per key. Only applied by230
* OpenAI-compatible adapters (completions, responses, Azure responses); other APIs ignore it.231
*/232
samplingParams?: SamplingParams;233
maxTokens?: number;234
/**235
* Preferred transport for providers that support multiple transports.236
* Providers that do not support this option ignore it.237
*/238
transport?: Transport;239
/**240
* Prompt cache retention preference. Providers map this to their supported values.241
* Default: "short".242
*/243
cacheRetention?: CacheRetention;244
/**245
* Optional session identifier for providers that support session-based caching.246
* Providers can use this to enable prompt caching, request routing, or other247
* session-aware features. Ignored by providers that don't support it.248
*/249
sessionId?: string;250
/**251
* WebSocket connect timeout in milliseconds for providers that support252
* WebSocket transports. This covers the connection/open handshake only;253
* stream idleness after connection uses timeoutMs.254
*/255
websocketConnectTimeoutMs?: number;256
/**257
* Optional metadata to include in API requests.258
* Providers extract the fields they understand and ignore the rest.259
* For example, Anthropic uses `user_id` for abuse tracking and rate limiting.260
*/261
metadata?: Record<string, unknown>;262
}264
export type ProviderStreamOptions = StreamOptions & Record<string, unknown>;266
export interface DeferredFetchOptions extends ProviderRequestOptions<Model<Api>> {267
/**268
* Maximum provider long-poll duration in milliseconds.269
* Defaults to 0, which performs one status check.270
*/271
wait?: number;272
}274
/** Request options for best-effort deferred-response cancellation. */275
export type DeferredCancelOptions = ProviderRequestOptions<Model<Api>>;277
/**278
* Maps known APIs to their full provider-specific stream option types.279
* Type-only imports from API implementation modules are erased at emit, so280
* this is tree-shake safe.281
*/282
export interface ApiOptionsMap {283
"anthropic-messages": AnthropicOptions;284
"openai-completions": OpenAICompletionsOptions;285
"openai-responses": OpenAIResponsesOptions;286
"openai-codex-responses": OpenAICodexResponsesOptions;287
"azure-openai-responses": AzureOpenAIResponsesOptions;288
"google-generative-ai": GoogleOptions;289
"google-vertex": GoogleVertexOptions;290
"mistral-conversations": MistralOptions;291
"bedrock-converse-stream": BedrockOptions;292
"pi-messages": PiMessagesOptions;293
}295
/**296
* Full stream options for an API. Known APIs resolve to their concrete option297
* type; custom API strings fall back to the generic shape.298
*/299
export type ApiStreamOptions<TApi extends Api> = TApi extends keyof ApiOptionsMap300
? ApiOptionsMap[TApi]301
: StreamOptions & Record<string, unknown>;303
/**304
* The uniform stream contract of an API implementation module: every module305
* under `src/api/` exports `stream` and `streamSimple`; capable modules may also306
* export deferred-response methods. Lazy wrappers (`lazyApi()`) and provider307
* factories pass these around as values. This is the untyped dispatch shape;308
* per-API option typing lives on the implementation modules themselves and on309
* `Provider.stream()` via `ApiStreamOptions`.310
*/311
export interface ProviderStreams {312
stream(model: Model<Api>, context: TranscriptContext, options?: StreamOptions): AssistantMessageEventStream;313
streamSimple(314
model: Model<Api>,315
context: TranscriptContext,316
options?: SimpleStreamOptions,317
): AssistantMessageEventStream;318
fetchDeferred?(319
model: Model<Api>,320
handle: DeferredHandle,321
options?: DeferredFetchOptions,322
): AssistantMessageEventStream;323
cancelDeferred?(model: Model<Api>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;324
}326
/**327
* The uniform contract of an image-generation API implementation module:328
* every image API module under `src/api/` exports exactly `generateImages`,329
* so the module itself satisfies this interface. Lazy wrappers and330
* `createProvider({ images })` pass these around as values.331
*/332
export interface ProviderImages {333
generateImages(334
model: ImageModel<ImageApi>,335
context: ImagesContext,336
options?: ImagesOptions,337
): Promise<AssistantImages>;338
}340
/** The uniform contract implemented by classifier API modules. */341
export interface ProviderClassifier {342
classify(343
model: ClassifierModel<ClassifierApi>,344
context: ClassifierContext,345
options?: ClassifierOptions,346
): Promise<ClassifierResult>;347
}349
export interface ClassifierOptions extends ProviderRequestOptions<ClassifierModel<ClassifierApi>> {350
/**351
* Divides the answer logits by this value before they are normalized into probabilities.352
* Values above 1 soften the distribution; values below 1 sharpen it. Must be positive.353
* APIs that cannot apply it ignore it.354
*/355
temperature?: number;356
}358
export interface ImagesOptions extends ProviderRequestOptions<ImageModel<ImageApi>> {359
/**360
* Optional metadata to include in API requests.361
* Providers extract the fields they understand and ignore the rest.362
*/363
metadata?: Record<string, unknown>;364
}366
export type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;368
// Unified options with reasoning passed to streamSimple() and completeSimple()369
export interface SimpleStreamOptions extends StreamOptions {370
/** Provider-neutral tool selection for simple requests. When omitted, adapters use provider-specific behavior. */371
toolChoice?: ToolChoice;372
reasoning?: ThinkingLevel;373
/** Ask a capable provider to return a durable handle and continue the request asynchronously. */374
deferred?: boolean | { window?: "15m" | "1h" | "24h" };375
/** Custom token budgets for thinking levels (token-based providers only) */376
thinkingBudgets?: ThinkingBudgets;377
}379
// Generic StreamFunction with typed options.380
//381
// Contract:382
// - Receives a normalized transcript: the system prompt and tools live in the383
// leading system message, never on the context itself.384
// - Must return an AssistantMessageEventStream.385
// - Direct streamSimple() calls may throw synchronously when request auth is386
// missing. Once a stream is returned, request/model/runtime failures should387
// be encoded in that stream.388
// - Error termination must produce an AssistantMessage with stopReason389
// "error" or "aborted" and errorMessage, emitted via the stream protocol.390
export type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (391
model: Model<TApi>,392
context: TranscriptContext,393
options?: TOptions,394
) => AssistantMessageEventStream;396
export type ImagesFunction<TOptions extends ImagesOptions = ImagesOptions> = (397
model: ImageModel<ImageApi>,398
context: ImagesContext,399
options?: TOptions,400
) => Promise<AssistantImages>;402
export type ClassifierFunction<TOptions extends ClassifierOptions = ClassifierOptions> = (403
model: ClassifierModel<ClassifierApi>,404
context: ClassifierContext,405
options?: TOptions,406
) => Promise<ClassifierResult>;408
export interface TextSignatureV1 {409
v: 1;410
id: string;411
phase?: "commentary" | "final_answer";412
}414
export interface TextContent {415
type: "text";416
text: string;417
textSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)418
}420
export interface ThinkingContent {421
type: "thinking";422
thinking: string;423
thinkingSignature?: string; // Provider-specific opaque or serialized reasoning replay data424
/** When true, the thinking content was redacted by safety filters. The opaque425
* encrypted payload is stored in `thinkingSignature` so it can be passed back426
* to the API for multi-turn continuity. */427
redacted?: boolean;428
}430
export interface ImageContent {431
type: "image";432
data: string; // base64 encoded image data433
mimeType: string; // e.g., "image/jpeg", "image/png"434
}436
export interface ToolCall {437
type: "toolCall";438
id: string;439
name: string;440
arguments: JsonObject;441
thoughtSignature?: string; // Google-specific: opaque signature for reusing thought context442
/** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */443
namespace?: string;444
/**445
* Set when the model's complete arguments text was not a valid JSON object. `arguments` is then `{}`.446
* Describes the problem and includes the text the model sent; tool argument validation fails with it.447
*/448
argumentsError?: string;449
}451
export interface Usage {452
input: number;453
output: number;454
cacheRead: number;455
cacheWrite: number;456
/** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */457
cacheWrite1h?: number;458
/**459
* Reasoning/thinking tokens, when the provider reports them. This is a subset of460
* `output`: `output` already includes these tokens. Set to a number (possibly 0) by461
* providers that expose a reasoning breakdown; left undefined by providers that don't.462
*/463
reasoning?: number;464
totalTokens: number;465
cost: {466
input: number;467
output: number;468
cacheRead: number;469
cacheWrite: number;470
total: number;471
};472
}474
export type StopReason = "pending" | "stop" | "length" | "toolUse" | "error" | "aborted" | "deferred";476
export type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;477
export type JsonObject = { [key: string]: JsonValue };479
type IsAny<T> = 0 extends 1 & T ? true : false;480
type IsExactlyJsonValue<T> = [T] extends [JsonValue] ? ([JsonValue] extends [T] ? true : false) : false;481
type IsJsonProperty<T> = IsAny<T> extends true482
? false483
: unknown extends T484
? false485
: [Exclude<T, undefined>] extends [never]486
? true487
: IsJsonCompatible<Exclude<T, undefined>>;488
type InvalidJsonKeys<T extends object> = {489
[TKey in keyof T]-?: TKey extends string | number ? (IsJsonProperty<T[TKey]> extends true ? never : TKey) : TKey;490
}[keyof T];491
type IsJsonCompatible<T> = IsAny<T> extends true492
? false493
: unknown extends T494
? false495
: IsExactlyJsonValue<T> extends true496
? true497
: T extends null | boolean | number | string498
? true499
: T extends undefined500
? false501
: T extends readonly (infer TItem)[]502
? IsJsonCompatible<TItem>503
: T extends (...args: never[]) => unknown504
? false505
: T extends object506
? [InvalidJsonKeys<T>] extends [never]507
? true508
: false509
: false;511
/** The JSON representation of a typed in-memory value. Optional object properties remain optional. */512
export type JsonRepresentation<T> = IsAny<T> extends true513
? JsonValue514
: unknown extends T515
? JsonValue516
: [T] extends [JsonValue]517
? T518
: T extends readonly unknown[]519
? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }520
: T extends object521
? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }522
: never;524
export interface DeferredHandle {525
provider: string;526
modelId: string;527
api: string;528
/** Provider token, such as a response id or batch id plus row id. */529
id: string;530
expiresAt?: number;531
pollAfterMs?: number;532
/** Provider conversion data required to reconstruct the final assistant message. */533
data?: JsonValue;534
}536
/**537
* System instructions and tool declarations at one point in the transcript.538
*539
* The leading system message is the system prompt. Later system messages change it:540
* `content` adds instructions from that point on, `sections` replace or remove named541
* prompt sections, and `toolsAdded`/`toolsRemoved` change the tool set. Replaying542
* every system message in order yields the current prompt and tools. Providers that543
* accept system messages mid-conversation send each one in place; other providers544
* rebuild the leading system message from the replayed state.545
*/546
export interface SystemMessage {547
role: "system";548
/** Instruction text. On the leading message this is the base prompt; later, additional instructions. */549
content: string | TextContent[];550
/**551
* Named, ordered prompt sections rendered verbatim after `content`. The leading message552
* declares them; later messages replace sections by name, and `null` removes one. Keep553
* each section self-delimiting (a tag, a heading) so the model can relate an update to554
* the original. Avoid integer-like names; JSON objects reorder those.555
*/556
sections?: Record<string, string | null>;557
/** Complete definitions of tools that become available at this point. */558
toolsAdded?: Tool[];559
/** Tools that stop being available at this point. */560
toolsRemoved?: ToolReference[];561
timestamp: number; // Unix timestamp in milliseconds562
}564
export interface UserMessage {565
role: "user";566
content: string | (TextContent | ImageContent)[];567
timestamp: number; // Unix timestamp in milliseconds568
}570
export interface AssistantMessage {571
role: "assistant";572
content: (TextContent | ThinkingContent | ToolCall)[];573
api: Api;574
provider: ProviderId;575
model: string;576
responseModel?: string; // Concrete model reported by the provider when different from the requested `model`577
responseId?: string; // Provider-specific response/message identifier when the upstream API exposes one578
/** Exact provider-native effort level used for this response. Absent for legacy or unmanaged responses. */579
providerThinkingLevel?: string;580
/** Pi thinking level the agent loop requested for this response. Absent outside the agent loop and for legacy responses. */581
thinkingLevel?: ModelThinkingLevel;582
diagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.583
usage: Usage;584
stopReason: StopReason;585
deferred?: DeferredHandle;586
errorMessage?: string;587
rawStopReason?: string;588
/**589
* Provider indication of whether the model explicitly ended its turn.590
* Preserved for debugging and does not currently affect agent control flow.591
*/592
endTurn?: boolean;593
/** Unix timestamp in milliseconds when the request started. */594
timestamp: number;595
/**596
* Milliseconds from `timestamp` until the response ended, measured with a monotonic clock. Set by597
* `AssistantMessageEventStream` on the final message of a response it saw start; absent for legacy messages and598
* for deferred results fetched later.599
*/600
durationMs?: number;601
}603
/** A tool call that another tool made while it ran, for example from a codemode script. */604
export interface NestedToolCallRecord {605
id: string;606
name: string;607
/** Omitted when over the size limits; `argumentsBytes` then gives their size. */608
arguments?: JsonObject;609
/** UTF-8 size of the arguments as JSON, set when `arguments` is omitted. */610
argumentsBytes?: number;611
/** `unfinished`: the call was still running when the calling tool finished. */612
status: "ok" | "error" | "unfinished";613
durationMs?: number;614
/** Error text, truncated. */615
error?: string;616
}618
/** Bounded record of the nested calls a tool made. Results are not recorded. */619
export interface NestedToolCalls {620
calls: NestedToolCallRecord[];621
/** False when calls were dropped, arguments omitted, or calls had not finished. */622
complete: boolean;623
}625
export type ToolResultMessage<TDetails = JsonValue> = IsJsonCompatible<TDetails> extends true626
? {627
role: "toolResult";628
toolCallId: string;629
toolName: string;630
content: (TextContent | ImageContent)[]; // Supports text and images631
details?: JsonRepresentation<TDetails>;632
/** Usage from the tool execution itself, if available. Not part of main LLM context accounting. */633
usage?: Usage;634
/** Calls this tool made to other tools. Kept for the session record; not sent to the model. */635
nestedCalls?: NestedToolCalls;636
isError: boolean;637
/** Unix timestamp in milliseconds when the result was created. */638
timestamp: number;639
/** Milliseconds the tool's execution took, measured with a monotonic clock. Absent for legacy results. */640
durationMs?: number;641
}642
: never;644
export type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;646
export type ImagesInputContent = TextContent | ImageContent;647
export type ImagesOutputContent = TextContent | ImageContent;649
export interface ImagesContext {650
input: ImagesInputContent[];651
}653
export type ImagesStopReason = "stop" | "error" | "aborted";655
export interface AssistantImages {656
api: ImageApi;657
provider: ProviderId;658
model: string;659
output: ImagesOutputContent[];660
responseId?: string;661
usage?: Usage;662
stopReason: ImagesStopReason;663
errorMessage?: string;664
timestamp: number; // Unix timestamp in milliseconds665
}667
export interface ClassifierChoiceQuestion {668
type: "choice";669
instructions: string;670
criteria: Record<string, string>;671
}673
export interface ClassifierScoreQuestion {674
type: "score";675
instructions: string;676
criteria: string[];677
}679
export interface ClassifierBoolQuestion {680
type: "bool";681
instructions: string;682
criteria: { true: string; false: string };683
}685
export type ClassifierQuestion = ClassifierChoiceQuestion | ClassifierScoreQuestion | ClassifierBoolQuestion;687
export interface ClassifierContext {688
state: JsonObject;689
/**690
* Images judged together with `state`. Only models whose `input` includes `"image"` accept them;691
* other models return an error result.692
*/693
images?: ImageContent[];694
questions: Record<string, ClassifierQuestion>;695
}697
export interface ClassifierChoiceAnswer {698
type: "choice";699
choice: string;700
probabilities: Record<string, number>;701
confidence: number;702
}704
export interface ClassifierScoreAnswer {705
type: "score";706
score: number;707
confidence: number;708
}710
export interface ClassifierBoolAnswer {711
type: "bool";712
probability: number;713
}715
export type ClassifierAnswer = ClassifierChoiceAnswer | ClassifierScoreAnswer | ClassifierBoolAnswer;716
export type ClassifierStopReason = "stop" | "error" | "aborted";718
export interface ClassifierResult {719
api: ClassifierApi;720
provider: ProviderId;721
model: string;722
answers: Record<string, ClassifierAnswer>;723
/** Token usage and its cost at the model's catalog price, when the service reports token counts. */724
usage?: Usage;725
stopReason: ClassifierStopReason;726
errorMessage?: string;727
timestamp: number; // Unix timestamp in milliseconds728
}730
import type { TSchema } from "typebox";732
/** OpenAI grammar variants for constrained sampling. */733
export type GrammarFormat = "openai_lark" | "openai_regex";735
export type GrammarVariants = Partial<Record<GrammarFormat, string>>;737
/**738
* Optional provider-side constrained sampling configs for a tool.739
*740
* The `json_schema` value roughly maps to the concept of `strict` in APIs which is741
* implemented as json-schema constrained sampling by APIs. Grammar variants let742
* callers provide provider-specific encodings of the same intended language.743
*/744
export type ConstrainedSamplingConfig =745
| {746
type: "json_schema";747
strict: "prefer" | "require";748
}749
| {750
type: "grammar";751
variants: GrammarVariants;752
};754
export interface Tool<TParameters extends TSchema = TSchema> {755
name: string;756
description: string;757
parameters: TParameters;758
constrainedSampling?: false | ConstrainedSamplingConfig;759
}761
export interface ToolReference {762
name: string;763
}765
/**766
* Request input accepted by the public stream entry points (`Models.stream()`,767
* `streamSimple()`, ...). `systemPrompt` and `tools` are shorthand for a leading768
* system message; `normalizeContext()` folds them into one before the request769
* reaches a provider.770
*/771
export interface Context {772
systemPrompt?: string;773
messages: Message[];774
tools?: Tool[];775
}777
declare const transcriptContextBrand: unique symbol;779
/**780
* Normalized request context passed to providers and API implementations. The781
* prompt and tool declarations are carried by the transcript's system messages.782
* Only `normalizeContext()` produces this type, so a raw `Context` cannot reach783
* provider code by accident.784
*/785
export type TranscriptContext = {786
messages: Message[];787
readonly [transcriptContextBrand]: true;788
};790
/**791
* Event protocol for AssistantMessageEventStream.792
*793
* Successful streams emit `start` before partial updates and terminate with794
* `done`. A stream may terminate directly with `error` when request setup fails795
* before generation starts; after `start`, failures also terminate with `error`.796
* Direct `streamSimple()` calls throw synchronously when request auth is missing.797
* Updates and `done` must never appear before `start`.798
*799
* `partial` is the shared live response-so-far helper, not an event-time800
* snapshot. Text and thinking blocks are empty when their `*_start` event is801
* emitted and grow only through their corresponding `*_delta` events until the802
* authoritative `*_end`. Redacted thinking may be complete at start and emit no803
* deltas. Tool-call arguments at `toolcall_start` are provider-specific;804
* `toolcall_delta` carries subsequent JSON updates.805
*/806
export type AssistantMessageEvent =807
| { type: "start"; partial: AssistantMessage }808
| { type: "text_start"; contentIndex: number; partial: AssistantMessage }809
| { type: "text_delta"; contentIndex: number; delta: string; partial: AssistantMessage }810
| { type: "text_end"; contentIndex: number; content: string; partial: AssistantMessage }811
| { type: "thinking_start"; contentIndex: number; partial: AssistantMessage }812
| { type: "thinking_delta"; contentIndex: number; delta: string; partial: AssistantMessage }813
| { type: "thinking_end"; contentIndex: number; content: string; partial: AssistantMessage }814
| { type: "toolcall_start"; contentIndex: number; partial: AssistantMessage }815
| { type: "toolcall_delta"; contentIndex: number; delta: string; partial: AssistantMessage }816
| { type: "toolcall_end"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }817
| {818
type: "done";819
reason: Extract<StopReason, "stop" | "length" | "toolUse" | "deferred">;820
message: AssistantMessage;821
}822
| { type: "error"; reason: Extract<StopReason, "aborted" | "error">; error: AssistantMessage };824
/** Fields shared by every catalog entry, regardless of what you can do with it. */825
export interface BaseModel<TApi extends string> {826
id: string;827
name: string;828
api: TApi;829
provider: ProviderId;830
baseUrl: string;831
input: ModelInputModality[];832
/** Provider input limits and cache-safe preprocessing metadata. */833
inputLimits?: ModelInputLimits;834
cost: ModelCost;835
headers?: Record<string, string>;836
}838
/** Chat model: usable with `stream()` and friends. */839
export interface Model<TApi extends Api> extends BaseModel<TApi> {840
/**841
* Optional: chat is the default model type, so models without `type` are chat842
* models. Narrow mixed model lists with `isModelType()` instead of comparing843
* `type` directly.844
*/845
type?: "chat";846
reasoning: boolean;847
/**848
* Maps pi thinking levels to provider/model-specific values.849
* Missing keys use provider defaults. null marks a level as unsupported.850
*/851
thinkingLevelMap?: ThinkingLevelMap;852
/** Prompt cache lifetimes per retention tier. Unset when the provider's cache behavior is unknown. */853
promptCache?: ModelPromptCache;854
contextWindow: number;855
maxTokens: number;856
/** Default sampling parameters for this model. See {@link StreamOptions.samplingParams}; per-request keys override these. */857
samplingParams?: SamplingParams;858
/** Sampling parameter overrides selected by the effective pi thinking level. */859
samplingParamsByThinkingLevel?: SamplingParamsByThinkingLevel;860
/** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */861
compat?: TApi extends "openai-completions"862
? OpenAICompletionsCompat863
: TApi extends "openai-responses" | "azure-openai-responses" | "openai-codex-responses"864
? OpenAIResponsesCompat865
: TApi extends "anthropic-messages"866
? AnthropicMessagesCompat867
: TApi extends "bedrock-converse-stream"868
? BedrockCompat869
: TApi extends "mistral-conversations"870
? MistralConversationsCompat871
: never;872
}874
/** Image-generation model: usable with `generateImages()` only. */875
export interface ImageModel<TApi extends ImageApi> extends BaseModel<TApi> {876
type: "image";877
/** Output modalities. Always includes `"image"`; `"text"` means the model can also return text blocks. */878
output: ("text" | "image")[];879
}881
/** Structured classifier model: usable with `classify()` only. */882
export interface ClassifierModel<TApi extends ClassifierApi> extends BaseModel<TApi> {883
type: "classifier";884
contextWindow: number;885
}887
/** Model shape for each model type. */888
export interface ModelTypeMap {889
chat: Model<Api>;890
image: ImageModel<ImageApi>;891
classifier: ClassifierModel<ClassifierApi>;892
}894
/** What a catalog entry is for. Decides which `Models` operation accepts it. */895
export type ModelType = keyof ModelTypeMap;897
/** Anything a provider can list. Narrow with `isModelType()`. */898
export type AnyModel = ModelTypeMap[ModelType];