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