@modelrelay/sdk 5.1.0 → 8.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/README.md +132 -55
- package/dist/api-B7SmXjnr.d.cts +5917 -0
- package/dist/api-B7SmXjnr.d.ts +5917 -0
- package/dist/api-CdHqjsU_.d.cts +6062 -0
- package/dist/api-CdHqjsU_.d.ts +6062 -0
- package/dist/api-DP9MoKHy.d.cts +5993 -0
- package/dist/api-DP9MoKHy.d.ts +5993 -0
- 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-HHBAD7FF.js +1133 -0
- package/dist/chunk-PKGWFDGU.js +1185 -0
- package/dist/chunk-SJC7Q4NK.js +1199 -0
- package/dist/chunk-YQWOQ74P.js +1166 -0
- package/dist/index.cjs +3180 -891
- package/dist/index.d.cts +950 -85
- package/dist/index.d.ts +950 -85
- package/dist/index.js +3099 -899
- package/dist/node.cjs +6 -2
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/tools-Bxdv0Np2.d.cts +1052 -0
- package/dist/tools-Bxdv0Np2.d.ts +1052 -0
- 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
|
@@ -0,0 +1,1052 @@
|
|
|
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
|
+
* Opaque signature from Gemini 3 thinking models that must be preserved
|
|
354
|
+
* and returned with tool results. Base64-encoded.
|
|
355
|
+
*/
|
|
356
|
+
thought_signature?: string;
|
|
357
|
+
}
|
|
358
|
+
interface ToolCall {
|
|
359
|
+
id: string;
|
|
360
|
+
type: ToolType;
|
|
361
|
+
function?: FunctionCall;
|
|
362
|
+
}
|
|
363
|
+
declare const OutputFormatTypes: {
|
|
364
|
+
readonly Text: "text";
|
|
365
|
+
readonly JsonSchema: "json_schema";
|
|
366
|
+
};
|
|
367
|
+
type OutputFormatType = (typeof OutputFormatTypes)[keyof typeof OutputFormatTypes];
|
|
368
|
+
interface JSONSchemaFormat {
|
|
369
|
+
name: string;
|
|
370
|
+
description?: string;
|
|
371
|
+
schema: Record<string, unknown>;
|
|
372
|
+
strict?: boolean;
|
|
373
|
+
}
|
|
374
|
+
interface OutputFormat {
|
|
375
|
+
type: OutputFormatType;
|
|
376
|
+
json_schema?: JSONSchemaFormat;
|
|
377
|
+
}
|
|
378
|
+
interface Citation {
|
|
379
|
+
url?: string;
|
|
380
|
+
title?: string;
|
|
381
|
+
}
|
|
382
|
+
interface Response {
|
|
383
|
+
id: string;
|
|
384
|
+
output: OutputItem[];
|
|
385
|
+
stopReason?: StopReason;
|
|
386
|
+
model: ModelId;
|
|
387
|
+
usage: Usage;
|
|
388
|
+
requestId?: string;
|
|
389
|
+
provider?: ProviderId;
|
|
390
|
+
citations?: Citation[];
|
|
391
|
+
}
|
|
392
|
+
interface FieldError {
|
|
393
|
+
field?: string;
|
|
394
|
+
message: string;
|
|
395
|
+
}
|
|
396
|
+
interface RetryConfig {
|
|
397
|
+
maxAttempts?: number;
|
|
398
|
+
baseBackoffMs?: number;
|
|
399
|
+
maxBackoffMs?: number;
|
|
400
|
+
retryPost?: boolean;
|
|
401
|
+
}
|
|
402
|
+
interface RetryMetadata {
|
|
403
|
+
attempts: number;
|
|
404
|
+
lastStatus?: number;
|
|
405
|
+
lastError?: string;
|
|
406
|
+
}
|
|
407
|
+
type TransportErrorKind = "timeout" | "connect" | "request" | "empty_response" | "other";
|
|
408
|
+
interface RequestContext {
|
|
409
|
+
method: string;
|
|
410
|
+
path: string;
|
|
411
|
+
model?: ModelId;
|
|
412
|
+
requestId?: string;
|
|
413
|
+
responseId?: string;
|
|
414
|
+
}
|
|
415
|
+
interface HttpRequestMetrics {
|
|
416
|
+
latencyMs: number;
|
|
417
|
+
status?: number;
|
|
418
|
+
error?: string;
|
|
419
|
+
retries?: RetryMetadata;
|
|
420
|
+
context: RequestContext;
|
|
421
|
+
}
|
|
422
|
+
interface StreamFirstTokenMetrics {
|
|
423
|
+
latencyMs: number;
|
|
424
|
+
error?: string;
|
|
425
|
+
context: RequestContext;
|
|
426
|
+
}
|
|
427
|
+
interface TokenUsageMetrics {
|
|
428
|
+
usage: Usage;
|
|
429
|
+
context: RequestContext;
|
|
430
|
+
}
|
|
431
|
+
interface MetricsCallbacks {
|
|
432
|
+
httpRequest?: (metrics: HttpRequestMetrics) => void;
|
|
433
|
+
streamFirstToken?: (metrics: StreamFirstTokenMetrics) => void;
|
|
434
|
+
usage?: (metrics: TokenUsageMetrics) => void;
|
|
435
|
+
}
|
|
436
|
+
interface TraceCallbacks {
|
|
437
|
+
requestStart?: (context: RequestContext) => void;
|
|
438
|
+
requestFinish?: (info: {
|
|
439
|
+
context: RequestContext;
|
|
440
|
+
status?: number;
|
|
441
|
+
error?: unknown;
|
|
442
|
+
retries?: RetryMetadata;
|
|
443
|
+
latencyMs: number;
|
|
444
|
+
}) => void;
|
|
445
|
+
streamEvent?: (info: {
|
|
446
|
+
context: RequestContext;
|
|
447
|
+
event: ResponseEvent;
|
|
448
|
+
}) => void;
|
|
449
|
+
streamError?: (info: {
|
|
450
|
+
context: RequestContext;
|
|
451
|
+
error: unknown;
|
|
452
|
+
}) => void;
|
|
453
|
+
}
|
|
454
|
+
declare function mergeMetrics(base?: MetricsCallbacks, override?: MetricsCallbacks): MetricsCallbacks | undefined;
|
|
455
|
+
declare function mergeTrace(base?: TraceCallbacks, override?: TraceCallbacks): TraceCallbacks | undefined;
|
|
456
|
+
declare function normalizeStopReason(value?: unknown): StopReason | undefined;
|
|
457
|
+
declare function stopReasonToString(value?: StopReason): string | undefined;
|
|
458
|
+
declare function normalizeModelId(value: unknown): ModelId | undefined;
|
|
459
|
+
declare function modelToString(value: ModelId): string;
|
|
460
|
+
type ResponseEventType = "message_start" | "message_delta" | "message_stop" | "tool_use_start" | "tool_use_delta" | "tool_use_stop" | "ping" | "custom";
|
|
461
|
+
interface MessageStartData {
|
|
462
|
+
responseId?: string;
|
|
463
|
+
model?: string;
|
|
464
|
+
message?: Record<string, unknown>;
|
|
465
|
+
[key: string]: unknown;
|
|
466
|
+
}
|
|
467
|
+
interface MessageDeltaData {
|
|
468
|
+
delta?: string | {
|
|
469
|
+
text?: string;
|
|
470
|
+
[key: string]: unknown;
|
|
471
|
+
};
|
|
472
|
+
responseId?: string;
|
|
473
|
+
model?: string;
|
|
474
|
+
[key: string]: unknown;
|
|
475
|
+
}
|
|
476
|
+
interface MessageStopData {
|
|
477
|
+
stopReason?: StopReason;
|
|
478
|
+
usage?: Usage;
|
|
479
|
+
responseId?: string;
|
|
480
|
+
model?: ModelId;
|
|
481
|
+
[key: string]: unknown;
|
|
482
|
+
}
|
|
483
|
+
/** Incremental update to a tool call during streaming. */
|
|
484
|
+
interface ToolCallDelta {
|
|
485
|
+
index: number;
|
|
486
|
+
id?: string;
|
|
487
|
+
type?: string;
|
|
488
|
+
function?: FunctionCallDelta;
|
|
489
|
+
}
|
|
490
|
+
/** Incremental function call data. */
|
|
491
|
+
interface FunctionCallDelta {
|
|
492
|
+
name?: string;
|
|
493
|
+
arguments?: string;
|
|
494
|
+
}
|
|
495
|
+
interface ResponseEvent<T = unknown> {
|
|
496
|
+
type: ResponseEventType;
|
|
497
|
+
event: string;
|
|
498
|
+
data?: T;
|
|
499
|
+
textDelta?: string;
|
|
500
|
+
/** Incremental tool call update during streaming. */
|
|
501
|
+
toolCallDelta?: ToolCallDelta;
|
|
502
|
+
/** Completed tool calls when type is tool_use_stop or message_stop. */
|
|
503
|
+
toolCalls?: ToolCall[];
|
|
504
|
+
/** Tool result payload when type is tool_use_stop. */
|
|
505
|
+
toolResult?: unknown;
|
|
506
|
+
responseId?: string;
|
|
507
|
+
model?: ModelId;
|
|
508
|
+
stopReason?: StopReason;
|
|
509
|
+
usage?: Usage;
|
|
510
|
+
requestId?: string;
|
|
511
|
+
raw: string;
|
|
512
|
+
}
|
|
513
|
+
type StructuredJSONRecordType = "start" | "update" | "completion" | "error";
|
|
514
|
+
/**
|
|
515
|
+
* Recursively makes all properties optional.
|
|
516
|
+
* Useful for typing partial payloads during progressive streaming before
|
|
517
|
+
* all fields are complete.
|
|
518
|
+
*
|
|
519
|
+
* @example
|
|
520
|
+
* interface Article { title: string; body: string; }
|
|
521
|
+
* type PartialArticle = DeepPartial<Article>;
|
|
522
|
+
* // { title?: string; body?: string; }
|
|
523
|
+
*/
|
|
524
|
+
type DeepPartial<T> = T extends object ? {
|
|
525
|
+
[P in keyof T]?: DeepPartial<T[P]>;
|
|
526
|
+
} : T;
|
|
527
|
+
interface StructuredJSONEvent<T> {
|
|
528
|
+
type: "update" | "completion";
|
|
529
|
+
payload: T;
|
|
530
|
+
requestId?: string;
|
|
531
|
+
/**
|
|
532
|
+
* Set of field paths that are complete (have their closing delimiter).
|
|
533
|
+
* Use dot notation for nested fields (e.g., "metadata.author").
|
|
534
|
+
* Check with completeFields.has("fieldName").
|
|
535
|
+
*/
|
|
536
|
+
completeFields: Set<string>;
|
|
537
|
+
}
|
|
538
|
+
interface APICustomerRef {
|
|
539
|
+
id: string;
|
|
540
|
+
external_id: string;
|
|
541
|
+
owner_id: string;
|
|
542
|
+
}
|
|
543
|
+
interface APICheckoutSession {
|
|
544
|
+
id: string;
|
|
545
|
+
plan: string;
|
|
546
|
+
status: string;
|
|
547
|
+
url: string;
|
|
548
|
+
expires_at?: string;
|
|
549
|
+
completed_at?: string;
|
|
550
|
+
}
|
|
551
|
+
interface APIUsage {
|
|
552
|
+
input_tokens?: number;
|
|
553
|
+
output_tokens?: number;
|
|
554
|
+
total_tokens?: number;
|
|
555
|
+
}
|
|
556
|
+
interface APIResponsesResponse {
|
|
557
|
+
id?: string;
|
|
558
|
+
stop_reason?: string;
|
|
559
|
+
model?: string;
|
|
560
|
+
usage?: APIUsage;
|
|
561
|
+
provider?: string;
|
|
562
|
+
output?: OutputItem[];
|
|
563
|
+
citations?: Citation[];
|
|
564
|
+
}
|
|
565
|
+
interface APIKey {
|
|
566
|
+
id: string;
|
|
567
|
+
label: string;
|
|
568
|
+
kind: string;
|
|
569
|
+
createdAt: Date;
|
|
570
|
+
expiresAt?: Date;
|
|
571
|
+
lastUsedAt?: Date;
|
|
572
|
+
redactedKey: string;
|
|
573
|
+
secretKey?: string;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Creates a user message.
|
|
578
|
+
*/
|
|
579
|
+
declare function createUserMessage(content: string): InputItem;
|
|
580
|
+
/**
|
|
581
|
+
* Creates an assistant message.
|
|
582
|
+
*/
|
|
583
|
+
declare function createAssistantMessage(content: string): InputItem;
|
|
584
|
+
/**
|
|
585
|
+
* Creates a system message.
|
|
586
|
+
*/
|
|
587
|
+
declare function createSystemMessage(content: string): InputItem;
|
|
588
|
+
/**
|
|
589
|
+
* Creates a tool call object.
|
|
590
|
+
*/
|
|
591
|
+
declare function createToolCall(id: string, name: string, args: string, type?: ToolType): ToolCall;
|
|
592
|
+
/**
|
|
593
|
+
* Creates a function call object.
|
|
594
|
+
*/
|
|
595
|
+
declare function createFunctionCall(name: string, args: string): FunctionCall;
|
|
596
|
+
/**
|
|
597
|
+
* Interface for Zod-like schema types.
|
|
598
|
+
*
|
|
599
|
+
* This is designed to be compatible with Zod's actual types while also
|
|
600
|
+
* supporting other schema libraries with similar structure.
|
|
601
|
+
*/
|
|
602
|
+
interface ZodLikeSchema {
|
|
603
|
+
_def: {
|
|
604
|
+
typeName: string;
|
|
605
|
+
[key: string]: unknown;
|
|
606
|
+
};
|
|
607
|
+
parse(data: unknown): unknown;
|
|
608
|
+
safeParse(data: unknown): {
|
|
609
|
+
success: boolean;
|
|
610
|
+
data?: unknown;
|
|
611
|
+
error?: unknown;
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Options for JSON Schema generation.
|
|
616
|
+
*/
|
|
617
|
+
interface JsonSchemaOptions {
|
|
618
|
+
/** Whether to include $schema property. Defaults to false. */
|
|
619
|
+
includeSchema?: boolean;
|
|
620
|
+
/** Target JSON Schema version. Defaults to "draft-07". */
|
|
621
|
+
target?: "draft-04" | "draft-07" | "draft-2019-09" | "draft-2020-12";
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Converts a Zod schema to JSON Schema.
|
|
625
|
+
* This is a simplified implementation that handles common Zod types.
|
|
626
|
+
* For full Zod support, consider using the 'zod-to-json-schema' package.
|
|
627
|
+
*
|
|
628
|
+
* @param schema - A Zod schema
|
|
629
|
+
* @param options - Optional JSON Schema generation options
|
|
630
|
+
* @returns A JSON Schema object
|
|
631
|
+
*/
|
|
632
|
+
declare function zodToJsonSchema(schema: ZodLikeSchema, options?: JsonSchemaOptions): Record<string, unknown>;
|
|
633
|
+
/**
|
|
634
|
+
* Creates a function tool from a Zod schema.
|
|
635
|
+
*
|
|
636
|
+
* This function automatically converts a Zod schema to a JSON Schema
|
|
637
|
+
* and creates a tool definition. It eliminates the need to manually
|
|
638
|
+
* write JSON schemas for tool parameters.
|
|
639
|
+
*
|
|
640
|
+
* @example
|
|
641
|
+
* ```typescript
|
|
642
|
+
* import { z } from "zod";
|
|
643
|
+
* import { createFunctionToolFromSchema } from "@modelrelay/sdk";
|
|
644
|
+
*
|
|
645
|
+
* const weatherParams = z.object({
|
|
646
|
+
* location: z.string().describe("City name"),
|
|
647
|
+
* unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
|
|
648
|
+
* });
|
|
649
|
+
*
|
|
650
|
+
* const weatherTool = createFunctionToolFromSchema(
|
|
651
|
+
* "get_weather",
|
|
652
|
+
* "Get weather for a location",
|
|
653
|
+
* weatherParams
|
|
654
|
+
* );
|
|
655
|
+
* ```
|
|
656
|
+
*
|
|
657
|
+
* @param name - The tool name
|
|
658
|
+
* @param description - A description of what the tool does
|
|
659
|
+
* @param schema - A Zod schema defining the tool's parameters
|
|
660
|
+
* @param options - Optional JSON Schema generation options
|
|
661
|
+
* @returns A Tool definition with the JSON schema derived from the Zod schema
|
|
662
|
+
*/
|
|
663
|
+
declare function createFunctionToolFromSchema(name: string, description: string, schema: ZodLikeSchema, options?: JsonSchemaOptions): Tool;
|
|
664
|
+
/**
|
|
665
|
+
* Creates a function tool with the given name, description, and JSON schema.
|
|
666
|
+
*/
|
|
667
|
+
declare function createFunctionTool(name: string, description: string, parameters?: Record<string, unknown>): Tool;
|
|
668
|
+
/**
|
|
669
|
+
* Returns a ToolChoice that lets the model decide when to use tools.
|
|
670
|
+
*/
|
|
671
|
+
declare function toolChoiceAuto(): ToolChoice;
|
|
672
|
+
/**
|
|
673
|
+
* Returns a ToolChoice that forces the model to use a tool.
|
|
674
|
+
*/
|
|
675
|
+
declare function toolChoiceRequired(): ToolChoice;
|
|
676
|
+
/**
|
|
677
|
+
* Returns a ToolChoice that prevents the model from using tools.
|
|
678
|
+
*/
|
|
679
|
+
declare function toolChoiceNone(): ToolChoice;
|
|
680
|
+
/**
|
|
681
|
+
* Returns true if the response contains tool calls.
|
|
682
|
+
*/
|
|
683
|
+
declare function hasToolCalls(response: Response): boolean;
|
|
684
|
+
/**
|
|
685
|
+
* Returns the first tool call from a response, or undefined if none exist.
|
|
686
|
+
*/
|
|
687
|
+
declare function firstToolCall(response: Response): ToolCall | undefined;
|
|
688
|
+
/**
|
|
689
|
+
* Creates a message containing the result of a tool call.
|
|
690
|
+
*/
|
|
691
|
+
declare function toolResultMessage(toolCallId: string, result: unknown): InputItem;
|
|
692
|
+
/**
|
|
693
|
+
* Creates a tool result message from a ToolCall.
|
|
694
|
+
* Convenience wrapper around toolResultMessage using the call's ID.
|
|
695
|
+
*/
|
|
696
|
+
declare function respondToToolCall(call: ToolCall, result: unknown): InputItem;
|
|
697
|
+
/**
|
|
698
|
+
* Creates an assistant message that includes tool calls.
|
|
699
|
+
* Used to include the assistant's tool-calling turn in conversation history.
|
|
700
|
+
*/
|
|
701
|
+
declare function assistantMessageWithToolCalls(content: string, toolCalls: ToolCall[]): InputItem;
|
|
702
|
+
/**
|
|
703
|
+
* Accumulates streaming tool call deltas into complete tool calls.
|
|
704
|
+
*/
|
|
705
|
+
declare class ToolCallAccumulator {
|
|
706
|
+
private calls;
|
|
707
|
+
/**
|
|
708
|
+
* Processes a streaming tool call delta.
|
|
709
|
+
* Returns true if this started a new tool call.
|
|
710
|
+
*/
|
|
711
|
+
processDelta(delta: ToolCallDelta): boolean;
|
|
712
|
+
/**
|
|
713
|
+
* Returns all accumulated tool calls in index order.
|
|
714
|
+
*/
|
|
715
|
+
getToolCalls(): ToolCall[];
|
|
716
|
+
/**
|
|
717
|
+
* Returns a specific tool call by index, or undefined if not found.
|
|
718
|
+
*/
|
|
719
|
+
getToolCall(index: number): ToolCall | undefined;
|
|
720
|
+
/**
|
|
721
|
+
* Clears all accumulated tool calls.
|
|
722
|
+
*/
|
|
723
|
+
reset(): void;
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Error thrown when tool argument parsing or validation fails.
|
|
727
|
+
* Contains a descriptive message suitable for sending back to the model.
|
|
728
|
+
*/
|
|
729
|
+
declare class ToolArgsError extends Error {
|
|
730
|
+
/** The tool call ID for correlation */
|
|
731
|
+
readonly toolCallId: string;
|
|
732
|
+
/** The tool name that was called */
|
|
733
|
+
readonly toolName: string;
|
|
734
|
+
/** The raw arguments string that failed to parse */
|
|
735
|
+
readonly rawArguments: string;
|
|
736
|
+
constructor(message: string, toolCallId: string, toolName: string, rawArguments: string);
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Schema interface compatible with Zod, Yup, and similar validation libraries.
|
|
740
|
+
* Any object with a `parse` method that returns the validated type works.
|
|
741
|
+
*/
|
|
742
|
+
interface Schema<T> {
|
|
743
|
+
parse(data: unknown): T;
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Parses and validates tool call arguments using a schema.
|
|
747
|
+
*
|
|
748
|
+
* Works with any schema library that has a `parse` method (Zod, Yup, etc.).
|
|
749
|
+
* Throws a descriptive ToolArgsError if parsing or validation fails.
|
|
750
|
+
*
|
|
751
|
+
* @example
|
|
752
|
+
* ```typescript
|
|
753
|
+
* import { z } from "zod";
|
|
754
|
+
*
|
|
755
|
+
* const WeatherArgs = z.object({
|
|
756
|
+
* location: z.string(),
|
|
757
|
+
* unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
|
|
758
|
+
* });
|
|
759
|
+
*
|
|
760
|
+
* // In your tool handler:
|
|
761
|
+
* const args = parseToolArgs(toolCall, WeatherArgs);
|
|
762
|
+
* // args is typed as { location: string; unit: "celsius" | "fahrenheit" }
|
|
763
|
+
* ```
|
|
764
|
+
*
|
|
765
|
+
* @param call - The tool call containing arguments to parse
|
|
766
|
+
* @param schema - A schema with a `parse` method (Zod, Yup, etc.)
|
|
767
|
+
* @returns The parsed and validated arguments with proper types
|
|
768
|
+
* @throws {ToolArgsError} If JSON parsing or schema validation fails
|
|
769
|
+
*/
|
|
770
|
+
declare function parseToolArgs<T>(call: ToolCall, schema: Schema<T>): T;
|
|
771
|
+
/**
|
|
772
|
+
* Attempts to parse tool arguments, returning a result object instead of throwing.
|
|
773
|
+
*
|
|
774
|
+
* @example
|
|
775
|
+
* ```typescript
|
|
776
|
+
* const result = tryParseToolArgs(toolCall, WeatherArgs);
|
|
777
|
+
* if (result.success) {
|
|
778
|
+
* console.log(result.data.location);
|
|
779
|
+
* } else {
|
|
780
|
+
* console.error(result.error.message);
|
|
781
|
+
* }
|
|
782
|
+
* ```
|
|
783
|
+
*
|
|
784
|
+
* @param call - The tool call containing arguments to parse
|
|
785
|
+
* @param schema - A schema with a `parse` method
|
|
786
|
+
* @returns An object with either { success: true, data: T } or { success: false, error: ToolArgsError }
|
|
787
|
+
*/
|
|
788
|
+
declare function tryParseToolArgs<T>(call: ToolCall, schema: Schema<T>): {
|
|
789
|
+
success: true;
|
|
790
|
+
data: T;
|
|
791
|
+
} | {
|
|
792
|
+
success: false;
|
|
793
|
+
error: ToolArgsError;
|
|
794
|
+
};
|
|
795
|
+
/**
|
|
796
|
+
* Parses raw JSON arguments without schema validation.
|
|
797
|
+
* Useful when you want JSON parsing error handling but not schema validation.
|
|
798
|
+
*
|
|
799
|
+
* @param call - The tool call containing arguments to parse
|
|
800
|
+
* @returns The parsed JSON as an unknown type
|
|
801
|
+
* @throws {ToolArgsError} If JSON parsing fails
|
|
802
|
+
*/
|
|
803
|
+
declare function parseToolArgsRaw(call: ToolCall): unknown;
|
|
804
|
+
/**
|
|
805
|
+
* Get the tool name from a tool call.
|
|
806
|
+
*
|
|
807
|
+
* This is a convenience function that unwraps the nested structure.
|
|
808
|
+
*
|
|
809
|
+
* @example
|
|
810
|
+
* ```typescript
|
|
811
|
+
* const name = getToolName(call); // Instead of call.function?.name
|
|
812
|
+
* ```
|
|
813
|
+
*/
|
|
814
|
+
declare function getToolName(call: ToolCall): string;
|
|
815
|
+
/**
|
|
816
|
+
* Get the raw arguments string from a tool call.
|
|
817
|
+
*
|
|
818
|
+
* @example
|
|
819
|
+
* ```typescript
|
|
820
|
+
* const argsJson = getToolArgsRaw(call); // Instead of call.function?.arguments
|
|
821
|
+
* ```
|
|
822
|
+
*/
|
|
823
|
+
declare function getToolArgsRaw(call: ToolCall): string;
|
|
824
|
+
/**
|
|
825
|
+
* Get parsed arguments from a tool call.
|
|
826
|
+
*
|
|
827
|
+
* Returns the parsed JSON object, or an empty object if parsing fails.
|
|
828
|
+
* For error handling, use parseToolArgsRaw instead.
|
|
829
|
+
*
|
|
830
|
+
* @example
|
|
831
|
+
* ```typescript
|
|
832
|
+
* const args = getToolArgs(call);
|
|
833
|
+
* console.log(args.location); // Access properties directly
|
|
834
|
+
* ```
|
|
835
|
+
*/
|
|
836
|
+
declare function getToolArgs<T = Record<string, unknown>>(call: ToolCall): T;
|
|
837
|
+
/**
|
|
838
|
+
* Extract all tool calls from a response.
|
|
839
|
+
*
|
|
840
|
+
* Flattens tool calls from all output items into a single array.
|
|
841
|
+
*
|
|
842
|
+
* @example
|
|
843
|
+
* ```typescript
|
|
844
|
+
* const calls = getAllToolCalls(response);
|
|
845
|
+
* for (const call of calls) {
|
|
846
|
+
* console.log(getToolName(call), getToolArgs(call));
|
|
847
|
+
* }
|
|
848
|
+
* ```
|
|
849
|
+
*/
|
|
850
|
+
declare function getAllToolCalls(response: Response): ToolCall[];
|
|
851
|
+
/**
|
|
852
|
+
* Extract assistant text from a response.
|
|
853
|
+
*
|
|
854
|
+
* Concatenates all text content parts from assistant role output items.
|
|
855
|
+
* Returns an empty string if no text content is present.
|
|
856
|
+
*
|
|
857
|
+
* @example
|
|
858
|
+
* ```typescript
|
|
859
|
+
* const text = getAssistantText(response);
|
|
860
|
+
* console.log("Assistant said:", text);
|
|
861
|
+
* ```
|
|
862
|
+
*/
|
|
863
|
+
declare function getAssistantText(response: Response): string;
|
|
864
|
+
/**
|
|
865
|
+
* Handler function type for tool execution.
|
|
866
|
+
* Can be sync or async, receives parsed arguments and returns a result.
|
|
867
|
+
*/
|
|
868
|
+
type ToolHandler<T = unknown, R = unknown> = (args: T, call: ToolCall) => R | Promise<R>;
|
|
869
|
+
/**
|
|
870
|
+
* Result of executing a tool call.
|
|
871
|
+
*/
|
|
872
|
+
interface ToolExecutionResult {
|
|
873
|
+
toolCallId: string;
|
|
874
|
+
toolName: string;
|
|
875
|
+
result: unknown;
|
|
876
|
+
error?: string;
|
|
877
|
+
/**
|
|
878
|
+
* True if the error is due to malformed arguments (JSON parse or validation failure)
|
|
879
|
+
* and the model should be given a chance to retry with corrected arguments.
|
|
880
|
+
*/
|
|
881
|
+
isRetryable?: boolean;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Registry for mapping tool names to handler functions with automatic dispatch.
|
|
885
|
+
*
|
|
886
|
+
* @example
|
|
887
|
+
* ```typescript
|
|
888
|
+
* const registry = new ToolRegistry()
|
|
889
|
+
* .register("get_weather", async (args) => {
|
|
890
|
+
* return { temp: 72, unit: "fahrenheit" };
|
|
891
|
+
* })
|
|
892
|
+
* .register("search", async (args) => {
|
|
893
|
+
* return { results: ["result1", "result2"] };
|
|
894
|
+
* });
|
|
895
|
+
*
|
|
896
|
+
* // Execute all tool calls from a response
|
|
897
|
+
* const results = await registry.executeAll(response.toolCalls);
|
|
898
|
+
*
|
|
899
|
+
* // Convert results to messages for the next request
|
|
900
|
+
* const messages = registry.resultsToMessages(results);
|
|
901
|
+
* ```
|
|
902
|
+
*/
|
|
903
|
+
declare class ToolRegistry {
|
|
904
|
+
private handlers;
|
|
905
|
+
/**
|
|
906
|
+
* Registers a handler function for a tool name.
|
|
907
|
+
* @param name - The tool name (must match the function name in the tool definition)
|
|
908
|
+
* @param handler - Function to execute when this tool is called
|
|
909
|
+
* @returns this for chaining
|
|
910
|
+
*/
|
|
911
|
+
register<T = unknown, R = unknown>(name: string, handler: ToolHandler<T, R>): this;
|
|
912
|
+
/**
|
|
913
|
+
* Unregisters a tool handler.
|
|
914
|
+
* @param name - The tool name to unregister
|
|
915
|
+
* @returns true if the handler was removed, false if it didn't exist
|
|
916
|
+
*/
|
|
917
|
+
unregister(name: string): boolean;
|
|
918
|
+
/**
|
|
919
|
+
* Checks if a handler is registered for the given tool name.
|
|
920
|
+
*/
|
|
921
|
+
has(name: string): boolean;
|
|
922
|
+
/**
|
|
923
|
+
* Returns the list of registered tool names.
|
|
924
|
+
*/
|
|
925
|
+
getRegisteredTools(): string[];
|
|
926
|
+
/**
|
|
927
|
+
* Executes a single tool call.
|
|
928
|
+
* @param call - The tool call to execute
|
|
929
|
+
* @returns The execution result
|
|
930
|
+
*/
|
|
931
|
+
execute(call: ToolCall): Promise<ToolExecutionResult>;
|
|
932
|
+
/**
|
|
933
|
+
* Executes multiple tool calls in parallel.
|
|
934
|
+
* @param calls - Array of tool calls to execute
|
|
935
|
+
* @returns Array of execution results in the same order as input
|
|
936
|
+
*/
|
|
937
|
+
executeAll(calls: ToolCall[]): Promise<ToolExecutionResult[]>;
|
|
938
|
+
/**
|
|
939
|
+
* Converts execution results to tool result messages.
|
|
940
|
+
* Useful for appending to the conversation history.
|
|
941
|
+
* @param results - Array of execution results
|
|
942
|
+
* @returns Array of tool result input items (role "tool")
|
|
943
|
+
*/
|
|
944
|
+
resultsToMessages(results: ToolExecutionResult[]): InputItem[];
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Formats a tool execution error into a message suitable for sending back to the model.
|
|
948
|
+
* The message is designed to help the model understand what went wrong and correct it.
|
|
949
|
+
*
|
|
950
|
+
* @example
|
|
951
|
+
* ```typescript
|
|
952
|
+
* const result = await registry.execute(toolCall);
|
|
953
|
+
* if (result.error && result.isRetryable) {
|
|
954
|
+
* const errorMessage = formatToolErrorForModel(result);
|
|
955
|
+
* messages.push(toolResultMessage(result.toolCallId, errorMessage));
|
|
956
|
+
* // Continue conversation to let model retry
|
|
957
|
+
* }
|
|
958
|
+
* ```
|
|
959
|
+
*/
|
|
960
|
+
declare function formatToolErrorForModel(result: ToolExecutionResult): string;
|
|
961
|
+
/**
|
|
962
|
+
* Checks if any results have retryable errors.
|
|
963
|
+
*
|
|
964
|
+
* @example
|
|
965
|
+
* ```typescript
|
|
966
|
+
* const results = await registry.executeAll(toolCalls);
|
|
967
|
+
* if (hasRetryableErrors(results)) {
|
|
968
|
+
* // Send error messages back to model and continue conversation
|
|
969
|
+
* }
|
|
970
|
+
* ```
|
|
971
|
+
*/
|
|
972
|
+
declare function hasRetryableErrors(results: ToolExecutionResult[]): boolean;
|
|
973
|
+
/**
|
|
974
|
+
* Filters results to only those with retryable errors.
|
|
975
|
+
*/
|
|
976
|
+
declare function getRetryableErrors(results: ToolExecutionResult[]): ToolExecutionResult[];
|
|
977
|
+
/**
|
|
978
|
+
* Creates tool result messages for retryable errors, formatted to help the model correct them.
|
|
979
|
+
*
|
|
980
|
+
* @example
|
|
981
|
+
* ```typescript
|
|
982
|
+
* const results = await registry.executeAll(toolCalls);
|
|
983
|
+
* if (hasRetryableErrors(results)) {
|
|
984
|
+
* const retryMessages = createRetryMessages(results);
|
|
985
|
+
* messages.push(...retryMessages);
|
|
986
|
+
* // Make another API call to let model retry
|
|
987
|
+
* }
|
|
988
|
+
* ```
|
|
989
|
+
*/
|
|
990
|
+
declare function createRetryMessages(results: ToolExecutionResult[]): InputItem[];
|
|
991
|
+
/**
|
|
992
|
+
* Options for executeWithRetry.
|
|
993
|
+
*/
|
|
994
|
+
interface RetryOptions {
|
|
995
|
+
/**
|
|
996
|
+
* Maximum number of retry attempts for parse/validation errors.
|
|
997
|
+
* @default 2
|
|
998
|
+
*/
|
|
999
|
+
maxRetries?: number;
|
|
1000
|
+
/**
|
|
1001
|
+
* Callback invoked when a retryable error occurs.
|
|
1002
|
+
* Should return new tool calls from the model's response.
|
|
1003
|
+
* If not provided, executeWithRetry will not retry automatically.
|
|
1004
|
+
*
|
|
1005
|
+
* @param errorMessages - Messages to send back to the model
|
|
1006
|
+
* @param attempt - Current attempt number (1-based)
|
|
1007
|
+
* @returns New tool calls from the model, or empty array to stop retrying
|
|
1008
|
+
*/
|
|
1009
|
+
onRetry?: (errorMessages: InputItem[], attempt: number) => Promise<ToolCall[]>;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* Executes tool calls with automatic retry on parse/validation errors.
|
|
1013
|
+
*
|
|
1014
|
+
* This is a higher-level utility that wraps registry.executeAll with retry logic.
|
|
1015
|
+
* When a retryable error occurs, it calls the onRetry callback to get new tool calls
|
|
1016
|
+
* from the model and continues execution.
|
|
1017
|
+
*
|
|
1018
|
+
* **Result Preservation**: Successful results are preserved across retries. If you
|
|
1019
|
+
* execute multiple tool calls and only some fail, the successful results are kept
|
|
1020
|
+
* and merged with the results from retry attempts. Results are keyed by toolCallId,
|
|
1021
|
+
* so if a retry returns a call with the same ID as a previous result, the newer
|
|
1022
|
+
* result will replace it.
|
|
1023
|
+
*
|
|
1024
|
+
* @example
|
|
1025
|
+
* ```typescript
|
|
1026
|
+
* const results = await executeWithRetry(registry, toolCalls, {
|
|
1027
|
+
* maxRetries: 2,
|
|
1028
|
+
* onRetry: async (errorMessages, attempt) => {
|
|
1029
|
+
* console.log(`Retry attempt ${attempt}`);
|
|
1030
|
+
* // Add error messages to conversation and call the model again
|
|
1031
|
+
* messages.push(assistantMessageWithToolCalls("", toolCalls));
|
|
1032
|
+
* messages.push(...errorMessages);
|
|
1033
|
+
* const req = client.responses
|
|
1034
|
+
* .new()
|
|
1035
|
+
* .model("...")
|
|
1036
|
+
* .input(messages)
|
|
1037
|
+
* .tools(tools)
|
|
1038
|
+
* .build();
|
|
1039
|
+
* const response = await client.responses.create(req);
|
|
1040
|
+
* return firstToolCall(response) ? [firstToolCall(response)!] : [];
|
|
1041
|
+
* },
|
|
1042
|
+
* });
|
|
1043
|
+
* ```
|
|
1044
|
+
*
|
|
1045
|
+
* @param registry - The tool registry to use for execution
|
|
1046
|
+
* @param toolCalls - Initial tool calls to execute
|
|
1047
|
+
* @param options - Retry configuration
|
|
1048
|
+
* @returns Final execution results after all retries, including preserved successes
|
|
1049
|
+
*/
|
|
1050
|
+
declare function executeWithRetry(registry: ToolRegistry, toolCalls: ToolCall[], options?: RetryOptions): Promise<ToolExecutionResult[]>;
|
|
1051
|
+
|
|
1052
|
+
export { tryParseToolArgs 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, getAssistantText as W, ToolCallAccumulator as X, zodToJsonSchema as Y, type ZodLikeSchema as Z, parseToolArgs as _, type RequestContext as a, stopReasonToString as a$, parseToolArgsRaw 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 Schema as a8, type ToolHandler as a9, type MessageRole as aA, ContentPartTypes as aB, type ContentPartType as aC, type ContentPart as aD, InputItemTypes as aE, type InputItemType as aF, OutputItemTypes as aG, type OutputItemType as aH, type OutputItem as aI, ToolTypes as aJ, type ToolType as aK, type FunctionTool as aL, type XSearchConfig as aM, type CodeExecConfig as aN, ToolChoiceTypes as aO, type ToolChoiceType as aP, type FunctionCall as aQ, OutputFormatTypes as aR, type OutputFormatType as aS, type JSONSchemaFormat as aT, type Citation as aU, type HttpRequestMetrics as aV, type StreamFirstTokenMetrics as aW, type TokenUsageMetrics as aX, mergeMetrics as aY, mergeTrace as aZ, normalizeStopReason as a_, type RetryOptions as aa, SDK_VERSION as ab, DEFAULT_CLIENT_HEADER as ac, DEFAULT_CONNECT_TIMEOUT_MS as ad, DEFAULT_REQUEST_TIMEOUT_MS as ae, type NonEmptyArray as af, StopReasons as ag, type KnownStopReason as ah, type StopReason as ai, asProviderId as aj, asModelId as ak, asTierCode as al, SubscriptionStatuses as am, type SubscriptionStatusKind as an, BillingProviders as ao, type BillingProvider as ap, type CustomerMetadata as aq, type ModelRelayBaseOptions as ar, type ModelRelayTokenOptions as as, type ModelRelayTokenProviderOptions as at, type TokenType as au, type Usage as av, createUsage as aw, type UsageSummary as ax, type Project as ay, MessageRoles as az, type TokenProvider as b, normalizeModelId as b0, modelToString as b1, type ResponseEventType as b2, type MessageStartData as b3, type MessageDeltaData as b4, type MessageStopData as b5, type ToolCallDelta as b6, type FunctionCallDelta as b7, type StructuredJSONRecordType as b8, type DeepPartial as b9, type APICustomerRef as ba, type APICheckoutSession as bb, type APIUsage as bc, type APIResponsesResponse as bd, type APIKey as be, 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, createFunctionToolFromSchema as s, toolChoiceAuto as t, toolChoiceRequired as u, toolChoiceNone as v, hasToolCalls as w, firstToolCall as x, createUserMessage as y, createAssistantMessage as z };
|