@modelrelay/sdk 1.44.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,998 @@
1
+ declare const SDK_VERSION: string;
2
+ declare const DEFAULT_BASE_URL = "https://api.modelrelay.ai/api/v1";
3
+ declare const DEFAULT_CLIENT_HEADER: string;
4
+ declare const DEFAULT_CONNECT_TIMEOUT_MS = 5000;
5
+ declare const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
6
+ type NonEmptyArray<T> = [T, ...T[]];
7
+ declare const StopReasons: {
8
+ readonly Completed: "completed";
9
+ readonly Stop: "stop";
10
+ readonly StopSequence: "stop_sequence";
11
+ readonly EndTurn: "end_turn";
12
+ readonly MaxTokens: "max_tokens";
13
+ readonly MaxLength: "max_len";
14
+ readonly MaxContext: "max_context";
15
+ readonly ToolCalls: "tool_calls";
16
+ readonly TimeLimit: "time_limit";
17
+ readonly ContentFilter: "content_filter";
18
+ readonly Incomplete: "incomplete";
19
+ readonly Unknown: "unknown";
20
+ };
21
+ type KnownStopReason = (typeof StopReasons)[keyof typeof StopReasons];
22
+ type StopReason = KnownStopReason | {
23
+ other: string;
24
+ };
25
+ /**
26
+ * Branded type for provider identifiers (e.g., "anthropic", "openai").
27
+ * The brand prevents accidental use of arbitrary strings where a provider ID is expected.
28
+ */
29
+ type ProviderId = string & {
30
+ readonly __brand: "ProviderId";
31
+ };
32
+ /**
33
+ * Branded type for model identifiers (e.g., "claude-3-5-sonnet-20241022").
34
+ * The brand prevents accidental use of arbitrary strings where a model ID is expected.
35
+ */
36
+ type ModelId = string & {
37
+ readonly __brand: "ModelId";
38
+ };
39
+ /**
40
+ * Branded type for tier codes (e.g., "free", "pro", "enterprise").
41
+ * The brand prevents accidental use of arbitrary strings where a tier code is expected.
42
+ */
43
+ type TierCode = string & {
44
+ readonly __brand: "TierCode";
45
+ };
46
+ /**
47
+ * Cast a string to a ProviderId. Use for known provider identifiers.
48
+ */
49
+ declare function asProviderId(value: string): ProviderId;
50
+ /**
51
+ * Cast a string to a ModelId. Use for known model identifiers.
52
+ */
53
+ declare function asModelId(value: string): ModelId;
54
+ /**
55
+ * Cast a string to a TierCode. Use for known tier codes.
56
+ */
57
+ declare function asTierCode(value: string): TierCode;
58
+ declare const SubscriptionStatuses: {
59
+ readonly Active: "active";
60
+ readonly Trialing: "trialing";
61
+ readonly PastDue: "past_due";
62
+ readonly Canceled: "canceled";
63
+ readonly Unpaid: "unpaid";
64
+ readonly Incomplete: "incomplete";
65
+ readonly IncompleteExpired: "incomplete_expired";
66
+ readonly Paused: "paused";
67
+ };
68
+ type SubscriptionStatusKind = (typeof SubscriptionStatuses)[keyof typeof SubscriptionStatuses];
69
+ declare const BillingProviders: {
70
+ readonly Stripe: "stripe";
71
+ readonly Crypto: "crypto";
72
+ readonly AppStore: "app_store";
73
+ readonly External: "external";
74
+ };
75
+ type BillingProvider = (typeof BillingProviders)[keyof typeof BillingProviders];
76
+ /** Arbitrary customer metadata. Values can be any JSON type. */
77
+ type CustomerMetadata = Record<string, unknown>;
78
+ type SecretKey = string & {
79
+ readonly __brand: "SecretKey";
80
+ };
81
+ type ApiKey = SecretKey;
82
+ /**
83
+ * TokenProvider supplies short-lived bearer tokens for ModelRelay data-plane calls.
84
+ *
85
+ * Providers are responsible for caching and refreshing tokens when needed.
86
+ */
87
+ interface TokenProvider {
88
+ getToken(): Promise<string>;
89
+ }
90
+ /**
91
+ * Common configuration options for the ModelRelay client.
92
+ */
93
+ interface ModelRelayBaseOptions {
94
+ /**
95
+ * Optional base URL override. Defaults to production API.
96
+ */
97
+ baseUrl?: string;
98
+ fetch?: typeof fetch;
99
+ /**
100
+ * Optional client header override for telemetry.
101
+ */
102
+ clientHeader?: string;
103
+ /**
104
+ * Default connect timeout in milliseconds (applies to each attempt).
105
+ */
106
+ connectTimeoutMs?: number;
107
+ /**
108
+ * Default request timeout in milliseconds (non-streaming). Set to 0 to disable.
109
+ */
110
+ timeoutMs?: number;
111
+ /**
112
+ * Retry configuration applied to all requests (can be overridden per call). Set to `false` to disable retries.
113
+ */
114
+ retry?: RetryConfig | false;
115
+ /**
116
+ * Default HTTP headers applied to every request.
117
+ */
118
+ defaultHeaders?: Record<string, string>;
119
+ /**
120
+ * Optional metrics callbacks for latency/usage.
121
+ */
122
+ metrics?: MetricsCallbacks;
123
+ /**
124
+ * Optional trace/log hooks for request + stream lifecycle.
125
+ */
126
+ trace?: TraceCallbacks;
127
+ }
128
+ /**
129
+ * Configuration options requiring an API key.
130
+ */
131
+ interface ModelRelayKeyOptions extends ModelRelayBaseOptions {
132
+ /**
133
+ * Secret API key (`mr_sk_...`). Required.
134
+ */
135
+ key: ApiKey;
136
+ /**
137
+ * Optional bearer token (takes precedence over key for requests when provided).
138
+ */
139
+ token?: string;
140
+ }
141
+ /**
142
+ * Configuration options requiring an access token.
143
+ */
144
+ interface ModelRelayTokenOptions extends ModelRelayBaseOptions {
145
+ /**
146
+ * Optional API key.
147
+ */
148
+ key?: ApiKey;
149
+ /**
150
+ * Bearer token to call the API directly (customer token). Required.
151
+ */
152
+ token: string;
153
+ }
154
+ /**
155
+ * Configuration options requiring a TokenProvider.
156
+ */
157
+ interface ModelRelayTokenProviderOptions extends ModelRelayBaseOptions {
158
+ /**
159
+ * Token provider used to fetch bearer tokens for `/responses`, `/runs`, and `/workflows/compile`.
160
+ */
161
+ tokenProvider: TokenProvider;
162
+ /**
163
+ * Optional API key. Useful for non-data-plane endpoints (e.g., /customers, /tiers).
164
+ */
165
+ key?: ApiKey;
166
+ }
167
+ /**
168
+ * ModelRelay client configuration.
169
+ *
170
+ * You must provide at least one of `key` or `token` for authentication.
171
+ * This is enforced at compile time through discriminated union types.
172
+ *
173
+ * @example With API key (server-side)
174
+ * ```typescript
175
+ * import { ModelRelay } from "@modelrelay/sdk";
176
+ * const client = ModelRelay.fromSecretKey("mr_sk_...");
177
+ * ```
178
+ *
179
+ * @example With access token (customer bearer token)
180
+ * ```typescript
181
+ * const client = new ModelRelay({ token: customerToken });
182
+ * ```
183
+ *
184
+ * @example With token provider (backend-minted tokens)
185
+ * ```typescript
186
+ * import { ModelRelay } from "@modelrelay/sdk";
187
+ * const client = new ModelRelay({ tokenProvider });
188
+ * ```
189
+ */
190
+ type ModelRelayOptions = ModelRelayKeyOptions | ModelRelayTokenOptions | ModelRelayTokenProviderOptions;
191
+ /**
192
+ * @deprecated Use ModelRelayOptions instead. This type allows empty configuration
193
+ * which will fail at runtime.
194
+ */
195
+ /** Token type for OAuth2 bearer tokens. */
196
+ type TokenType = "Bearer";
197
+ interface CustomerTokenRequest {
198
+ customerId?: string;
199
+ customerExternalId?: string;
200
+ ttlSeconds?: number;
201
+ }
202
+ /**
203
+ * Request to get or create a customer token.
204
+ * This upserts the customer (creating if needed) then mints a token.
205
+ */
206
+ interface GetOrCreateCustomerTokenRequest {
207
+ /** Your external customer identifier (required). */
208
+ externalId: string;
209
+ /** Customer email address (required for customer creation). */
210
+ email: string;
211
+ /** Optional customer metadata. */
212
+ metadata?: CustomerMetadata;
213
+ /** Optional token TTL in seconds (default: 7 days, max: 30 days). */
214
+ ttlSeconds?: number;
215
+ }
216
+ interface CustomerToken {
217
+ token: string;
218
+ expiresAt: Date;
219
+ expiresIn: number;
220
+ tokenType: TokenType;
221
+ projectId: string;
222
+ /** Identity customer ID (always present for valid customer tokens). */
223
+ customerId?: string;
224
+ /** Billing profile ID for managed billing customers. */
225
+ billingProfileId?: string;
226
+ customerExternalId: string;
227
+ /** Optional for BYOB (external billing) projects */
228
+ tierCode?: TierCode;
229
+ }
230
+ interface Usage {
231
+ inputTokens: number;
232
+ outputTokens: number;
233
+ totalTokens: number;
234
+ }
235
+ /**
236
+ * Creates a Usage object with automatic totalTokens calculation if not provided.
237
+ */
238
+ declare function createUsage(inputTokens: number, outputTokens: number, totalTokens?: number): Usage;
239
+ interface UsageSummary {
240
+ plan: string;
241
+ planType?: string;
242
+ windowStart?: Date | string;
243
+ windowEnd?: Date | string;
244
+ limit?: number;
245
+ used?: number;
246
+ images?: number;
247
+ actionsLimit?: number;
248
+ actionsUsed?: number;
249
+ remaining?: number;
250
+ state?: string;
251
+ }
252
+ interface Project {
253
+ id: string;
254
+ name: string;
255
+ description?: string;
256
+ createdAt?: Date;
257
+ updatedAt?: Date;
258
+ }
259
+ /**
260
+ * Valid roles for chat messages.
261
+ */
262
+ declare const MessageRoles: {
263
+ readonly User: "user";
264
+ readonly Assistant: "assistant";
265
+ readonly System: "system";
266
+ readonly Tool: "tool";
267
+ };
268
+ type MessageRole = (typeof MessageRoles)[keyof typeof MessageRoles];
269
+ declare const ContentPartTypes: {
270
+ readonly Text: "text";
271
+ };
272
+ type ContentPartType = (typeof ContentPartTypes)[keyof typeof ContentPartTypes];
273
+ type ContentPart = {
274
+ type: "text";
275
+ text: string;
276
+ };
277
+ declare const InputItemTypes: {
278
+ readonly Message: "message";
279
+ };
280
+ type InputItemType = (typeof InputItemTypes)[keyof typeof InputItemTypes];
281
+ type InputItem = {
282
+ type: "message";
283
+ role: MessageRole;
284
+ content: ContentPart[];
285
+ toolCalls?: ToolCall[];
286
+ toolCallId?: string;
287
+ };
288
+ declare const OutputItemTypes: {
289
+ readonly Message: "message";
290
+ };
291
+ type OutputItemType = (typeof OutputItemTypes)[keyof typeof OutputItemTypes];
292
+ type OutputItem = {
293
+ type: "message";
294
+ role: MessageRole;
295
+ content: ContentPart[];
296
+ toolCalls?: ToolCall[];
297
+ };
298
+ declare const ToolTypes: {
299
+ readonly Function: "function";
300
+ readonly Web: "web";
301
+ readonly XSearch: "x_search";
302
+ readonly CodeExecution: "code_execution";
303
+ };
304
+ type ToolType = (typeof ToolTypes)[keyof typeof ToolTypes];
305
+ declare const WebToolIntents: {
306
+ readonly Auto: "auto";
307
+ readonly SearchWeb: "search_web";
308
+ readonly FetchURL: "fetch_url";
309
+ };
310
+ type WebToolIntent = (typeof WebToolIntents)[keyof typeof WebToolIntents];
311
+ interface FunctionTool {
312
+ name: string;
313
+ description?: string;
314
+ parameters?: Record<string, unknown>;
315
+ }
316
+ interface WebSearchConfig {
317
+ allowedDomains?: string[];
318
+ excludedDomains?: string[];
319
+ maxUses?: number;
320
+ intent?: WebToolIntent;
321
+ }
322
+ interface XSearchConfig {
323
+ allowedHandles?: string[];
324
+ excludedHandles?: string[];
325
+ fromDate?: string;
326
+ toDate?: string;
327
+ }
328
+ interface CodeExecConfig {
329
+ language?: string;
330
+ timeoutMs?: number;
331
+ }
332
+ interface Tool {
333
+ type: ToolType;
334
+ function?: FunctionTool;
335
+ web?: WebSearchConfig;
336
+ xSearch?: XSearchConfig;
337
+ codeExecution?: CodeExecConfig;
338
+ }
339
+ declare const ToolChoiceTypes: {
340
+ readonly Auto: "auto";
341
+ readonly Required: "required";
342
+ readonly None: "none";
343
+ };
344
+ type ToolChoiceType = (typeof ToolChoiceTypes)[keyof typeof ToolChoiceTypes];
345
+ interface ToolChoice {
346
+ type: ToolChoiceType;
347
+ /**
348
+ * Optional function tool name to force.
349
+ * Only valid when type is "required".
350
+ */
351
+ function?: string;
352
+ }
353
+ interface FunctionCall {
354
+ name: string;
355
+ arguments: string;
356
+ }
357
+ interface ToolCall {
358
+ id: string;
359
+ type: ToolType;
360
+ function?: FunctionCall;
361
+ }
362
+ declare const OutputFormatTypes: {
363
+ readonly Text: "text";
364
+ readonly JsonSchema: "json_schema";
365
+ };
366
+ type OutputFormatType = (typeof OutputFormatTypes)[keyof typeof OutputFormatTypes];
367
+ interface JSONSchemaFormat {
368
+ name: string;
369
+ description?: string;
370
+ schema: Record<string, unknown>;
371
+ strict?: boolean;
372
+ }
373
+ interface OutputFormat {
374
+ type: OutputFormatType;
375
+ json_schema?: JSONSchemaFormat;
376
+ }
377
+ interface Citation {
378
+ url?: string;
379
+ title?: string;
380
+ }
381
+ interface Response {
382
+ id: string;
383
+ output: OutputItem[];
384
+ stopReason?: StopReason;
385
+ model: ModelId;
386
+ usage: Usage;
387
+ requestId?: string;
388
+ provider?: ProviderId;
389
+ citations?: Citation[];
390
+ }
391
+ interface FieldError {
392
+ field?: string;
393
+ message: string;
394
+ }
395
+ interface RetryConfig {
396
+ maxAttempts?: number;
397
+ baseBackoffMs?: number;
398
+ maxBackoffMs?: number;
399
+ retryPost?: boolean;
400
+ }
401
+ interface RetryMetadata {
402
+ attempts: number;
403
+ lastStatus?: number;
404
+ lastError?: string;
405
+ }
406
+ type TransportErrorKind = "timeout" | "connect" | "request" | "empty_response" | "other";
407
+ interface RequestContext {
408
+ method: string;
409
+ path: string;
410
+ model?: ModelId;
411
+ requestId?: string;
412
+ responseId?: string;
413
+ }
414
+ interface HttpRequestMetrics {
415
+ latencyMs: number;
416
+ status?: number;
417
+ error?: string;
418
+ retries?: RetryMetadata;
419
+ context: RequestContext;
420
+ }
421
+ interface StreamFirstTokenMetrics {
422
+ latencyMs: number;
423
+ error?: string;
424
+ context: RequestContext;
425
+ }
426
+ interface TokenUsageMetrics {
427
+ usage: Usage;
428
+ context: RequestContext;
429
+ }
430
+ interface MetricsCallbacks {
431
+ httpRequest?: (metrics: HttpRequestMetrics) => void;
432
+ streamFirstToken?: (metrics: StreamFirstTokenMetrics) => void;
433
+ usage?: (metrics: TokenUsageMetrics) => void;
434
+ }
435
+ interface TraceCallbacks {
436
+ requestStart?: (context: RequestContext) => void;
437
+ requestFinish?: (info: {
438
+ context: RequestContext;
439
+ status?: number;
440
+ error?: unknown;
441
+ retries?: RetryMetadata;
442
+ latencyMs: number;
443
+ }) => void;
444
+ streamEvent?: (info: {
445
+ context: RequestContext;
446
+ event: ResponseEvent;
447
+ }) => void;
448
+ streamError?: (info: {
449
+ context: RequestContext;
450
+ error: unknown;
451
+ }) => void;
452
+ }
453
+ declare function mergeMetrics(base?: MetricsCallbacks, override?: MetricsCallbacks): MetricsCallbacks | undefined;
454
+ declare function mergeTrace(base?: TraceCallbacks, override?: TraceCallbacks): TraceCallbacks | undefined;
455
+ declare function normalizeStopReason(value?: unknown): StopReason | undefined;
456
+ declare function stopReasonToString(value?: StopReason): string | undefined;
457
+ declare function normalizeModelId(value: unknown): ModelId | undefined;
458
+ declare function modelToString(value: ModelId): string;
459
+ type ResponseEventType = "message_start" | "message_delta" | "message_stop" | "tool_use_start" | "tool_use_delta" | "tool_use_stop" | "ping" | "custom";
460
+ interface MessageStartData {
461
+ responseId?: string;
462
+ model?: string;
463
+ message?: Record<string, unknown>;
464
+ [key: string]: unknown;
465
+ }
466
+ interface MessageDeltaData {
467
+ delta?: string | {
468
+ text?: string;
469
+ [key: string]: unknown;
470
+ };
471
+ responseId?: string;
472
+ model?: string;
473
+ [key: string]: unknown;
474
+ }
475
+ interface MessageStopData {
476
+ stopReason?: StopReason;
477
+ usage?: Usage;
478
+ responseId?: string;
479
+ model?: ModelId;
480
+ [key: string]: unknown;
481
+ }
482
+ /** Incremental update to a tool call during streaming. */
483
+ interface ToolCallDelta {
484
+ index: number;
485
+ id?: string;
486
+ type?: string;
487
+ function?: FunctionCallDelta;
488
+ }
489
+ /** Incremental function call data. */
490
+ interface FunctionCallDelta {
491
+ name?: string;
492
+ arguments?: string;
493
+ }
494
+ interface ResponseEvent<T = unknown> {
495
+ type: ResponseEventType;
496
+ event: string;
497
+ data?: T;
498
+ textDelta?: string;
499
+ /** Incremental tool call update during streaming. */
500
+ toolCallDelta?: ToolCallDelta;
501
+ /** Completed tool calls when type is tool_use_stop or message_stop. */
502
+ toolCalls?: ToolCall[];
503
+ /** Tool result payload when type is tool_use_stop. */
504
+ toolResult?: unknown;
505
+ responseId?: string;
506
+ model?: ModelId;
507
+ stopReason?: StopReason;
508
+ usage?: Usage;
509
+ requestId?: string;
510
+ raw: string;
511
+ }
512
+ type StructuredJSONRecordType = "start" | "update" | "completion" | "error";
513
+ /**
514
+ * Recursively makes all properties optional.
515
+ * Useful for typing partial payloads during progressive streaming before
516
+ * all fields are complete.
517
+ *
518
+ * @example
519
+ * interface Article { title: string; body: string; }
520
+ * type PartialArticle = DeepPartial<Article>;
521
+ * // { title?: string; body?: string; }
522
+ */
523
+ type DeepPartial<T> = T extends object ? {
524
+ [P in keyof T]?: DeepPartial<T[P]>;
525
+ } : T;
526
+ interface StructuredJSONEvent<T> {
527
+ type: "update" | "completion";
528
+ payload: T;
529
+ requestId?: string;
530
+ /**
531
+ * Set of field paths that are complete (have their closing delimiter).
532
+ * Use dot notation for nested fields (e.g., "metadata.author").
533
+ * Check with completeFields.has("fieldName").
534
+ */
535
+ completeFields: Set<string>;
536
+ }
537
+ interface APICustomerRef {
538
+ id: string;
539
+ external_id: string;
540
+ owner_id: string;
541
+ }
542
+ interface APICheckoutSession {
543
+ id: string;
544
+ plan: string;
545
+ status: string;
546
+ url: string;
547
+ expires_at?: string;
548
+ completed_at?: string;
549
+ }
550
+ interface APIUsage {
551
+ input_tokens?: number;
552
+ output_tokens?: number;
553
+ total_tokens?: number;
554
+ }
555
+ interface APIResponsesResponse {
556
+ id?: string;
557
+ stop_reason?: string;
558
+ model?: string;
559
+ usage?: APIUsage;
560
+ provider?: string;
561
+ output?: OutputItem[];
562
+ citations?: Citation[];
563
+ }
564
+ interface APIKey {
565
+ id: string;
566
+ label: string;
567
+ kind: string;
568
+ createdAt: Date;
569
+ expiresAt?: Date;
570
+ lastUsedAt?: Date;
571
+ redactedKey: string;
572
+ secretKey?: string;
573
+ }
574
+
575
+ /**
576
+ * Creates a user message.
577
+ */
578
+ declare function createUserMessage(content: string): InputItem;
579
+ /**
580
+ * Creates an assistant message.
581
+ */
582
+ declare function createAssistantMessage(content: string): InputItem;
583
+ /**
584
+ * Creates a system message.
585
+ */
586
+ declare function createSystemMessage(content: string): InputItem;
587
+ /**
588
+ * Creates a tool call object.
589
+ */
590
+ declare function createToolCall(id: string, name: string, args: string, type?: ToolType): ToolCall;
591
+ /**
592
+ * Creates a function call object.
593
+ */
594
+ declare function createFunctionCall(name: string, args: string): FunctionCall;
595
+ /**
596
+ * Interface for Zod-like schema types.
597
+ * Compatible with Zod's ZodType and similar libraries.
598
+ */
599
+ interface ZodLikeSchema {
600
+ _def: {
601
+ typeName: string;
602
+ [key: string]: unknown;
603
+ };
604
+ parse(data: unknown): unknown;
605
+ safeParse(data: unknown): {
606
+ success: boolean;
607
+ data?: unknown;
608
+ error?: unknown;
609
+ };
610
+ }
611
+ /**
612
+ * Options for JSON Schema generation.
613
+ */
614
+ interface JsonSchemaOptions {
615
+ /** Whether to include $schema property. Defaults to false. */
616
+ includeSchema?: boolean;
617
+ /** Target JSON Schema version. Defaults to "draft-07". */
618
+ target?: "draft-04" | "draft-07" | "draft-2019-09" | "draft-2020-12";
619
+ }
620
+ /**
621
+ * Converts a Zod schema to JSON Schema.
622
+ * This is a simplified implementation that handles common Zod types.
623
+ * For full Zod support, consider using the 'zod-to-json-schema' package.
624
+ *
625
+ * @param schema - A Zod schema
626
+ * @param options - Optional JSON Schema generation options
627
+ * @returns A JSON Schema object
628
+ */
629
+ declare function zodToJsonSchema(schema: ZodLikeSchema, options?: JsonSchemaOptions): Record<string, unknown>;
630
+ /**
631
+ * Creates a function tool from a Zod schema.
632
+ *
633
+ * This function automatically converts a Zod schema to a JSON Schema
634
+ * and creates a tool definition. It eliminates the need to manually
635
+ * write JSON schemas for tool parameters.
636
+ *
637
+ * @example
638
+ * ```typescript
639
+ * import { z } from "zod";
640
+ * import { createFunctionToolFromSchema } from "@modelrelay/sdk";
641
+ *
642
+ * const weatherParams = z.object({
643
+ * location: z.string().describe("City name"),
644
+ * unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
645
+ * });
646
+ *
647
+ * const weatherTool = createFunctionToolFromSchema(
648
+ * "get_weather",
649
+ * "Get weather for a location",
650
+ * weatherParams
651
+ * );
652
+ * ```
653
+ *
654
+ * @param name - The tool name
655
+ * @param description - A description of what the tool does
656
+ * @param schema - A Zod schema defining the tool's parameters
657
+ * @param options - Optional JSON Schema generation options
658
+ * @returns A Tool definition with the JSON schema derived from the Zod schema
659
+ */
660
+ declare function createFunctionToolFromSchema(name: string, description: string, schema: ZodLikeSchema, options?: JsonSchemaOptions): Tool;
661
+ /**
662
+ * Creates a function tool with the given name, description, and JSON schema.
663
+ */
664
+ declare function createFunctionTool(name: string, description: string, parameters?: Record<string, unknown>): Tool;
665
+ /**
666
+ * Creates a web tool with optional domain filters and intent.
667
+ */
668
+ declare function createWebTool(options?: {
669
+ intent?: WebToolIntent;
670
+ allowedDomains?: string[];
671
+ excludedDomains?: string[];
672
+ maxUses?: number;
673
+ }): Tool;
674
+ /**
675
+ * Returns a ToolChoice that lets the model decide when to use tools.
676
+ */
677
+ declare function toolChoiceAuto(): ToolChoice;
678
+ /**
679
+ * Returns a ToolChoice that forces the model to use a tool.
680
+ */
681
+ declare function toolChoiceRequired(): ToolChoice;
682
+ /**
683
+ * Returns a ToolChoice that prevents the model from using tools.
684
+ */
685
+ declare function toolChoiceNone(): ToolChoice;
686
+ /**
687
+ * Returns true if the response contains tool calls.
688
+ */
689
+ declare function hasToolCalls(response: Response): boolean;
690
+ /**
691
+ * Returns the first tool call from a response, or undefined if none exist.
692
+ */
693
+ declare function firstToolCall(response: Response): ToolCall | undefined;
694
+ /**
695
+ * Creates a message containing the result of a tool call.
696
+ */
697
+ declare function toolResultMessage(toolCallId: string, result: unknown): InputItem;
698
+ /**
699
+ * Creates a tool result message from a ToolCall.
700
+ * Convenience wrapper around toolResultMessage using the call's ID.
701
+ */
702
+ declare function respondToToolCall(call: ToolCall, result: unknown): InputItem;
703
+ /**
704
+ * Creates an assistant message that includes tool calls.
705
+ * Used to include the assistant's tool-calling turn in conversation history.
706
+ */
707
+ declare function assistantMessageWithToolCalls(content: string, toolCalls: ToolCall[]): InputItem;
708
+ /**
709
+ * Accumulates streaming tool call deltas into complete tool calls.
710
+ */
711
+ declare class ToolCallAccumulator {
712
+ private calls;
713
+ /**
714
+ * Processes a streaming tool call delta.
715
+ * Returns true if this started a new tool call.
716
+ */
717
+ processDelta(delta: ToolCallDelta): boolean;
718
+ /**
719
+ * Returns all accumulated tool calls in index order.
720
+ */
721
+ getToolCalls(): ToolCall[];
722
+ /**
723
+ * Returns a specific tool call by index, or undefined if not found.
724
+ */
725
+ getToolCall(index: number): ToolCall | undefined;
726
+ /**
727
+ * Clears all accumulated tool calls.
728
+ */
729
+ reset(): void;
730
+ }
731
+ /**
732
+ * Error thrown when tool argument parsing or validation fails.
733
+ * Contains a descriptive message suitable for sending back to the model.
734
+ */
735
+ declare class ToolArgsError extends Error {
736
+ /** The tool call ID for correlation */
737
+ readonly toolCallId: string;
738
+ /** The tool name that was called */
739
+ readonly toolName: string;
740
+ /** The raw arguments string that failed to parse */
741
+ readonly rawArguments: string;
742
+ constructor(message: string, toolCallId: string, toolName: string, rawArguments: string);
743
+ }
744
+ /**
745
+ * Schema interface compatible with Zod, Yup, and similar validation libraries.
746
+ * Any object with a `parse` method that returns the validated type works.
747
+ */
748
+ interface Schema<T> {
749
+ parse(data: unknown): T;
750
+ }
751
+ /**
752
+ * Parses and validates tool call arguments using a schema.
753
+ *
754
+ * Works with any schema library that has a `parse` method (Zod, Yup, etc.).
755
+ * Throws a descriptive ToolArgsError if parsing or validation fails.
756
+ *
757
+ * @example
758
+ * ```typescript
759
+ * import { z } from "zod";
760
+ *
761
+ * const WeatherArgs = z.object({
762
+ * location: z.string(),
763
+ * unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
764
+ * });
765
+ *
766
+ * // In your tool handler:
767
+ * const args = parseToolArgs(toolCall, WeatherArgs);
768
+ * // args is typed as { location: string; unit: "celsius" | "fahrenheit" }
769
+ * ```
770
+ *
771
+ * @param call - The tool call containing arguments to parse
772
+ * @param schema - A schema with a `parse` method (Zod, Yup, etc.)
773
+ * @returns The parsed and validated arguments with proper types
774
+ * @throws {ToolArgsError} If JSON parsing or schema validation fails
775
+ */
776
+ declare function parseToolArgs<T>(call: ToolCall, schema: Schema<T>): T;
777
+ /**
778
+ * Attempts to parse tool arguments, returning a result object instead of throwing.
779
+ *
780
+ * @example
781
+ * ```typescript
782
+ * const result = tryParseToolArgs(toolCall, WeatherArgs);
783
+ * if (result.success) {
784
+ * console.log(result.data.location);
785
+ * } else {
786
+ * console.error(result.error.message);
787
+ * }
788
+ * ```
789
+ *
790
+ * @param call - The tool call containing arguments to parse
791
+ * @param schema - A schema with a `parse` method
792
+ * @returns An object with either { success: true, data: T } or { success: false, error: ToolArgsError }
793
+ */
794
+ declare function tryParseToolArgs<T>(call: ToolCall, schema: Schema<T>): {
795
+ success: true;
796
+ data: T;
797
+ } | {
798
+ success: false;
799
+ error: ToolArgsError;
800
+ };
801
+ /**
802
+ * Parses raw JSON arguments without schema validation.
803
+ * Useful when you want JSON parsing error handling but not schema validation.
804
+ *
805
+ * @param call - The tool call containing arguments to parse
806
+ * @returns The parsed JSON as an unknown type
807
+ * @throws {ToolArgsError} If JSON parsing fails
808
+ */
809
+ declare function parseToolArgsRaw(call: ToolCall): unknown;
810
+ /**
811
+ * Handler function type for tool execution.
812
+ * Can be sync or async, receives parsed arguments and returns a result.
813
+ */
814
+ type ToolHandler<T = unknown, R = unknown> = (args: T, call: ToolCall) => R | Promise<R>;
815
+ /**
816
+ * Result of executing a tool call.
817
+ */
818
+ interface ToolExecutionResult {
819
+ toolCallId: string;
820
+ toolName: string;
821
+ result: unknown;
822
+ error?: string;
823
+ /**
824
+ * True if the error is due to malformed arguments (JSON parse or validation failure)
825
+ * and the model should be given a chance to retry with corrected arguments.
826
+ */
827
+ isRetryable?: boolean;
828
+ }
829
+ /**
830
+ * Registry for mapping tool names to handler functions with automatic dispatch.
831
+ *
832
+ * @example
833
+ * ```typescript
834
+ * const registry = new ToolRegistry()
835
+ * .register("get_weather", async (args) => {
836
+ * return { temp: 72, unit: "fahrenheit" };
837
+ * })
838
+ * .register("search", async (args) => {
839
+ * return { results: ["result1", "result2"] };
840
+ * });
841
+ *
842
+ * // Execute all tool calls from a response
843
+ * const results = await registry.executeAll(response.toolCalls);
844
+ *
845
+ * // Convert results to messages for the next request
846
+ * const messages = registry.resultsToMessages(results);
847
+ * ```
848
+ */
849
+ declare class ToolRegistry {
850
+ private handlers;
851
+ /**
852
+ * Registers a handler function for a tool name.
853
+ * @param name - The tool name (must match the function name in the tool definition)
854
+ * @param handler - Function to execute when this tool is called
855
+ * @returns this for chaining
856
+ */
857
+ register<T = unknown, R = unknown>(name: string, handler: ToolHandler<T, R>): this;
858
+ /**
859
+ * Unregisters a tool handler.
860
+ * @param name - The tool name to unregister
861
+ * @returns true if the handler was removed, false if it didn't exist
862
+ */
863
+ unregister(name: string): boolean;
864
+ /**
865
+ * Checks if a handler is registered for the given tool name.
866
+ */
867
+ has(name: string): boolean;
868
+ /**
869
+ * Returns the list of registered tool names.
870
+ */
871
+ getRegisteredTools(): string[];
872
+ /**
873
+ * Executes a single tool call.
874
+ * @param call - The tool call to execute
875
+ * @returns The execution result
876
+ */
877
+ execute(call: ToolCall): Promise<ToolExecutionResult>;
878
+ /**
879
+ * Executes multiple tool calls in parallel.
880
+ * @param calls - Array of tool calls to execute
881
+ * @returns Array of execution results in the same order as input
882
+ */
883
+ executeAll(calls: ToolCall[]): Promise<ToolExecutionResult[]>;
884
+ /**
885
+ * Converts execution results to tool result messages.
886
+ * Useful for appending to the conversation history.
887
+ * @param results - Array of execution results
888
+ * @returns Array of tool result input items (role "tool")
889
+ */
890
+ resultsToMessages(results: ToolExecutionResult[]): InputItem[];
891
+ }
892
+ /**
893
+ * Formats a tool execution error into a message suitable for sending back to the model.
894
+ * The message is designed to help the model understand what went wrong and correct it.
895
+ *
896
+ * @example
897
+ * ```typescript
898
+ * const result = await registry.execute(toolCall);
899
+ * if (result.error && result.isRetryable) {
900
+ * const errorMessage = formatToolErrorForModel(result);
901
+ * messages.push(toolResultMessage(result.toolCallId, errorMessage));
902
+ * // Continue conversation to let model retry
903
+ * }
904
+ * ```
905
+ */
906
+ declare function formatToolErrorForModel(result: ToolExecutionResult): string;
907
+ /**
908
+ * Checks if any results have retryable errors.
909
+ *
910
+ * @example
911
+ * ```typescript
912
+ * const results = await registry.executeAll(toolCalls);
913
+ * if (hasRetryableErrors(results)) {
914
+ * // Send error messages back to model and continue conversation
915
+ * }
916
+ * ```
917
+ */
918
+ declare function hasRetryableErrors(results: ToolExecutionResult[]): boolean;
919
+ /**
920
+ * Filters results to only those with retryable errors.
921
+ */
922
+ declare function getRetryableErrors(results: ToolExecutionResult[]): ToolExecutionResult[];
923
+ /**
924
+ * Creates tool result messages for retryable errors, formatted to help the model correct them.
925
+ *
926
+ * @example
927
+ * ```typescript
928
+ * const results = await registry.executeAll(toolCalls);
929
+ * if (hasRetryableErrors(results)) {
930
+ * const retryMessages = createRetryMessages(results);
931
+ * messages.push(...retryMessages);
932
+ * // Make another API call to let model retry
933
+ * }
934
+ * ```
935
+ */
936
+ declare function createRetryMessages(results: ToolExecutionResult[]): InputItem[];
937
+ /**
938
+ * Options for executeWithRetry.
939
+ */
940
+ interface RetryOptions {
941
+ /**
942
+ * Maximum number of retry attempts for parse/validation errors.
943
+ * @default 2
944
+ */
945
+ maxRetries?: number;
946
+ /**
947
+ * Callback invoked when a retryable error occurs.
948
+ * Should return new tool calls from the model's response.
949
+ * If not provided, executeWithRetry will not retry automatically.
950
+ *
951
+ * @param errorMessages - Messages to send back to the model
952
+ * @param attempt - Current attempt number (1-based)
953
+ * @returns New tool calls from the model, or empty array to stop retrying
954
+ */
955
+ onRetry?: (errorMessages: InputItem[], attempt: number) => Promise<ToolCall[]>;
956
+ }
957
+ /**
958
+ * Executes tool calls with automatic retry on parse/validation errors.
959
+ *
960
+ * This is a higher-level utility that wraps registry.executeAll with retry logic.
961
+ * When a retryable error occurs, it calls the onRetry callback to get new tool calls
962
+ * from the model and continues execution.
963
+ *
964
+ * **Result Preservation**: Successful results are preserved across retries. If you
965
+ * execute multiple tool calls and only some fail, the successful results are kept
966
+ * and merged with the results from retry attempts. Results are keyed by toolCallId,
967
+ * so if a retry returns a call with the same ID as a previous result, the newer
968
+ * result will replace it.
969
+ *
970
+ * @example
971
+ * ```typescript
972
+ * const results = await executeWithRetry(registry, toolCalls, {
973
+ * maxRetries: 2,
974
+ * onRetry: async (errorMessages, attempt) => {
975
+ * console.log(`Retry attempt ${attempt}`);
976
+ * // Add error messages to conversation and call the model again
977
+ * messages.push(assistantMessageWithToolCalls("", toolCalls));
978
+ * messages.push(...errorMessages);
979
+ * const req = client.responses
980
+ * .new()
981
+ * .model("...")
982
+ * .input(messages)
983
+ * .tools(tools)
984
+ * .build();
985
+ * const response = await client.responses.create(req);
986
+ * return firstToolCall(response) ? [firstToolCall(response)!] : [];
987
+ * },
988
+ * });
989
+ * ```
990
+ *
991
+ * @param registry - The tool registry to use for execution
992
+ * @param toolCalls - Initial tool calls to execute
993
+ * @param options - Retry configuration
994
+ * @returns Final execution results after all retries, including preserved successes
995
+ */
996
+ declare function executeWithRetry(registry: ToolRegistry, toolCalls: ToolCall[], options?: RetryOptions): Promise<ToolExecutionResult[]>;
997
+
998
+ export { getRetryableErrors as $, type ApiKey as A, createSystemMessage as B, type CustomerTokenRequest as C, DEFAULT_BASE_URL as D, toolResultMessage as E, type FieldError as F, type GetOrCreateCustomerTokenRequest as G, respondToToolCall as H, type InputItem as I, assistantMessageWithToolCalls as J, createToolCall as K, createFunctionCall as L, type MetricsCallbacks as M, ToolCallAccumulator as N, type OutputFormat as O, type ProviderId as P, zodToJsonSchema as Q, type RetryConfig as R, type StructuredJSONEvent as S, type TraceCallbacks as T, parseToolArgs as U, tryParseToolArgs as V, parseToolArgsRaw as W, ToolArgsError as X, formatToolErrorForModel as Y, type ZodLikeSchema as Z, hasRetryableErrors as _, type RequestContext as a, normalizeModelId as a$, createRetryMessages as a0, executeWithRetry as a1, type JsonSchemaOptions as a2, type Schema as a3, type ToolHandler as a4, type RetryOptions as a5, SDK_VERSION as a6, DEFAULT_CLIENT_HEADER as a7, DEFAULT_CONNECT_TIMEOUT_MS as a8, DEFAULT_REQUEST_TIMEOUT_MS as a9, type InputItemType as aA, OutputItemTypes as aB, type OutputItemType as aC, type OutputItem as aD, ToolTypes as aE, type ToolType as aF, WebToolIntents as aG, type WebToolIntent as aH, type FunctionTool as aI, type WebSearchConfig as aJ, type XSearchConfig as aK, type CodeExecConfig as aL, ToolChoiceTypes as aM, type ToolChoiceType as aN, type FunctionCall as aO, type ToolCall as aP, OutputFormatTypes as aQ, type OutputFormatType as aR, type JSONSchemaFormat as aS, type Citation as aT, type HttpRequestMetrics as aU, type StreamFirstTokenMetrics as aV, type TokenUsageMetrics as aW, mergeMetrics as aX, mergeTrace as aY, normalizeStopReason as aZ, stopReasonToString as a_, type NonEmptyArray as aa, StopReasons as ab, type KnownStopReason as ac, type StopReason as ad, asProviderId as ae, asModelId as af, asTierCode as ag, SubscriptionStatuses as ah, type SubscriptionStatusKind as ai, BillingProviders as aj, type BillingProvider as ak, type CustomerMetadata as al, type ModelRelayBaseOptions as am, type ModelRelayTokenOptions as an, type ModelRelayTokenProviderOptions as ao, type TokenType as ap, type Usage as aq, createUsage as ar, type UsageSummary as as, type Project as at, MessageRoles as au, type MessageRole as av, ContentPartTypes as aw, type ContentPartType as ax, type ContentPart as ay, InputItemTypes as az, type TokenProvider as b, modelToString as b0, type ResponseEventType as b1, type MessageStartData as b2, type MessageDeltaData as b3, type MessageStopData as b4, type ToolCallDelta as b5, type FunctionCallDelta as b6, type StructuredJSONRecordType as b7, type DeepPartial as b8, type APICustomerRef as b9, type APICheckoutSession as ba, type APIUsage as bb, type APIResponsesResponse as bc, type APIKey as bd, type CustomerToken as c, type ModelId as d, type Tool as e, type ToolChoice as f, type ResponseEvent as g, type Response as h, type RetryMetadata as i, type TransportErrorKind as j, ToolRegistry as k, type ToolExecutionResult as l, type TierCode as m, type SecretKey as n, type ModelRelayKeyOptions as o, type ModelRelayOptions as p, createFunctionTool as q, createFunctionToolFromSchema as r, createWebTool as s, toolChoiceAuto as t, toolChoiceRequired as u, toolChoiceNone as v, hasToolCalls as w, firstToolCall as x, createUserMessage as y, createAssistantMessage as z };