返回源码地图

packages/ai/src/types.ts

v1.3.0 · 71023aec1546 · 04:430–462及540–650,工具错误、usage、消息与事件契约

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type { TelemetryContext } from "@earendil-works/pi-telemetry";
2import type { AnthropicOptions } from "./api/anthropic-messages.ts";
3import type { AzureOpenAIResponsesOptions } from "./api/azure-openai-responses.ts";
4import type { BedrockOptions } from "./api/bedrock-converse-stream.ts";
5import type { GoogleOptions } from "./api/google-generative-ai.ts";
6import type { GoogleVertexOptions } from "./api/google-vertex.ts";
7import type { MistralOptions } from "./api/mistral-conversations.ts";
8import type { OpenAICodexResponsesOptions } from "./api/openai-codex-responses.ts";
9import type { OpenAICompletionsOptions } from "./api/openai-completions.ts";
10import type { OpenAIResponsesOptions } from "./api/openai-responses.ts";
11import type { PiMessagesOptions } from "./api/pi-messages.ts";
12import type {
13 AnthropicMessagesCompat,
14 BedrockCompat,
15 MistralConversationsCompat,
16 OpenAICompletionsCompat,
17 OpenAIResponsesCompat,
18} from "./providers/compat-schema.ts";
19import type {
20 CacheRetention,
21 ModelCost,
22 ModelInputLimits,
23 ModelInputModality,
24 ModelPromptCache,
25 ModelThinkingLevel,
26 ThinkingLevel,
27 ThinkingLevelMap,
28} from "./providers/model-schema.ts";
29import type { AssistantMessageDiagnostic } from "./utils/diagnostics.ts";
30import type { AssistantMessageEventStream } from "./utils/event-stream.ts";
31
32export 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";
45export 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";
59export type { AssistantMessageEventStream } from "./utils/event-stream.ts";
60
61export 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";
72
73export type Api = KnownApi | (string & {});
74
75export type KnownImageApi = "openrouter-images";
76
77export type ImageApi = KnownImageApi | (string & {});
78
79export type KnownClassifierApi =
80 | "typesafe-system-one"
81 | "cloudflare-workers-ai-system-one"
82 | "llama-cpp-classify"
83 | "openai-decisions";
84
85export type ClassifierApi = KnownClassifierApi | (string & {});
86
87export 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";
130export type ProviderId = KnownProvider | string;
131
132export type ToolChoice = "auto" | "none";
133export type SamplingParams = Record<string, unknown>;
134export type SamplingParamsByThinkingLevel = Partial<Record<ModelThinkingLevel, SamplingParams>>;
135/** Token budgets for each thinking level (token-based providers only) */
136export interface ThinkingBudgets {
137 minimal?: number;
138 low?: number;
139 medium?: number;
140 high?: number;
141}
142
143// Base options all providers share
144export type Transport = "sse" | "websocket" | "websocket-cached" | "auto";
145
146/** Provider-scoped environment overrides. Values take precedence over process.env. */
147export type ProviderEnv = Record<string, string>;
148export type ProviderHeaders = Record<string, string | null>;
149export type FetchFunction = typeof globalThis.fetch;
150
151export interface ProviderResponse {
152 status: number;
153 headers: Record<string, string>;
154}
155
156/** Authentication, HTTP transport, and lifecycle callbacks shared by provider requests. */
157export 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 for
170 * provider configuration such as regional settings, endpoint placeholders, and
171 * 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 so
187 * 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 immediately
205 * with an error containing the requested delay, allowing higher-level retry logic
206 * to handle it with user visibility.
207 * Default: 60000 (60 seconds). Set to 0 to disable the cap.
208 */
209 maxRetryDelayMs?: number;
210}
211
212export interface StreamOptions extends ProviderRequestOptions<Model<Api>> {
213 /**
214 * Optional callback invoked after an HTTP response is received and before
215 * 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 request
227 * 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 by
230 * 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 other
247 * 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 support
252 * 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}
263
264export type ProviderStreamOptions = StreamOptions & Record<string, unknown>;
265
266export 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}
273
274/** Request options for best-effort deferred-response cancellation. */
275export type DeferredCancelOptions = ProviderRequestOptions<Model<Api>>;
276
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, so
280 * this is tree-shake safe.
281 */
282export 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}
294
295/**
296 * Full stream options for an API. Known APIs resolve to their concrete option
297 * type; custom API strings fall back to the generic shape.
298 */
299export type ApiStreamOptions<TApi extends Api> = TApi extends keyof ApiOptionsMap
300 ? ApiOptionsMap[TApi]
301 : StreamOptions & Record<string, unknown>;
302
303/**
304 * The uniform stream contract of an API implementation module: every module
305 * under `src/api/` exports `stream` and `streamSimple`; capable modules may also
306 * export deferred-response methods. Lazy wrappers (`lazyApi()`) and provider
307 * factories pass these around as values. This is the untyped dispatch shape;
308 * per-API option typing lives on the implementation modules themselves and on
309 * `Provider.stream()` via `ApiStreamOptions`.
310 */
311export 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}
325
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 and
330 * `createProvider({ images })` pass these around as values.
331 */
332export interface ProviderImages {
333 generateImages(
334 model: ImageModel<ImageApi>,
335 context: ImagesContext,
336 options?: ImagesOptions,
337 ): Promise<AssistantImages>;
338}
339
340/** The uniform contract implemented by classifier API modules. */
341export interface ProviderClassifier {
342 classify(
343 model: ClassifierModel<ClassifierApi>,
344 context: ClassifierContext,
345 options?: ClassifierOptions,
346 ): Promise<ClassifierResult>;
347}
348
349export 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}
357
358export 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}
365
366export type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;
367
368// Unified options with reasoning passed to streamSimple() and completeSimple()
369export 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}
378
379// Generic StreamFunction with typed options.
380//
381// Contract:
382// - Receives a normalized transcript: the system prompt and tools live in the
383// leading system message, never on the context itself.
384// - Must return an AssistantMessageEventStream.
385// - Direct streamSimple() calls may throw synchronously when request auth is
386// missing. Once a stream is returned, request/model/runtime failures should
387// be encoded in that stream.
388// - Error termination must produce an AssistantMessage with stopReason
389// "error" or "aborted" and errorMessage, emitted via the stream protocol.
390export type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (
391 model: Model<TApi>,
392 context: TranscriptContext,
393 options?: TOptions,
394) => AssistantMessageEventStream;
395
396export type ImagesFunction<TOptions extends ImagesOptions = ImagesOptions> = (
397 model: ImageModel<ImageApi>,
398 context: ImagesContext,
399 options?: TOptions,
400) => Promise<AssistantImages>;
401
402export type ClassifierFunction<TOptions extends ClassifierOptions = ClassifierOptions> = (
403 model: ClassifierModel<ClassifierApi>,
404 context: ClassifierContext,
405 options?: TOptions,
406) => Promise<ClassifierResult>;
407
408export interface TextSignatureV1 {
409 v: 1;
410 id: string;
411 phase?: "commentary" | "final_answer";
412}
413
414export 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}
419
420export interface ThinkingContent {
421 type: "thinking";
422 thinking: string;
423 thinkingSignature?: string; // Provider-specific opaque or serialized reasoning replay data
424 /** When true, the thinking content was redacted by safety filters. The opaque
425 * encrypted payload is stored in `thinkingSignature` so it can be passed back
426 * to the API for multi-turn continuity. */
427 redacted?: boolean;
428}
429
430export interface ImageContent {
431 type: "image";
432 data: string; // base64 encoded image data
433 mimeType: string; // e.g., "image/jpeg", "image/png"
434}
435
436export interface ToolCall {
437 type: "toolCall";
438 id: string;
439 name: string;
440 arguments: JsonObject;
441 thoughtSignature?: string; // Google-specific: opaque signature for reusing thought context
442 /** 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}
450
451export 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 of
460 * `output`: `output` already includes these tokens. Set to a number (possibly 0) by
461 * 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}
473
474export type StopReason = "pending" | "stop" | "length" | "toolUse" | "error" | "aborted" | "deferred";
475
476export type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;
477export type JsonObject = { [key: string]: JsonValue };
478
479type IsAny<T> = 0 extends 1 & T ? true : false;
480type IsExactlyJsonValue<T> = [T] extends [JsonValue] ? ([JsonValue] extends [T] ? true : false) : false;
481type IsJsonProperty<T> = IsAny<T> extends true
482 ? false
483 : unknown extends T
484 ? false
485 : [Exclude<T, undefined>] extends [never]
486 ? true
487 : IsJsonCompatible<Exclude<T, undefined>>;
488type InvalidJsonKeys<T extends object> = {
489 [TKey in keyof T]-?: TKey extends string | number ? (IsJsonProperty<T[TKey]> extends true ? never : TKey) : TKey;
490}[keyof T];
491type IsJsonCompatible<T> = IsAny<T> extends true
492 ? false
493 : unknown extends T
494 ? false
495 : IsExactlyJsonValue<T> extends true
496 ? true
497 : T extends null | boolean | number | string
498 ? true
499 : T extends undefined
500 ? false
501 : T extends readonly (infer TItem)[]
502 ? IsJsonCompatible<TItem>
503 : T extends (...args: never[]) => unknown
504 ? false
505 : T extends object
506 ? [InvalidJsonKeys<T>] extends [never]
507 ? true
508 : false
509 : false;
510
511/** The JSON representation of a typed in-memory value. Optional object properties remain optional. */
512export type JsonRepresentation<T> = IsAny<T> extends true
513 ? JsonValue
514 : unknown extends T
515 ? JsonValue
516 : [T] extends [JsonValue]
517 ? T
518 : T extends readonly unknown[]
519 ? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }
520 : T extends object
521 ? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }
522 : never;
523
524export 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}
535
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 named
541 * prompt sections, and `toolsAdded`/`toolsRemoved` change the tool set. Replaying
542 * every system message in order yields the current prompt and tools. Providers that
543 * accept system messages mid-conversation send each one in place; other providers
544 * rebuild the leading system message from the replayed state.
545 */
546export 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 message
552 * declares them; later messages replace sections by name, and `null` removes one. Keep
553 * each section self-delimiting (a tag, a heading) so the model can relate an update to
554 * 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 milliseconds
562}
563
564export interface UserMessage {
565 role: "user";
566 content: string | (TextContent | ImageContent)[];
567 timestamp: number; // Unix timestamp in milliseconds
568}
569
570export 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 one
578 /** 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 by
597 * `AssistantMessageEventStream` on the final message of a response it saw start; absent for legacy messages and
598 * for deferred results fetched later.
599 */
600 durationMs?: number;
601}
602
603/** A tool call that another tool made while it ran, for example from a codemode script. */
604export 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}
617
618/** Bounded record of the nested calls a tool made. Results are not recorded. */
619export interface NestedToolCalls {
620 calls: NestedToolCallRecord[];
621 /** False when calls were dropped, arguments omitted, or calls had not finished. */
622 complete: boolean;
623}
624
625export type ToolResultMessage<TDetails = JsonValue> = IsJsonCompatible<TDetails> extends true
626 ? {
627 role: "toolResult";
628 toolCallId: string;
629 toolName: string;
630 content: (TextContent | ImageContent)[]; // Supports text and images
631 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;
643
644export type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;
645
646export type ImagesInputContent = TextContent | ImageContent;
647export type ImagesOutputContent = TextContent | ImageContent;
648
649export interface ImagesContext {
650 input: ImagesInputContent[];
651}
652
653export type ImagesStopReason = "stop" | "error" | "aborted";
654
655export 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 milliseconds
665}
666
667export interface ClassifierChoiceQuestion {
668 type: "choice";
669 instructions: string;
670 criteria: Record<string, string>;
671}
672
673export interface ClassifierScoreQuestion {
674 type: "score";
675 instructions: string;
676 criteria: string[];
677}
678
679export interface ClassifierBoolQuestion {
680 type: "bool";
681 instructions: string;
682 criteria: { true: string; false: string };
683}
684
685export type ClassifierQuestion = ClassifierChoiceQuestion | ClassifierScoreQuestion | ClassifierBoolQuestion;
686
687export 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}
696
697export interface ClassifierChoiceAnswer {
698 type: "choice";
699 choice: string;
700 probabilities: Record<string, number>;
701 confidence: number;
702}
703
704export interface ClassifierScoreAnswer {
705 type: "score";
706 score: number;
707 confidence: number;
708}
709
710export interface ClassifierBoolAnswer {
711 type: "bool";
712 probability: number;
713}
714
715export type ClassifierAnswer = ClassifierChoiceAnswer | ClassifierScoreAnswer | ClassifierBoolAnswer;
716export type ClassifierStopReason = "stop" | "error" | "aborted";
717
718export 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 milliseconds
728}
729
730import type { TSchema } from "typebox";
731
732/** OpenAI grammar variants for constrained sampling. */
733export type GrammarFormat = "openai_lark" | "openai_regex";
734
735export type GrammarVariants = Partial<Record<GrammarFormat, string>>;
736
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 is
741 * implemented as json-schema constrained sampling by APIs. Grammar variants let
742 * callers provide provider-specific encodings of the same intended language.
743 */
744export type ConstrainedSamplingConfig =
745 | {
746 type: "json_schema";
747 strict: "prefer" | "require";
748 }
749 | {
750 type: "grammar";
751 variants: GrammarVariants;
752 };
753
754export interface Tool<TParameters extends TSchema = TSchema> {
755 name: string;
756 description: string;
757 parameters: TParameters;
758 constrainedSampling?: false | ConstrainedSamplingConfig;
759}
760
761export interface ToolReference {
762 name: string;
763}
764
765/**
766 * Request input accepted by the public stream entry points (`Models.stream()`,
767 * `streamSimple()`, ...). `systemPrompt` and `tools` are shorthand for a leading
768 * system message; `normalizeContext()` folds them into one before the request
769 * reaches a provider.
770 */
771export interface Context {
772 systemPrompt?: string;
773 messages: Message[];
774 tools?: Tool[];
775}
776
777declare const transcriptContextBrand: unique symbol;
778
779/**
780 * Normalized request context passed to providers and API implementations. The
781 * prompt and tool declarations are carried by the transcript's system messages.
782 * Only `normalizeContext()` produces this type, so a raw `Context` cannot reach
783 * provider code by accident.
784 */
785export type TranscriptContext = {
786 messages: Message[];
787 readonly [transcriptContextBrand]: true;
788};
789
790/**
791 * Event protocol for AssistantMessageEventStream.
792 *
793 * Successful streams emit `start` before partial updates and terminate with
794 * `done`. A stream may terminate directly with `error` when request setup fails
795 * 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-time
800 * snapshot. Text and thinking blocks are empty when their `*_start` event is
801 * emitted and grow only through their corresponding `*_delta` events until the
802 * authoritative `*_end`. Redacted thinking may be complete at start and emit no
803 * deltas. Tool-call arguments at `toolcall_start` are provider-specific;
804 * `toolcall_delta` carries subsequent JSON updates.
805 */
806export 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 };
823
824/** Fields shared by every catalog entry, regardless of what you can do with it. */
825export 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}
837
838/** Chat model: usable with `stream()` and friends. */
839export interface Model<TApi extends Api> extends BaseModel<TApi> {
840 /**
841 * Optional: chat is the default model type, so models without `type` are chat
842 * models. Narrow mixed model lists with `isModelType()` instead of comparing
843 * `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 ? OpenAICompletionsCompat
863 : TApi extends "openai-responses" | "azure-openai-responses" | "openai-codex-responses"
864 ? OpenAIResponsesCompat
865 : TApi extends "anthropic-messages"
866 ? AnthropicMessagesCompat
867 : TApi extends "bedrock-converse-stream"
868 ? BedrockCompat
869 : TApi extends "mistral-conversations"
870 ? MistralConversationsCompat
871 : never;
872}
873
874/** Image-generation model: usable with `generateImages()` only. */
875export 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}
880
881/** Structured classifier model: usable with `classify()` only. */
882export interface ClassifierModel<TApi extends ClassifierApi> extends BaseModel<TApi> {
883 type: "classifier";
884 contextWindow: number;
885}
886
887/** Model shape for each model type. */
888export interface ModelTypeMap {
889 chat: Model<Api>;
890 image: ImageModel<ImageApi>;
891 classifier: ClassifierModel<ClassifierApi>;
892}
893
894/** What a catalog entry is for. Decides which `Models` operation accepts it. */
895export type ModelType = keyof ModelTypeMap;
896
897/** Anything a provider can list. Narrow with `isModelType()`. */
898export type AnyModel = ModelTypeMap[ModelType];