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