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