@modelrelay/sdk 8.1.0 → 9.0.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.
- package/dist/chunk-AQJ4VKNC.js +1199 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/tools-QkA_kWul.d.cts +1042 -0
- package/dist/tools-QkA_kWul.d.ts +1042 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1042 @@
|
|
|
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
|
+
* Tier code for customers without an existing subscription.
|
|
203
|
+
* When provided, a billing profile is created for the customer with this tier.
|
|
204
|
+
*/
|
|
205
|
+
tierCode?: TierCode;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Request to get or create a customer token.
|
|
209
|
+
* This upserts the customer (creating if needed) then mints a token.
|
|
210
|
+
*/
|
|
211
|
+
interface GetOrCreateCustomerTokenRequest {
|
|
212
|
+
/** Your external customer identifier (required). */
|
|
213
|
+
externalId: string;
|
|
214
|
+
/** Customer email address (required for customer creation). */
|
|
215
|
+
email: string;
|
|
216
|
+
/**
|
|
217
|
+
* Tier code for the customer's subscription.
|
|
218
|
+
* Required for new customers on managed billing projects.
|
|
219
|
+
* Existing customers use their current tier if not provided.
|
|
220
|
+
*/
|
|
221
|
+
tierCode: TierCode;
|
|
222
|
+
/** Optional customer metadata. */
|
|
223
|
+
metadata?: CustomerMetadata;
|
|
224
|
+
/** Optional token TTL in seconds (default: 7 days, max: 30 days). */
|
|
225
|
+
ttlSeconds?: number;
|
|
226
|
+
}
|
|
227
|
+
interface CustomerToken {
|
|
228
|
+
token: string;
|
|
229
|
+
expiresAt: Date;
|
|
230
|
+
expiresIn: number;
|
|
231
|
+
tokenType: TokenType;
|
|
232
|
+
projectId: string;
|
|
233
|
+
/** Identity customer ID (always present for valid customer tokens). */
|
|
234
|
+
customerId?: string;
|
|
235
|
+
/** Billing profile ID for managed billing customers. */
|
|
236
|
+
billingProfileId?: string;
|
|
237
|
+
customerExternalId: string;
|
|
238
|
+
/** Optional for BYOB (external billing) projects */
|
|
239
|
+
tierCode?: TierCode;
|
|
240
|
+
}
|
|
241
|
+
interface Usage {
|
|
242
|
+
inputTokens: number;
|
|
243
|
+
outputTokens: number;
|
|
244
|
+
totalTokens: number;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Creates a Usage object with automatic totalTokens calculation if not provided.
|
|
248
|
+
*/
|
|
249
|
+
declare function createUsage(inputTokens: number, outputTokens: number, totalTokens?: number): Usage;
|
|
250
|
+
interface UsageSummary {
|
|
251
|
+
plan: string;
|
|
252
|
+
planType?: string;
|
|
253
|
+
windowStart?: Date | string;
|
|
254
|
+
windowEnd?: Date | string;
|
|
255
|
+
limit?: number;
|
|
256
|
+
used?: number;
|
|
257
|
+
images?: number;
|
|
258
|
+
actionsLimit?: number;
|
|
259
|
+
actionsUsed?: number;
|
|
260
|
+
remaining?: number;
|
|
261
|
+
state?: string;
|
|
262
|
+
}
|
|
263
|
+
interface Project {
|
|
264
|
+
id: string;
|
|
265
|
+
name: string;
|
|
266
|
+
description?: string;
|
|
267
|
+
createdAt?: Date;
|
|
268
|
+
updatedAt?: Date;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Valid roles for chat messages.
|
|
272
|
+
*/
|
|
273
|
+
declare const MessageRoles: {
|
|
274
|
+
readonly User: "user";
|
|
275
|
+
readonly Assistant: "assistant";
|
|
276
|
+
readonly System: "system";
|
|
277
|
+
readonly Tool: "tool";
|
|
278
|
+
};
|
|
279
|
+
type MessageRole = (typeof MessageRoles)[keyof typeof MessageRoles];
|
|
280
|
+
declare const ContentPartTypes: {
|
|
281
|
+
readonly Text: "text";
|
|
282
|
+
};
|
|
283
|
+
type ContentPartType = (typeof ContentPartTypes)[keyof typeof ContentPartTypes];
|
|
284
|
+
type ContentPart = {
|
|
285
|
+
type: "text";
|
|
286
|
+
text: string;
|
|
287
|
+
};
|
|
288
|
+
declare const InputItemTypes: {
|
|
289
|
+
readonly Message: "message";
|
|
290
|
+
};
|
|
291
|
+
type InputItemType = (typeof InputItemTypes)[keyof typeof InputItemTypes];
|
|
292
|
+
type InputItem = {
|
|
293
|
+
type: "message";
|
|
294
|
+
role: MessageRole;
|
|
295
|
+
content: ContentPart[];
|
|
296
|
+
toolCalls?: ToolCall[];
|
|
297
|
+
toolCallId?: string;
|
|
298
|
+
};
|
|
299
|
+
declare const OutputItemTypes: {
|
|
300
|
+
readonly Message: "message";
|
|
301
|
+
};
|
|
302
|
+
type OutputItemType = (typeof OutputItemTypes)[keyof typeof OutputItemTypes];
|
|
303
|
+
type OutputItem = {
|
|
304
|
+
type: "message";
|
|
305
|
+
role: MessageRole;
|
|
306
|
+
content: ContentPart[];
|
|
307
|
+
toolCalls?: ToolCall[];
|
|
308
|
+
};
|
|
309
|
+
declare const ToolTypes: {
|
|
310
|
+
readonly Function: "function";
|
|
311
|
+
readonly XSearch: "x_search";
|
|
312
|
+
readonly CodeExecution: "code_execution";
|
|
313
|
+
};
|
|
314
|
+
type ToolType = (typeof ToolTypes)[keyof typeof ToolTypes];
|
|
315
|
+
interface FunctionTool {
|
|
316
|
+
name: string;
|
|
317
|
+
description?: string;
|
|
318
|
+
parameters?: Record<string, unknown>;
|
|
319
|
+
}
|
|
320
|
+
interface XSearchConfig {
|
|
321
|
+
allowedHandles?: string[];
|
|
322
|
+
excludedHandles?: string[];
|
|
323
|
+
fromDate?: string;
|
|
324
|
+
toDate?: string;
|
|
325
|
+
}
|
|
326
|
+
interface CodeExecConfig {
|
|
327
|
+
language?: string;
|
|
328
|
+
timeoutMs?: number;
|
|
329
|
+
}
|
|
330
|
+
interface Tool {
|
|
331
|
+
type: ToolType;
|
|
332
|
+
function?: FunctionTool;
|
|
333
|
+
xSearch?: XSearchConfig;
|
|
334
|
+
codeExecution?: CodeExecConfig;
|
|
335
|
+
}
|
|
336
|
+
declare const ToolChoiceTypes: {
|
|
337
|
+
readonly Auto: "auto";
|
|
338
|
+
readonly Required: "required";
|
|
339
|
+
readonly None: "none";
|
|
340
|
+
};
|
|
341
|
+
type ToolChoiceType = (typeof ToolChoiceTypes)[keyof typeof ToolChoiceTypes];
|
|
342
|
+
interface ToolChoice {
|
|
343
|
+
type: ToolChoiceType;
|
|
344
|
+
/**
|
|
345
|
+
* Optional function tool name to force.
|
|
346
|
+
* Only valid when type is "required".
|
|
347
|
+
*/
|
|
348
|
+
function?: string;
|
|
349
|
+
}
|
|
350
|
+
interface FunctionCall {
|
|
351
|
+
name: string;
|
|
352
|
+
arguments: string;
|
|
353
|
+
}
|
|
354
|
+
interface ToolCall {
|
|
355
|
+
id: string;
|
|
356
|
+
type: ToolType;
|
|
357
|
+
function?: FunctionCall;
|
|
358
|
+
}
|
|
359
|
+
declare const OutputFormatTypes: {
|
|
360
|
+
readonly Text: "text";
|
|
361
|
+
readonly JsonSchema: "json_schema";
|
|
362
|
+
};
|
|
363
|
+
type OutputFormatType = (typeof OutputFormatTypes)[keyof typeof OutputFormatTypes];
|
|
364
|
+
interface JSONSchemaFormat {
|
|
365
|
+
name: string;
|
|
366
|
+
description?: string;
|
|
367
|
+
schema: Record<string, unknown>;
|
|
368
|
+
strict?: boolean;
|
|
369
|
+
}
|
|
370
|
+
interface OutputFormat {
|
|
371
|
+
type: OutputFormatType;
|
|
372
|
+
json_schema?: JSONSchemaFormat;
|
|
373
|
+
}
|
|
374
|
+
interface Citation {
|
|
375
|
+
url?: string;
|
|
376
|
+
title?: string;
|
|
377
|
+
}
|
|
378
|
+
interface Response {
|
|
379
|
+
id: string;
|
|
380
|
+
output: OutputItem[];
|
|
381
|
+
stopReason?: StopReason;
|
|
382
|
+
model: ModelId;
|
|
383
|
+
usage: Usage;
|
|
384
|
+
requestId?: string;
|
|
385
|
+
provider?: ProviderId;
|
|
386
|
+
citations?: Citation[];
|
|
387
|
+
}
|
|
388
|
+
interface FieldError {
|
|
389
|
+
field?: string;
|
|
390
|
+
message: string;
|
|
391
|
+
}
|
|
392
|
+
interface RetryConfig {
|
|
393
|
+
maxAttempts?: number;
|
|
394
|
+
baseBackoffMs?: number;
|
|
395
|
+
maxBackoffMs?: number;
|
|
396
|
+
retryPost?: boolean;
|
|
397
|
+
}
|
|
398
|
+
interface RetryMetadata {
|
|
399
|
+
attempts: number;
|
|
400
|
+
lastStatus?: number;
|
|
401
|
+
lastError?: string;
|
|
402
|
+
}
|
|
403
|
+
type TransportErrorKind = "timeout" | "connect" | "request" | "empty_response" | "other";
|
|
404
|
+
interface RequestContext {
|
|
405
|
+
method: string;
|
|
406
|
+
path: string;
|
|
407
|
+
model?: ModelId;
|
|
408
|
+
requestId?: string;
|
|
409
|
+
responseId?: string;
|
|
410
|
+
}
|
|
411
|
+
interface HttpRequestMetrics {
|
|
412
|
+
latencyMs: number;
|
|
413
|
+
status?: number;
|
|
414
|
+
error?: string;
|
|
415
|
+
retries?: RetryMetadata;
|
|
416
|
+
context: RequestContext;
|
|
417
|
+
}
|
|
418
|
+
interface StreamFirstTokenMetrics {
|
|
419
|
+
latencyMs: number;
|
|
420
|
+
error?: string;
|
|
421
|
+
context: RequestContext;
|
|
422
|
+
}
|
|
423
|
+
interface TokenUsageMetrics {
|
|
424
|
+
usage: Usage;
|
|
425
|
+
context: RequestContext;
|
|
426
|
+
}
|
|
427
|
+
interface MetricsCallbacks {
|
|
428
|
+
httpRequest?: (metrics: HttpRequestMetrics) => void;
|
|
429
|
+
streamFirstToken?: (metrics: StreamFirstTokenMetrics) => void;
|
|
430
|
+
usage?: (metrics: TokenUsageMetrics) => void;
|
|
431
|
+
}
|
|
432
|
+
interface TraceCallbacks {
|
|
433
|
+
requestStart?: (context: RequestContext) => void;
|
|
434
|
+
requestFinish?: (info: {
|
|
435
|
+
context: RequestContext;
|
|
436
|
+
status?: number;
|
|
437
|
+
error?: unknown;
|
|
438
|
+
retries?: RetryMetadata;
|
|
439
|
+
latencyMs: number;
|
|
440
|
+
}) => void;
|
|
441
|
+
streamEvent?: (info: {
|
|
442
|
+
context: RequestContext;
|
|
443
|
+
event: ResponseEvent;
|
|
444
|
+
}) => void;
|
|
445
|
+
streamError?: (info: {
|
|
446
|
+
context: RequestContext;
|
|
447
|
+
error: unknown;
|
|
448
|
+
}) => void;
|
|
449
|
+
}
|
|
450
|
+
declare function mergeMetrics(base?: MetricsCallbacks, override?: MetricsCallbacks): MetricsCallbacks | undefined;
|
|
451
|
+
declare function mergeTrace(base?: TraceCallbacks, override?: TraceCallbacks): TraceCallbacks | undefined;
|
|
452
|
+
declare function normalizeStopReason(value?: unknown): StopReason | undefined;
|
|
453
|
+
declare function stopReasonToString(value?: StopReason): string | undefined;
|
|
454
|
+
declare function normalizeModelId(value: unknown): ModelId | undefined;
|
|
455
|
+
declare function modelToString(value: ModelId): string;
|
|
456
|
+
type ResponseEventType = "message_start" | "message_delta" | "message_stop" | "tool_use_start" | "tool_use_delta" | "tool_use_stop" | "ping" | "custom";
|
|
457
|
+
interface MessageStartData {
|
|
458
|
+
responseId?: string;
|
|
459
|
+
model?: string;
|
|
460
|
+
message?: Record<string, unknown>;
|
|
461
|
+
[key: string]: unknown;
|
|
462
|
+
}
|
|
463
|
+
interface MessageDeltaData {
|
|
464
|
+
delta?: string | {
|
|
465
|
+
text?: string;
|
|
466
|
+
[key: string]: unknown;
|
|
467
|
+
};
|
|
468
|
+
responseId?: string;
|
|
469
|
+
model?: string;
|
|
470
|
+
[key: string]: unknown;
|
|
471
|
+
}
|
|
472
|
+
interface MessageStopData {
|
|
473
|
+
stopReason?: StopReason;
|
|
474
|
+
usage?: Usage;
|
|
475
|
+
responseId?: string;
|
|
476
|
+
model?: ModelId;
|
|
477
|
+
[key: string]: unknown;
|
|
478
|
+
}
|
|
479
|
+
/** Incremental update to a tool call during streaming. */
|
|
480
|
+
interface ToolCallDelta {
|
|
481
|
+
index: number;
|
|
482
|
+
id?: string;
|
|
483
|
+
type?: string;
|
|
484
|
+
function?: FunctionCallDelta;
|
|
485
|
+
}
|
|
486
|
+
/** Incremental function call data. */
|
|
487
|
+
interface FunctionCallDelta {
|
|
488
|
+
name?: string;
|
|
489
|
+
arguments?: string;
|
|
490
|
+
}
|
|
491
|
+
interface ResponseEvent<T = unknown> {
|
|
492
|
+
type: ResponseEventType;
|
|
493
|
+
event: string;
|
|
494
|
+
data?: T;
|
|
495
|
+
textDelta?: string;
|
|
496
|
+
/** Incremental tool call update during streaming. */
|
|
497
|
+
toolCallDelta?: ToolCallDelta;
|
|
498
|
+
/** Completed tool calls when type is tool_use_stop or message_stop. */
|
|
499
|
+
toolCalls?: ToolCall[];
|
|
500
|
+
/** Tool result payload when type is tool_use_stop. */
|
|
501
|
+
toolResult?: unknown;
|
|
502
|
+
responseId?: string;
|
|
503
|
+
model?: ModelId;
|
|
504
|
+
stopReason?: StopReason;
|
|
505
|
+
usage?: Usage;
|
|
506
|
+
requestId?: string;
|
|
507
|
+
raw: string;
|
|
508
|
+
}
|
|
509
|
+
type StructuredJSONRecordType = "start" | "update" | "completion" | "error";
|
|
510
|
+
/**
|
|
511
|
+
* Recursively makes all properties optional.
|
|
512
|
+
* Useful for typing partial payloads during progressive streaming before
|
|
513
|
+
* all fields are complete.
|
|
514
|
+
*
|
|
515
|
+
* @example
|
|
516
|
+
* interface Article { title: string; body: string; }
|
|
517
|
+
* type PartialArticle = DeepPartial<Article>;
|
|
518
|
+
* // { title?: string; body?: string; }
|
|
519
|
+
*/
|
|
520
|
+
type DeepPartial<T> = T extends object ? {
|
|
521
|
+
[P in keyof T]?: DeepPartial<T[P]>;
|
|
522
|
+
} : T;
|
|
523
|
+
interface StructuredJSONEvent<T> {
|
|
524
|
+
type: "update" | "completion";
|
|
525
|
+
payload: T;
|
|
526
|
+
requestId?: string;
|
|
527
|
+
/**
|
|
528
|
+
* Set of field paths that are complete (have their closing delimiter).
|
|
529
|
+
* Use dot notation for nested fields (e.g., "metadata.author").
|
|
530
|
+
* Check with completeFields.has("fieldName").
|
|
531
|
+
*/
|
|
532
|
+
completeFields: Set<string>;
|
|
533
|
+
}
|
|
534
|
+
interface APICustomerRef {
|
|
535
|
+
id: string;
|
|
536
|
+
external_id: string;
|
|
537
|
+
owner_id: string;
|
|
538
|
+
}
|
|
539
|
+
interface APICheckoutSession {
|
|
540
|
+
id: string;
|
|
541
|
+
plan: string;
|
|
542
|
+
status: string;
|
|
543
|
+
url: string;
|
|
544
|
+
expires_at?: string;
|
|
545
|
+
completed_at?: string;
|
|
546
|
+
}
|
|
547
|
+
interface APIUsage {
|
|
548
|
+
input_tokens?: number;
|
|
549
|
+
output_tokens?: number;
|
|
550
|
+
total_tokens?: number;
|
|
551
|
+
}
|
|
552
|
+
interface APIResponsesResponse {
|
|
553
|
+
id?: string;
|
|
554
|
+
stop_reason?: string;
|
|
555
|
+
model?: string;
|
|
556
|
+
usage?: APIUsage;
|
|
557
|
+
provider?: string;
|
|
558
|
+
output?: OutputItem[];
|
|
559
|
+
citations?: Citation[];
|
|
560
|
+
}
|
|
561
|
+
interface APIKey {
|
|
562
|
+
id: string;
|
|
563
|
+
label: string;
|
|
564
|
+
kind: string;
|
|
565
|
+
createdAt: Date;
|
|
566
|
+
expiresAt?: Date;
|
|
567
|
+
lastUsedAt?: Date;
|
|
568
|
+
redactedKey: string;
|
|
569
|
+
secretKey?: string;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Creates a user message.
|
|
574
|
+
*/
|
|
575
|
+
declare function createUserMessage(content: string): InputItem;
|
|
576
|
+
/**
|
|
577
|
+
* Creates an assistant message.
|
|
578
|
+
*/
|
|
579
|
+
declare function createAssistantMessage(content: string): InputItem;
|
|
580
|
+
/**
|
|
581
|
+
* Creates a system message.
|
|
582
|
+
*/
|
|
583
|
+
declare function createSystemMessage(content: string): InputItem;
|
|
584
|
+
/**
|
|
585
|
+
* Creates a tool call object.
|
|
586
|
+
*/
|
|
587
|
+
declare function createToolCall(id: string, name: string, args: string, type?: ToolType): ToolCall;
|
|
588
|
+
/**
|
|
589
|
+
* Creates a function call object.
|
|
590
|
+
*/
|
|
591
|
+
declare function createFunctionCall(name: string, args: string): FunctionCall;
|
|
592
|
+
/**
|
|
593
|
+
* Public interface for Zod-like schema types.
|
|
594
|
+
*
|
|
595
|
+
* This interface is designed to accept actual Zod schemas without requiring
|
|
596
|
+
* an index signature on `_def`, which Zod's types don't expose.
|
|
597
|
+
* Use this type in public APIs that accept schemas.
|
|
598
|
+
*/
|
|
599
|
+
interface AnySchema {
|
|
600
|
+
_def: {
|
|
601
|
+
typeName: string;
|
|
602
|
+
};
|
|
603
|
+
parse(data: unknown): unknown;
|
|
604
|
+
safeParse(data: unknown): {
|
|
605
|
+
success: boolean;
|
|
606
|
+
data?: unknown;
|
|
607
|
+
error?: unknown;
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Interface for Zod-like schema types with index signature.
|
|
612
|
+
*
|
|
613
|
+
* The index signature allows dynamic property access on `_def` which is needed
|
|
614
|
+
* for schema conversion (accessing checks, shape, items, etc.).
|
|
615
|
+
* For accepting actual Zod schemas in public APIs, use AnySchema instead.
|
|
616
|
+
*/
|
|
617
|
+
interface ZodLikeSchema {
|
|
618
|
+
_def: {
|
|
619
|
+
typeName: string;
|
|
620
|
+
};
|
|
621
|
+
parse(data: unknown): unknown;
|
|
622
|
+
safeParse(data: unknown): {
|
|
623
|
+
success: boolean;
|
|
624
|
+
data?: unknown;
|
|
625
|
+
error?: unknown;
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Options for JSON Schema generation.
|
|
630
|
+
*/
|
|
631
|
+
interface JsonSchemaOptions {
|
|
632
|
+
/** Whether to include $schema property. Defaults to false. */
|
|
633
|
+
includeSchema?: boolean;
|
|
634
|
+
/** Target JSON Schema version. Defaults to "draft-07". */
|
|
635
|
+
target?: "draft-04" | "draft-07" | "draft-2019-09" | "draft-2020-12";
|
|
636
|
+
}
|
|
637
|
+
type InferSchema<S extends ZodLikeSchema> = S extends {
|
|
638
|
+
parse(data: unknown): infer T;
|
|
639
|
+
} ? T : never;
|
|
640
|
+
type TypedFunctionTool<S extends ZodLikeSchema> = Tool & {
|
|
641
|
+
type: typeof ToolTypes.Function;
|
|
642
|
+
function: FunctionTool;
|
|
643
|
+
_schema: S;
|
|
644
|
+
};
|
|
645
|
+
type TypedToolCall<S extends ZodLikeSchema> = Omit<ToolCall, "function"> & {
|
|
646
|
+
function: Omit<FunctionCall, "arguments"> & {
|
|
647
|
+
arguments: InferSchema<S>;
|
|
648
|
+
};
|
|
649
|
+
};
|
|
650
|
+
/**
|
|
651
|
+
* Converts a Zod schema to JSON Schema.
|
|
652
|
+
* This is a simplified implementation that handles common Zod types.
|
|
653
|
+
* For full Zod support, consider using the 'zod-to-json-schema' package.
|
|
654
|
+
*
|
|
655
|
+
* @param schema - A Zod schema
|
|
656
|
+
* @param options - Optional JSON Schema generation options
|
|
657
|
+
* @returns A JSON Schema object
|
|
658
|
+
*/
|
|
659
|
+
declare function zodToJsonSchema(schema: ZodLikeSchema, options?: JsonSchemaOptions): Record<string, unknown>;
|
|
660
|
+
/**
|
|
661
|
+
* Creates a typed function tool from a Zod schema with attached schema metadata.
|
|
662
|
+
*
|
|
663
|
+
* This function creates a tool that includes the original schema as non-enumerable
|
|
664
|
+
* metadata, enabling typed argument extraction via parseTypedToolCall and getTypedToolCall.
|
|
665
|
+
*
|
|
666
|
+
* @example
|
|
667
|
+
* ```typescript
|
|
668
|
+
* import { z } from "zod";
|
|
669
|
+
*
|
|
670
|
+
* const tool = createTypedTool({
|
|
671
|
+
* name: "get_weather",
|
|
672
|
+
* description: "Get weather for a location",
|
|
673
|
+
* parameters: z.object({
|
|
674
|
+
* location: z.string().describe("City name"),
|
|
675
|
+
* unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
|
|
676
|
+
* }),
|
|
677
|
+
* });
|
|
678
|
+
*
|
|
679
|
+
* // Later, extract typed arguments:
|
|
680
|
+
* const typedCall = getTypedToolCall(response, tool);
|
|
681
|
+
* console.log(typedCall?.function.arguments.location); // Typed as string
|
|
682
|
+
* ```
|
|
683
|
+
*/
|
|
684
|
+
declare function createTypedTool<S extends ZodLikeSchema>(def: {
|
|
685
|
+
name: string;
|
|
686
|
+
description: string;
|
|
687
|
+
parameters: S;
|
|
688
|
+
options?: JsonSchemaOptions;
|
|
689
|
+
}): TypedFunctionTool<S>;
|
|
690
|
+
/**
|
|
691
|
+
* Creates a function tool with the given name, description, and JSON schema.
|
|
692
|
+
*/
|
|
693
|
+
declare function createFunctionTool(name: string, description: string, parameters?: Record<string, unknown>): Tool;
|
|
694
|
+
/**
|
|
695
|
+
* Returns a ToolChoice that lets the model decide when to use tools.
|
|
696
|
+
*/
|
|
697
|
+
declare function toolChoiceAuto(): ToolChoice;
|
|
698
|
+
/**
|
|
699
|
+
* Returns a ToolChoice that forces the model to use a tool.
|
|
700
|
+
*/
|
|
701
|
+
declare function toolChoiceRequired(): ToolChoice;
|
|
702
|
+
/**
|
|
703
|
+
* Returns a ToolChoice that prevents the model from using tools.
|
|
704
|
+
*/
|
|
705
|
+
declare function toolChoiceNone(): ToolChoice;
|
|
706
|
+
/**
|
|
707
|
+
* Returns true if the response contains tool calls.
|
|
708
|
+
*/
|
|
709
|
+
declare function hasToolCalls(response: Response): boolean;
|
|
710
|
+
/**
|
|
711
|
+
* Returns the first tool call from a response, or undefined if none exist.
|
|
712
|
+
*/
|
|
713
|
+
declare function firstToolCall(response: Response): ToolCall | undefined;
|
|
714
|
+
/**
|
|
715
|
+
* Creates a message containing the result of a tool call.
|
|
716
|
+
*/
|
|
717
|
+
declare function toolResultMessage(toolCallId: string, result: unknown): InputItem;
|
|
718
|
+
/**
|
|
719
|
+
* Creates a tool result message from a ToolCall.
|
|
720
|
+
* Convenience wrapper around toolResultMessage using the call's ID.
|
|
721
|
+
*/
|
|
722
|
+
declare function respondToToolCall(call: ToolCall, result: unknown): InputItem;
|
|
723
|
+
/**
|
|
724
|
+
* Creates an assistant message that includes tool calls.
|
|
725
|
+
* Used to include the assistant's tool-calling turn in conversation history.
|
|
726
|
+
*/
|
|
727
|
+
declare function assistantMessageWithToolCalls(content: string, toolCalls: ToolCall[]): InputItem;
|
|
728
|
+
/**
|
|
729
|
+
* Accumulates streaming tool call deltas into complete tool calls.
|
|
730
|
+
*/
|
|
731
|
+
declare class ToolCallAccumulator {
|
|
732
|
+
private calls;
|
|
733
|
+
/**
|
|
734
|
+
* Processes a streaming tool call delta.
|
|
735
|
+
* Returns true if this started a new tool call.
|
|
736
|
+
*/
|
|
737
|
+
processDelta(delta: ToolCallDelta): boolean;
|
|
738
|
+
/**
|
|
739
|
+
* Returns all accumulated tool calls in index order.
|
|
740
|
+
*/
|
|
741
|
+
getToolCalls(): ToolCall[];
|
|
742
|
+
/**
|
|
743
|
+
* Returns a specific tool call by index, or undefined if not found.
|
|
744
|
+
*/
|
|
745
|
+
getToolCall(index: number): ToolCall | undefined;
|
|
746
|
+
/**
|
|
747
|
+
* Clears all accumulated tool calls.
|
|
748
|
+
*/
|
|
749
|
+
reset(): void;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Error thrown when tool argument parsing or validation fails.
|
|
753
|
+
* Contains a descriptive message suitable for sending back to the model.
|
|
754
|
+
*/
|
|
755
|
+
declare class ToolArgsError extends Error {
|
|
756
|
+
/** The tool call ID for correlation */
|
|
757
|
+
readonly toolCallId: string;
|
|
758
|
+
/** The tool name that was called */
|
|
759
|
+
readonly toolName: string;
|
|
760
|
+
/** The raw arguments string that failed to parse */
|
|
761
|
+
readonly rawArguments: string;
|
|
762
|
+
constructor(message: string, toolCallId: string, toolName: string, rawArguments: string);
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Parse a tool call into a typed tool call using the tool's schema.
|
|
766
|
+
*/
|
|
767
|
+
declare function parseTypedToolCall<S extends ZodLikeSchema>(call: ToolCall, tool: TypedFunctionTool<S>): TypedToolCall<S>;
|
|
768
|
+
/**
|
|
769
|
+
* Get the first typed tool call for a specific tool from a response.
|
|
770
|
+
*/
|
|
771
|
+
declare function getTypedToolCall<S extends ZodLikeSchema>(response: Response, tool: TypedFunctionTool<S>): TypedToolCall<S> | undefined;
|
|
772
|
+
/**
|
|
773
|
+
* Get all typed tool calls for a specific tool from a response.
|
|
774
|
+
*/
|
|
775
|
+
declare function getTypedToolCalls<S extends ZodLikeSchema>(response: Response, tool: TypedFunctionTool<S>): TypedToolCall<S>[];
|
|
776
|
+
/**
|
|
777
|
+
* Get the tool name from a tool call.
|
|
778
|
+
*
|
|
779
|
+
* This is a convenience function that unwraps the nested structure.
|
|
780
|
+
*
|
|
781
|
+
* @example
|
|
782
|
+
* ```typescript
|
|
783
|
+
* const name = getToolName(call); // Instead of call.function?.name
|
|
784
|
+
* ```
|
|
785
|
+
*/
|
|
786
|
+
declare function getToolName(call: ToolCall): string;
|
|
787
|
+
/**
|
|
788
|
+
* Get the raw arguments string from a tool call.
|
|
789
|
+
*
|
|
790
|
+
* @example
|
|
791
|
+
* ```typescript
|
|
792
|
+
* const argsJson = getToolArgsRaw(call); // Instead of call.function?.arguments
|
|
793
|
+
* ```
|
|
794
|
+
*/
|
|
795
|
+
declare function getToolArgsRaw(call: ToolCall): string;
|
|
796
|
+
/**
|
|
797
|
+
* Result type for getToolArgs that includes parse error information.
|
|
798
|
+
*/
|
|
799
|
+
type ToolArgsResult<T> = {
|
|
800
|
+
ok: true;
|
|
801
|
+
args: T;
|
|
802
|
+
} | {
|
|
803
|
+
ok: false;
|
|
804
|
+
error: string;
|
|
805
|
+
raw: string;
|
|
806
|
+
};
|
|
807
|
+
/**
|
|
808
|
+
* Get parsed arguments from a tool call with explicit error handling.
|
|
809
|
+
*
|
|
810
|
+
* Returns a discriminated union indicating success or failure.
|
|
811
|
+
* Use this instead of parseToolArgsRaw for proper error handling.
|
|
812
|
+
*
|
|
813
|
+
* @example
|
|
814
|
+
* ```typescript
|
|
815
|
+
* const result = getToolArgs(call);
|
|
816
|
+
* if (!result.ok) {
|
|
817
|
+
* console.error(`Parse failed: ${result.error}, raw: ${result.raw}`);
|
|
818
|
+
* return;
|
|
819
|
+
* }
|
|
820
|
+
* console.log(result.args.location);
|
|
821
|
+
* ```
|
|
822
|
+
*/
|
|
823
|
+
declare function getToolArgs<T = Record<string, unknown>>(call: ToolCall): ToolArgsResult<T>;
|
|
824
|
+
/**
|
|
825
|
+
* Extract all tool calls from a response.
|
|
826
|
+
*
|
|
827
|
+
* Flattens tool calls from all output items into a single array.
|
|
828
|
+
*
|
|
829
|
+
* @example
|
|
830
|
+
* ```typescript
|
|
831
|
+
* const calls = getAllToolCalls(response);
|
|
832
|
+
* for (const call of calls) {
|
|
833
|
+
* const result = getToolArgs(call);
|
|
834
|
+
* if (result.ok) {
|
|
835
|
+
* console.log(getToolName(call), result.args);
|
|
836
|
+
* }
|
|
837
|
+
* }
|
|
838
|
+
* ```
|
|
839
|
+
*/
|
|
840
|
+
declare function getAllToolCalls(response: Response): ToolCall[];
|
|
841
|
+
/**
|
|
842
|
+
* Extract assistant text from a response.
|
|
843
|
+
*
|
|
844
|
+
* Concatenates all text content parts from assistant role output items.
|
|
845
|
+
* Returns an empty string if no text content is present.
|
|
846
|
+
*
|
|
847
|
+
* @example
|
|
848
|
+
* ```typescript
|
|
849
|
+
* const text = getAssistantText(response);
|
|
850
|
+
* console.log("Assistant said:", text);
|
|
851
|
+
* ```
|
|
852
|
+
*/
|
|
853
|
+
declare function getAssistantText(response: Response): string;
|
|
854
|
+
/**
|
|
855
|
+
* Handler function type for tool execution.
|
|
856
|
+
* Can be sync or async, receives parsed arguments and returns a result.
|
|
857
|
+
*/
|
|
858
|
+
type ToolHandler<T = unknown, R = unknown> = (args: T, call: ToolCall) => R | Promise<R>;
|
|
859
|
+
/**
|
|
860
|
+
* Result of executing a tool call.
|
|
861
|
+
*/
|
|
862
|
+
interface ToolExecutionResult {
|
|
863
|
+
toolCallId: string;
|
|
864
|
+
toolName: string;
|
|
865
|
+
result: unknown;
|
|
866
|
+
error?: string;
|
|
867
|
+
/**
|
|
868
|
+
* True if the error is due to malformed arguments (JSON parse or validation failure)
|
|
869
|
+
* and the model should be given a chance to retry with corrected arguments.
|
|
870
|
+
*/
|
|
871
|
+
isRetryable?: boolean;
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Registry for mapping tool names to handler functions with automatic dispatch.
|
|
875
|
+
*
|
|
876
|
+
* @example
|
|
877
|
+
* ```typescript
|
|
878
|
+
* const registry = new ToolRegistry()
|
|
879
|
+
* .register("get_weather", async (args) => {
|
|
880
|
+
* return { temp: 72, unit: "fahrenheit" };
|
|
881
|
+
* })
|
|
882
|
+
* .register("search", async (args) => {
|
|
883
|
+
* return { results: ["result1", "result2"] };
|
|
884
|
+
* });
|
|
885
|
+
*
|
|
886
|
+
* // Execute all tool calls from a response
|
|
887
|
+
* const results = await registry.executeAll(response.toolCalls);
|
|
888
|
+
*
|
|
889
|
+
* // Convert results to messages for the next request
|
|
890
|
+
* const messages = registry.resultsToMessages(results);
|
|
891
|
+
* ```
|
|
892
|
+
*/
|
|
893
|
+
declare class ToolRegistry {
|
|
894
|
+
private handlers;
|
|
895
|
+
/**
|
|
896
|
+
* Registers a handler function for a tool name.
|
|
897
|
+
* @param name - The tool name (must match the function name in the tool definition)
|
|
898
|
+
* @param handler - Function to execute when this tool is called
|
|
899
|
+
* @returns this for chaining
|
|
900
|
+
*/
|
|
901
|
+
register<T = unknown, R = unknown>(name: string, handler: ToolHandler<T, R>): this;
|
|
902
|
+
/**
|
|
903
|
+
* Unregisters a tool handler.
|
|
904
|
+
* @param name - The tool name to unregister
|
|
905
|
+
* @returns true if the handler was removed, false if it didn't exist
|
|
906
|
+
*/
|
|
907
|
+
unregister(name: string): boolean;
|
|
908
|
+
/**
|
|
909
|
+
* Checks if a handler is registered for the given tool name.
|
|
910
|
+
*/
|
|
911
|
+
has(name: string): boolean;
|
|
912
|
+
/**
|
|
913
|
+
* Returns the list of registered tool names.
|
|
914
|
+
*/
|
|
915
|
+
getRegisteredTools(): string[];
|
|
916
|
+
/**
|
|
917
|
+
* Executes a single tool call.
|
|
918
|
+
* @param call - The tool call to execute
|
|
919
|
+
* @returns The execution result
|
|
920
|
+
*/
|
|
921
|
+
execute(call: ToolCall): Promise<ToolExecutionResult>;
|
|
922
|
+
/**
|
|
923
|
+
* Executes multiple tool calls in parallel.
|
|
924
|
+
* @param calls - Array of tool calls to execute
|
|
925
|
+
* @returns Array of execution results in the same order as input
|
|
926
|
+
*/
|
|
927
|
+
executeAll(calls: ToolCall[]): Promise<ToolExecutionResult[]>;
|
|
928
|
+
/**
|
|
929
|
+
* Converts execution results to tool result messages.
|
|
930
|
+
* Useful for appending to the conversation history.
|
|
931
|
+
* @param results - Array of execution results
|
|
932
|
+
* @returns Array of tool result input items (role "tool")
|
|
933
|
+
*/
|
|
934
|
+
resultsToMessages(results: ToolExecutionResult[]): InputItem[];
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Formats a tool execution error into a message suitable for sending back to the model.
|
|
938
|
+
* The message is designed to help the model understand what went wrong and correct it.
|
|
939
|
+
*
|
|
940
|
+
* @example
|
|
941
|
+
* ```typescript
|
|
942
|
+
* const result = await registry.execute(toolCall);
|
|
943
|
+
* if (result.error && result.isRetryable) {
|
|
944
|
+
* const errorMessage = formatToolErrorForModel(result);
|
|
945
|
+
* messages.push(toolResultMessage(result.toolCallId, errorMessage));
|
|
946
|
+
* // Continue conversation to let model retry
|
|
947
|
+
* }
|
|
948
|
+
* ```
|
|
949
|
+
*/
|
|
950
|
+
declare function formatToolErrorForModel(result: ToolExecutionResult): string;
|
|
951
|
+
/**
|
|
952
|
+
* Checks if any results have retryable errors.
|
|
953
|
+
*
|
|
954
|
+
* @example
|
|
955
|
+
* ```typescript
|
|
956
|
+
* const results = await registry.executeAll(toolCalls);
|
|
957
|
+
* if (hasRetryableErrors(results)) {
|
|
958
|
+
* // Send error messages back to model and continue conversation
|
|
959
|
+
* }
|
|
960
|
+
* ```
|
|
961
|
+
*/
|
|
962
|
+
declare function hasRetryableErrors(results: ToolExecutionResult[]): boolean;
|
|
963
|
+
/**
|
|
964
|
+
* Filters results to only those with retryable errors.
|
|
965
|
+
*/
|
|
966
|
+
declare function getRetryableErrors(results: ToolExecutionResult[]): ToolExecutionResult[];
|
|
967
|
+
/**
|
|
968
|
+
* Creates tool result messages for retryable errors, formatted to help the model correct them.
|
|
969
|
+
*
|
|
970
|
+
* @example
|
|
971
|
+
* ```typescript
|
|
972
|
+
* const results = await registry.executeAll(toolCalls);
|
|
973
|
+
* if (hasRetryableErrors(results)) {
|
|
974
|
+
* const retryMessages = createRetryMessages(results);
|
|
975
|
+
* messages.push(...retryMessages);
|
|
976
|
+
* // Make another API call to let model retry
|
|
977
|
+
* }
|
|
978
|
+
* ```
|
|
979
|
+
*/
|
|
980
|
+
declare function createRetryMessages(results: ToolExecutionResult[]): InputItem[];
|
|
981
|
+
/**
|
|
982
|
+
* Options for executeWithRetry.
|
|
983
|
+
*/
|
|
984
|
+
interface RetryOptions {
|
|
985
|
+
/**
|
|
986
|
+
* Maximum number of retry attempts for parse/validation errors.
|
|
987
|
+
* @default 2
|
|
988
|
+
*/
|
|
989
|
+
maxRetries?: number;
|
|
990
|
+
/**
|
|
991
|
+
* Callback invoked when a retryable error occurs.
|
|
992
|
+
* Should return new tool calls from the model's response.
|
|
993
|
+
* If not provided, executeWithRetry will not retry automatically.
|
|
994
|
+
*
|
|
995
|
+
* @param errorMessages - Messages to send back to the model
|
|
996
|
+
* @param attempt - Current attempt number (1-based)
|
|
997
|
+
* @returns New tool calls from the model, or empty array to stop retrying
|
|
998
|
+
*/
|
|
999
|
+
onRetry?: (errorMessages: InputItem[], attempt: number) => Promise<ToolCall[]>;
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Executes tool calls with automatic retry on parse/validation errors.
|
|
1003
|
+
*
|
|
1004
|
+
* This is a higher-level utility that wraps registry.executeAll with retry logic.
|
|
1005
|
+
* When a retryable error occurs, it calls the onRetry callback to get new tool calls
|
|
1006
|
+
* from the model and continues execution.
|
|
1007
|
+
*
|
|
1008
|
+
* **Result Preservation**: Successful results are preserved across retries. If you
|
|
1009
|
+
* execute multiple tool calls and only some fail, the successful results are kept
|
|
1010
|
+
* and merged with the results from retry attempts. Results are keyed by toolCallId,
|
|
1011
|
+
* so if a retry returns a call with the same ID as a previous result, the newer
|
|
1012
|
+
* result will replace it.
|
|
1013
|
+
*
|
|
1014
|
+
* @example
|
|
1015
|
+
* ```typescript
|
|
1016
|
+
* const results = await executeWithRetry(registry, toolCalls, {
|
|
1017
|
+
* maxRetries: 2,
|
|
1018
|
+
* onRetry: async (errorMessages, attempt) => {
|
|
1019
|
+
* console.log(`Retry attempt ${attempt}`);
|
|
1020
|
+
* // Add error messages to conversation and call the model again
|
|
1021
|
+
* messages.push(assistantMessageWithToolCalls("", toolCalls));
|
|
1022
|
+
* messages.push(...errorMessages);
|
|
1023
|
+
* const req = client.responses
|
|
1024
|
+
* .new()
|
|
1025
|
+
* .model("...")
|
|
1026
|
+
* .input(messages)
|
|
1027
|
+
* .tools(tools)
|
|
1028
|
+
* .build();
|
|
1029
|
+
* const response = await client.responses.create(req);
|
|
1030
|
+
* return firstToolCall(response) ? [firstToolCall(response)!] : [];
|
|
1031
|
+
* },
|
|
1032
|
+
* });
|
|
1033
|
+
* ```
|
|
1034
|
+
*
|
|
1035
|
+
* @param registry - The tool registry to use for execution
|
|
1036
|
+
* @param toolCalls - Initial tool calls to execute
|
|
1037
|
+
* @param options - Retry configuration
|
|
1038
|
+
* @returns Final execution results after all retries, including preserved successes
|
|
1039
|
+
*/
|
|
1040
|
+
declare function executeWithRetry(registry: ToolRegistry, toolCalls: ToolCall[], options?: RetryOptions): Promise<ToolExecutionResult[]>;
|
|
1041
|
+
|
|
1042
|
+
export { getAssistantText as $, type ApiKey as A, createAssistantMessage as B, type CustomerTokenRequest as C, DEFAULT_BASE_URL as D, createSystemMessage as E, type FieldError as F, type GetOrCreateCustomerTokenRequest as G, toolResultMessage as H, type InputItem as I, respondToToolCall as J, assistantMessageWithToolCalls as K, createToolCall as L, type MetricsCallbacks as M, createFunctionCall as N, type OutputFormat as O, type ProviderId as P, getToolName as Q, type RetryConfig as R, type StructuredJSONEvent as S, type TraceCallbacks as T, getToolArgsRaw as U, getToolArgs as V, getAllToolCalls as W, getTypedToolCall as X, getTypedToolCalls as Y, type ZodLikeSchema as Z, parseTypedToolCall as _, type RequestContext as a, type TokenUsageMetrics as a$, ToolCallAccumulator as a0, zodToJsonSchema as a1, ToolArgsError as a2, formatToolErrorForModel as a3, hasRetryableErrors as a4, getRetryableErrors as a5, createRetryMessages as a6, executeWithRetry as a7, type JsonSchemaOptions as a8, type InferSchema as a9, createUsage as aA, type UsageSummary as aB, type Project as aC, MessageRoles as aD, type MessageRole as aE, ContentPartTypes as aF, type ContentPartType as aG, type ContentPart as aH, InputItemTypes as aI, type InputItemType as aJ, OutputItemTypes as aK, type OutputItemType as aL, type OutputItem as aM, ToolTypes as aN, type ToolType as aO, type FunctionTool as aP, type XSearchConfig as aQ, type CodeExecConfig as aR, ToolChoiceTypes as aS, type ToolChoiceType as aT, type FunctionCall as aU, OutputFormatTypes as aV, type OutputFormatType as aW, type JSONSchemaFormat as aX, type Citation as aY, type HttpRequestMetrics as aZ, type StreamFirstTokenMetrics as a_, type TypedFunctionTool as aa, type TypedToolCall as ab, type ToolHandler as ac, type RetryOptions as ad, type ToolArgsResult as ae, SDK_VERSION as af, DEFAULT_CLIENT_HEADER as ag, DEFAULT_CONNECT_TIMEOUT_MS as ah, DEFAULT_REQUEST_TIMEOUT_MS as ai, type NonEmptyArray as aj, StopReasons as ak, type KnownStopReason as al, type StopReason as am, asProviderId as an, asModelId as ao, asTierCode as ap, SubscriptionStatuses as aq, type SubscriptionStatusKind as ar, BillingProviders as as, type BillingProvider as at, type CustomerMetadata as au, type ModelRelayBaseOptions as av, type ModelRelayTokenOptions as aw, type ModelRelayTokenProviderOptions as ax, type TokenType as ay, type Usage as az, type TokenProvider as b, mergeMetrics as b0, mergeTrace as b1, normalizeStopReason as b2, stopReasonToString as b3, normalizeModelId as b4, modelToString as b5, type ResponseEventType as b6, type MessageStartData as b7, type MessageDeltaData as b8, type MessageStopData as b9, type ToolCallDelta as ba, type FunctionCallDelta as bb, type StructuredJSONRecordType as bc, type DeepPartial as bd, type APICustomerRef as be, type APICheckoutSession as bf, type APIUsage as bg, type APIResponsesResponse as bh, type APIKey as bi, type CustomerToken as c, type ModelId as d, type Tool as e, type ToolChoice as f, type ToolCall as g, type Response as h, type ResponseEvent as i, type RetryMetadata as j, type TransportErrorKind as k, ToolRegistry as l, type ToolExecutionResult as m, type TierCode as n, type AnySchema as o, type SecretKey as p, type ModelRelayKeyOptions as q, type ModelRelayOptions as r, createFunctionTool as s, createTypedTool as t, toolChoiceAuto as u, toolChoiceRequired as v, toolChoiceNone as w, hasToolCalls as x, firstToolCall as y, createUserMessage as z };
|