@modelrelay/sdk 0.4.0 → 0.7.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/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  declare const SDK_VERSION: string;
2
2
  declare const DEFAULT_BASE_URL = "https://api.modelrelay.ai/api/v1";
3
- declare const STAGING_BASE_URL = "https://api-stg.modelrelay.ai/api/v1";
4
- declare const SANDBOX_BASE_URL = "https://api.sandbox.modelrelay.ai/api/v1";
5
3
  declare const DEFAULT_CLIENT_HEADER: string;
6
4
  declare const DEFAULT_CONNECT_TIMEOUT_MS = 5000;
7
5
  declare const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
@@ -28,7 +26,6 @@ declare const Providers: {
28
26
  readonly OpenAI: "openai";
29
27
  readonly Anthropic: "anthropic";
30
28
  readonly Grok: "grok";
31
- readonly OpenRouter: "openrouter";
32
29
  readonly Echo: "echo";
33
30
  };
34
31
  type KnownProvider = (typeof Providers)[keyof typeof Providers];
@@ -42,16 +39,117 @@ declare const Models: {
42
39
  readonly AnthropicClaude35HaikuLatest: "anthropic/claude-3-5-haiku-latest";
43
40
  readonly AnthropicClaude35SonnetLatest: "anthropic/claude-3-5-sonnet-latest";
44
41
  readonly AnthropicClaudeOpus45: "anthropic/claude-opus-4-5-20251101";
45
- readonly OpenRouterClaude35Haiku: "anthropic/claude-3.5-haiku";
42
+ readonly AnthropicClaude35Haiku: "anthropic/claude-3.5-haiku";
46
43
  readonly Grok2: "grok-2";
47
- readonly Grok4Fast: "grok-4-fast";
44
+ readonly Grok4_1FastNonReasoning: "grok-4-1-fast-non-reasoning";
45
+ readonly Grok4_1FastReasoning: "grok-4-1-fast-reasoning";
48
46
  readonly Echo1: "echo-1";
49
47
  };
50
48
  type KnownModel = (typeof Models)[keyof typeof Models];
51
49
  type ModelId = KnownModel | {
52
50
  other: string;
53
51
  } | string;
54
- interface ModelRelayOptions {
52
+ /**
53
+ * Common configuration options for the ModelRelay client.
54
+ */
55
+ interface ModelRelayBaseOptions {
56
+ /**
57
+ * Optional base URL override. Defaults to production API.
58
+ */
59
+ baseUrl?: string;
60
+ fetch?: typeof fetch;
61
+ /**
62
+ * Default customer metadata used when exchanging publishable keys for frontend tokens.
63
+ */
64
+ customer?: FrontendCustomer;
65
+ /**
66
+ * Optional client header override for telemetry.
67
+ */
68
+ clientHeader?: string;
69
+ /**
70
+ * Default connect timeout in milliseconds (applies to each attempt).
71
+ */
72
+ connectTimeoutMs?: number;
73
+ /**
74
+ * Default request timeout in milliseconds (non-streaming). Set to 0 to disable.
75
+ */
76
+ timeoutMs?: number;
77
+ /**
78
+ * Retry configuration applied to all requests (can be overridden per call). Set to `false` to disable retries.
79
+ */
80
+ retry?: RetryConfig | false;
81
+ /**
82
+ * Default HTTP headers applied to every request.
83
+ */
84
+ defaultHeaders?: Record<string, string>;
85
+ /**
86
+ * Default metadata merged into every chat completion request.
87
+ */
88
+ defaultMetadata?: Record<string, string>;
89
+ /**
90
+ * Optional metrics callbacks for latency/usage.
91
+ */
92
+ metrics?: MetricsCallbacks;
93
+ /**
94
+ * Optional trace/log hooks for request + stream lifecycle.
95
+ */
96
+ trace?: TraceCallbacks;
97
+ }
98
+ /**
99
+ * Configuration options requiring an API key.
100
+ */
101
+ interface ModelRelayKeyOptions extends ModelRelayBaseOptions {
102
+ /**
103
+ * API key (secret or publishable). Required.
104
+ * - Secret keys (`mr_sk_...`) are for server-side API calls.
105
+ * - Publishable keys (`mr_pk_...`) are for frontend token exchange.
106
+ */
107
+ key: string;
108
+ /**
109
+ * Optional bearer token (takes precedence over key for requests when provided).
110
+ */
111
+ token?: string;
112
+ }
113
+ /**
114
+ * Configuration options requiring an access token.
115
+ */
116
+ interface ModelRelayTokenOptions extends ModelRelayBaseOptions {
117
+ /**
118
+ * Optional API key.
119
+ */
120
+ key?: string;
121
+ /**
122
+ * Bearer token to call the API directly (server or frontend token). Required.
123
+ */
124
+ token: string;
125
+ }
126
+ /**
127
+ * ModelRelay client configuration.
128
+ *
129
+ * You must provide at least one of `key` or `token` for authentication.
130
+ * This is enforced at compile time through discriminated union types.
131
+ *
132
+ * @example With API key (server-side)
133
+ * ```typescript
134
+ * const client = new ModelRelay({ key: "mr_sk_..." });
135
+ * ```
136
+ *
137
+ * @example With access token (frontend or after token exchange)
138
+ * ```typescript
139
+ * const client = new ModelRelay({ token: frontendToken });
140
+ * ```
141
+ *
142
+ * @example With publishable key (frontend token exchange)
143
+ * ```typescript
144
+ * const client = new ModelRelay({ key: "mr_pk_...", customer: { id: "user123" } });
145
+ * ```
146
+ */
147
+ type ModelRelayOptions = ModelRelayKeyOptions | ModelRelayTokenOptions;
148
+ /**
149
+ * @deprecated Use ModelRelayOptions instead. This type allows empty configuration
150
+ * which will fail at runtime.
151
+ */
152
+ interface ModelRelayOptionsLegacy {
55
153
  /**
56
154
  * API key (secret or publishable). Publishable keys are required for frontend token exchange.
57
155
  */
@@ -61,9 +159,8 @@ interface ModelRelayOptions {
61
159
  */
62
160
  token?: string;
63
161
  /**
64
- * Optional environment preset; overridden by `baseUrl` when provided.
162
+ * Optional base URL override. Defaults to production API.
65
163
  */
66
- environment?: Environment;
67
164
  baseUrl?: string;
68
165
  fetch?: typeof fetch;
69
166
  /**
@@ -103,7 +200,6 @@ interface ModelRelayOptions {
103
200
  */
104
201
  trace?: TraceCallbacks;
105
202
  }
106
- type Environment = "production" | "staging" | "sandbox";
107
203
  interface FrontendCustomer {
108
204
  id: string;
109
205
  deviceId?: string;
@@ -164,6 +260,60 @@ interface Project {
164
260
  interface ChatMessage {
165
261
  role: string;
166
262
  content: string;
263
+ toolCalls?: ToolCall[];
264
+ toolCallId?: string;
265
+ }
266
+ declare const ToolTypes: {
267
+ readonly Function: "function";
268
+ readonly WebSearch: "web_search";
269
+ readonly XSearch: "x_search";
270
+ readonly CodeExecution: "code_execution";
271
+ };
272
+ type ToolType = (typeof ToolTypes)[keyof typeof ToolTypes];
273
+ interface FunctionTool {
274
+ name: string;
275
+ description?: string;
276
+ parameters?: Record<string, unknown>;
277
+ }
278
+ interface WebSearchConfig {
279
+ allowedDomains?: string[];
280
+ excludedDomains?: string[];
281
+ maxUses?: number;
282
+ }
283
+ interface XSearchConfig {
284
+ allowedHandles?: string[];
285
+ excludedHandles?: string[];
286
+ fromDate?: string;
287
+ toDate?: string;
288
+ }
289
+ interface CodeExecConfig {
290
+ language?: string;
291
+ timeoutMs?: number;
292
+ }
293
+ interface Tool {
294
+ type: ToolType;
295
+ function?: FunctionTool;
296
+ webSearch?: WebSearchConfig;
297
+ xSearch?: XSearchConfig;
298
+ codeExecution?: CodeExecConfig;
299
+ }
300
+ declare const ToolChoiceTypes: {
301
+ readonly Auto: "auto";
302
+ readonly Required: "required";
303
+ readonly None: "none";
304
+ };
305
+ type ToolChoiceType = (typeof ToolChoiceTypes)[keyof typeof ToolChoiceTypes];
306
+ interface ToolChoice {
307
+ type: ToolChoiceType;
308
+ }
309
+ interface FunctionCall {
310
+ name: string;
311
+ arguments: string;
312
+ }
313
+ interface ToolCall {
314
+ id: string;
315
+ type: ToolType;
316
+ function?: FunctionCall;
167
317
  }
168
318
  interface ChatCompletionCreateParams {
169
319
  model: ModelId;
@@ -174,6 +324,14 @@ interface ChatCompletionCreateParams {
174
324
  metadata?: Record<string, string>;
175
325
  stop?: string[];
176
326
  stopSequences?: string[];
327
+ /**
328
+ * Tools available for the model to call.
329
+ */
330
+ tools?: Tool[];
331
+ /**
332
+ * Controls how the model responds to tool calls.
333
+ */
334
+ toolChoice?: ToolChoice;
177
335
  /**
178
336
  * When using publishable keys, a customer id is required to mint a frontend token.
179
337
  */
@@ -195,6 +353,7 @@ interface ChatCompletionResponse {
195
353
  model?: ModelId;
196
354
  usage: Usage;
197
355
  requestId?: string;
356
+ toolCalls?: ToolCall[];
198
357
  }
199
358
  interface FieldError {
200
359
  field?: string;
@@ -267,7 +426,7 @@ declare function normalizeProvider(value?: unknown): ProviderId | undefined;
267
426
  declare function providerToString(value?: ProviderId): string | undefined;
268
427
  declare function normalizeModelId(value: unknown): ModelId | undefined;
269
428
  declare function modelToString(value: ModelId): string;
270
- type ChatEventType = "message_start" | "message_delta" | "message_stop" | "ping" | "custom";
429
+ type ChatEventType = "message_start" | "message_delta" | "message_stop" | "tool_use_start" | "tool_use_delta" | "tool_use_stop" | "ping" | "custom";
271
430
  interface MessageStartData {
272
431
  responseId?: string;
273
432
  model?: string;
@@ -290,11 +449,27 @@ interface MessageStopData {
290
449
  model?: ModelId;
291
450
  [key: string]: unknown;
292
451
  }
452
+ /** Incremental update to a tool call during streaming. */
453
+ interface ToolCallDelta {
454
+ index: number;
455
+ id?: string;
456
+ type?: string;
457
+ function?: FunctionCallDelta;
458
+ }
459
+ /** Incremental function call data. */
460
+ interface FunctionCallDelta {
461
+ name?: string;
462
+ arguments?: string;
463
+ }
293
464
  interface ChatCompletionEvent<T = unknown> {
294
465
  type: ChatEventType;
295
466
  event: string;
296
467
  data?: T;
297
468
  textDelta?: string;
469
+ /** Incremental tool call update during streaming. */
470
+ toolCallDelta?: ToolCallDelta;
471
+ /** Completed tool calls when type is tool_use_stop or message_stop. */
472
+ toolCalls?: ToolCall[];
298
473
  responseId?: string;
299
474
  model?: ModelId;
300
475
  stopReason?: StopReason;
@@ -424,7 +599,6 @@ declare class HTTPClient {
424
599
  timeoutMs?: number;
425
600
  retry?: RetryConfig | false;
426
601
  defaultHeaders?: Record<string, string>;
427
- environment?: Environment;
428
602
  metrics?: MetricsCallbacks;
429
603
  trace?: TraceCallbacks;
430
604
  });
@@ -656,6 +830,49 @@ declare class CustomersClient {
656
830
  getSubscription(customerId: string): Promise<SubscriptionStatus>;
657
831
  }
658
832
 
833
+ /**
834
+ * Billing interval for a tier.
835
+ */
836
+ type PriceInterval = "month" | "year";
837
+ /**
838
+ * Tier represents a pricing tier in a ModelRelay project.
839
+ */
840
+ interface Tier {
841
+ id: string;
842
+ project_id: string;
843
+ tier_code: string;
844
+ display_name: string;
845
+ spend_limit_cents: number;
846
+ stripe_price_id?: string;
847
+ price_amount?: number;
848
+ price_currency?: string;
849
+ price_interval?: PriceInterval;
850
+ trial_days?: number;
851
+ created_at: string;
852
+ updated_at: string;
853
+ }
854
+ interface TiersClientConfig {
855
+ apiKey?: string;
856
+ }
857
+ /**
858
+ * TiersClient provides methods to query tiers in a project.
859
+ * Works with both publishable keys (mr_pk_*) and secret keys (mr_sk_*).
860
+ */
861
+ declare class TiersClient {
862
+ private readonly http;
863
+ private readonly apiKey?;
864
+ constructor(http: HTTPClient, cfg: TiersClientConfig);
865
+ private ensureApiKey;
866
+ /**
867
+ * List all tiers in the project.
868
+ */
869
+ list(): Promise<Tier[]>;
870
+ /**
871
+ * Get a tier by ID.
872
+ */
873
+ get(tierId: string): Promise<Tier>;
874
+ }
875
+
659
876
  type ErrorCategory = "config" | "transport" | "api";
660
877
  declare class ModelRelayError extends Error {
661
878
  category: ErrorCategory;
@@ -700,12 +917,409 @@ declare class APIError extends ModelRelayError {
700
917
  }
701
918
  declare function parseErrorResponse(response: Response, retries?: RetryMetadata): Promise<APIError>;
702
919
 
920
+ /**
921
+ * Interface for Zod-like schema types.
922
+ * Compatible with Zod's ZodType and similar libraries.
923
+ */
924
+ interface ZodLikeSchema {
925
+ _def: {
926
+ typeName: string;
927
+ [key: string]: unknown;
928
+ };
929
+ parse(data: unknown): unknown;
930
+ safeParse(data: unknown): {
931
+ success: boolean;
932
+ data?: unknown;
933
+ error?: unknown;
934
+ };
935
+ }
936
+ /**
937
+ * Options for JSON Schema generation.
938
+ */
939
+ interface JsonSchemaOptions {
940
+ /** Whether to include $schema property. Defaults to false. */
941
+ includeSchema?: boolean;
942
+ /** Target JSON Schema version. Defaults to "draft-07". */
943
+ target?: "draft-04" | "draft-07" | "draft-2019-09" | "draft-2020-12";
944
+ }
945
+ /**
946
+ * Converts a Zod schema to JSON Schema.
947
+ * This is a simplified implementation that handles common Zod types.
948
+ * For full Zod support, consider using the 'zod-to-json-schema' package.
949
+ *
950
+ * @param schema - A Zod schema
951
+ * @param options - Optional JSON Schema generation options
952
+ * @returns A JSON Schema object
953
+ */
954
+ declare function zodToJsonSchema(schema: ZodLikeSchema, options?: JsonSchemaOptions): Record<string, unknown>;
955
+ /**
956
+ * Creates a function tool from a Zod schema.
957
+ *
958
+ * This function automatically converts a Zod schema to a JSON Schema
959
+ * and creates a tool definition. It eliminates the need to manually
960
+ * write JSON schemas for tool parameters.
961
+ *
962
+ * @example
963
+ * ```typescript
964
+ * import { z } from "zod";
965
+ * import { createFunctionToolFromSchema } from "@modelrelay/sdk";
966
+ *
967
+ * const weatherParams = z.object({
968
+ * location: z.string().describe("City name"),
969
+ * unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
970
+ * });
971
+ *
972
+ * const weatherTool = createFunctionToolFromSchema(
973
+ * "get_weather",
974
+ * "Get weather for a location",
975
+ * weatherParams
976
+ * );
977
+ * ```
978
+ *
979
+ * @param name - The tool name
980
+ * @param description - A description of what the tool does
981
+ * @param schema - A Zod schema defining the tool's parameters
982
+ * @param options - Optional JSON Schema generation options
983
+ * @returns A Tool definition with the JSON schema derived from the Zod schema
984
+ */
985
+ declare function createFunctionToolFromSchema(name: string, description: string, schema: ZodLikeSchema, options?: JsonSchemaOptions): Tool;
986
+ /**
987
+ * Creates a function tool with the given name, description, and JSON schema.
988
+ */
989
+ declare function createFunctionTool(name: string, description: string, parameters?: Record<string, unknown>): Tool;
990
+ /**
991
+ * Creates a web search tool with optional domain filters.
992
+ */
993
+ declare function createWebSearchTool(options?: {
994
+ allowedDomains?: string[];
995
+ excludedDomains?: string[];
996
+ maxUses?: number;
997
+ }): Tool;
998
+ /**
999
+ * Returns a ToolChoice that lets the model decide when to use tools.
1000
+ */
1001
+ declare function toolChoiceAuto(): ToolChoice;
1002
+ /**
1003
+ * Returns a ToolChoice that forces the model to use a tool.
1004
+ */
1005
+ declare function toolChoiceRequired(): ToolChoice;
1006
+ /**
1007
+ * Returns a ToolChoice that prevents the model from using tools.
1008
+ */
1009
+ declare function toolChoiceNone(): ToolChoice;
1010
+ /**
1011
+ * Returns true if the response contains tool calls.
1012
+ */
1013
+ declare function hasToolCalls(response: ChatCompletionResponse): boolean;
1014
+ /**
1015
+ * Returns the first tool call from a response, or undefined if none exist.
1016
+ */
1017
+ declare function firstToolCall(response: ChatCompletionResponse): ToolCall | undefined;
1018
+ /**
1019
+ * Creates a message containing the result of a tool call.
1020
+ */
1021
+ declare function toolResultMessage(toolCallId: string, result: unknown): ChatMessage;
1022
+ /**
1023
+ * Creates a tool result message from a ToolCall.
1024
+ * Convenience wrapper around toolResultMessage using the call's ID.
1025
+ */
1026
+ declare function respondToToolCall(call: ToolCall, result: unknown): ChatMessage;
1027
+ /**
1028
+ * Creates an assistant message that includes tool calls.
1029
+ * Used to include the assistant's tool-calling turn in conversation history.
1030
+ */
1031
+ declare function assistantMessageWithToolCalls(content: string, toolCalls: ToolCall[]): ChatMessage;
1032
+ /**
1033
+ * Accumulates streaming tool call deltas into complete tool calls.
1034
+ */
1035
+ declare class ToolCallAccumulator {
1036
+ private calls;
1037
+ /**
1038
+ * Processes a streaming tool call delta.
1039
+ * Returns true if this started a new tool call.
1040
+ */
1041
+ processDelta(delta: ToolCallDelta): boolean;
1042
+ /**
1043
+ * Returns all accumulated tool calls in index order.
1044
+ */
1045
+ getToolCalls(): ToolCall[];
1046
+ /**
1047
+ * Returns a specific tool call by index, or undefined if not found.
1048
+ */
1049
+ getToolCall(index: number): ToolCall | undefined;
1050
+ /**
1051
+ * Clears all accumulated tool calls.
1052
+ */
1053
+ reset(): void;
1054
+ }
1055
+ /**
1056
+ * Error thrown when tool argument parsing or validation fails.
1057
+ * Contains a descriptive message suitable for sending back to the model.
1058
+ */
1059
+ declare class ToolArgsError extends Error {
1060
+ /** The tool call ID for correlation */
1061
+ readonly toolCallId: string;
1062
+ /** The tool name that was called */
1063
+ readonly toolName: string;
1064
+ /** The raw arguments string that failed to parse */
1065
+ readonly rawArguments: string;
1066
+ constructor(message: string, toolCallId: string, toolName: string, rawArguments: string);
1067
+ }
1068
+ /**
1069
+ * Schema interface compatible with Zod, Yup, and similar validation libraries.
1070
+ * Any object with a `parse` method that returns the validated type works.
1071
+ */
1072
+ interface Schema<T> {
1073
+ parse(data: unknown): T;
1074
+ }
1075
+ /**
1076
+ * Parses and validates tool call arguments using a schema.
1077
+ *
1078
+ * Works with any schema library that has a `parse` method (Zod, Yup, etc.).
1079
+ * Throws a descriptive ToolArgsError if parsing or validation fails.
1080
+ *
1081
+ * @example
1082
+ * ```typescript
1083
+ * import { z } from "zod";
1084
+ *
1085
+ * const WeatherArgs = z.object({
1086
+ * location: z.string(),
1087
+ * unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
1088
+ * });
1089
+ *
1090
+ * // In your tool handler:
1091
+ * const args = parseToolArgs(toolCall, WeatherArgs);
1092
+ * // args is typed as { location: string; unit: "celsius" | "fahrenheit" }
1093
+ * ```
1094
+ *
1095
+ * @param call - The tool call containing arguments to parse
1096
+ * @param schema - A schema with a `parse` method (Zod, Yup, etc.)
1097
+ * @returns The parsed and validated arguments with proper types
1098
+ * @throws {ToolArgsError} If JSON parsing or schema validation fails
1099
+ */
1100
+ declare function parseToolArgs<T>(call: ToolCall, schema: Schema<T>): T;
1101
+ /**
1102
+ * Attempts to parse tool arguments, returning a result object instead of throwing.
1103
+ *
1104
+ * @example
1105
+ * ```typescript
1106
+ * const result = tryParseToolArgs(toolCall, WeatherArgs);
1107
+ * if (result.success) {
1108
+ * console.log(result.data.location);
1109
+ * } else {
1110
+ * console.error(result.error.message);
1111
+ * }
1112
+ * ```
1113
+ *
1114
+ * @param call - The tool call containing arguments to parse
1115
+ * @param schema - A schema with a `parse` method
1116
+ * @returns An object with either { success: true, data: T } or { success: false, error: ToolArgsError }
1117
+ */
1118
+ declare function tryParseToolArgs<T>(call: ToolCall, schema: Schema<T>): {
1119
+ success: true;
1120
+ data: T;
1121
+ } | {
1122
+ success: false;
1123
+ error: ToolArgsError;
1124
+ };
1125
+ /**
1126
+ * Parses raw JSON arguments without schema validation.
1127
+ * Useful when you want JSON parsing error handling but not schema validation.
1128
+ *
1129
+ * @param call - The tool call containing arguments to parse
1130
+ * @returns The parsed JSON as an unknown type
1131
+ * @throws {ToolArgsError} If JSON parsing fails
1132
+ */
1133
+ declare function parseToolArgsRaw(call: ToolCall): unknown;
1134
+ /**
1135
+ * Handler function type for tool execution.
1136
+ * Can be sync or async, receives parsed arguments and returns a result.
1137
+ */
1138
+ type ToolHandler<T = unknown, R = unknown> = (args: T, call: ToolCall) => R | Promise<R>;
1139
+ /**
1140
+ * Result of executing a tool call.
1141
+ */
1142
+ interface ToolExecutionResult {
1143
+ toolCallId: string;
1144
+ toolName: string;
1145
+ result: unknown;
1146
+ error?: string;
1147
+ /**
1148
+ * True if the error is due to malformed arguments (JSON parse or validation failure)
1149
+ * and the model should be given a chance to retry with corrected arguments.
1150
+ */
1151
+ isRetryable?: boolean;
1152
+ }
1153
+ /**
1154
+ * Registry for mapping tool names to handler functions with automatic dispatch.
1155
+ *
1156
+ * @example
1157
+ * ```typescript
1158
+ * const registry = new ToolRegistry()
1159
+ * .register("get_weather", async (args) => {
1160
+ * return { temp: 72, unit: "fahrenheit" };
1161
+ * })
1162
+ * .register("search", async (args) => {
1163
+ * return { results: ["result1", "result2"] };
1164
+ * });
1165
+ *
1166
+ * // Execute all tool calls from a response
1167
+ * const results = await registry.executeAll(response.toolCalls);
1168
+ *
1169
+ * // Convert results to messages for the next request
1170
+ * const messages = registry.resultsToMessages(results);
1171
+ * ```
1172
+ */
1173
+ declare class ToolRegistry {
1174
+ private handlers;
1175
+ /**
1176
+ * Registers a handler function for a tool name.
1177
+ * @param name - The tool name (must match the function name in the tool definition)
1178
+ * @param handler - Function to execute when this tool is called
1179
+ * @returns this for chaining
1180
+ */
1181
+ register<T = unknown, R = unknown>(name: string, handler: ToolHandler<T, R>): this;
1182
+ /**
1183
+ * Unregisters a tool handler.
1184
+ * @param name - The tool name to unregister
1185
+ * @returns true if the handler was removed, false if it didn't exist
1186
+ */
1187
+ unregister(name: string): boolean;
1188
+ /**
1189
+ * Checks if a handler is registered for the given tool name.
1190
+ */
1191
+ has(name: string): boolean;
1192
+ /**
1193
+ * Returns the list of registered tool names.
1194
+ */
1195
+ getRegisteredTools(): string[];
1196
+ /**
1197
+ * Executes a single tool call.
1198
+ * @param call - The tool call to execute
1199
+ * @returns The execution result
1200
+ */
1201
+ execute(call: ToolCall): Promise<ToolExecutionResult>;
1202
+ /**
1203
+ * Executes multiple tool calls in parallel.
1204
+ * @param calls - Array of tool calls to execute
1205
+ * @returns Array of execution results in the same order as input
1206
+ */
1207
+ executeAll(calls: ToolCall[]): Promise<ToolExecutionResult[]>;
1208
+ /**
1209
+ * Converts execution results to tool result messages.
1210
+ * Useful for appending to the conversation history.
1211
+ * @param results - Array of execution results
1212
+ * @returns Array of ChatMessage objects with role "tool"
1213
+ */
1214
+ resultsToMessages(results: ToolExecutionResult[]): ChatMessage[];
1215
+ }
1216
+ /**
1217
+ * Formats a tool execution error into a message suitable for sending back to the model.
1218
+ * The message is designed to help the model understand what went wrong and correct it.
1219
+ *
1220
+ * @example
1221
+ * ```typescript
1222
+ * const result = await registry.execute(toolCall);
1223
+ * if (result.error && result.isRetryable) {
1224
+ * const errorMessage = formatToolErrorForModel(result);
1225
+ * messages.push(toolResultMessage(result.toolCallId, errorMessage));
1226
+ * // Continue conversation to let model retry
1227
+ * }
1228
+ * ```
1229
+ */
1230
+ declare function formatToolErrorForModel(result: ToolExecutionResult): string;
1231
+ /**
1232
+ * Checks if any results have retryable errors.
1233
+ *
1234
+ * @example
1235
+ * ```typescript
1236
+ * const results = await registry.executeAll(toolCalls);
1237
+ * if (hasRetryableErrors(results)) {
1238
+ * // Send error messages back to model and continue conversation
1239
+ * }
1240
+ * ```
1241
+ */
1242
+ declare function hasRetryableErrors(results: ToolExecutionResult[]): boolean;
1243
+ /**
1244
+ * Filters results to only those with retryable errors.
1245
+ */
1246
+ declare function getRetryableErrors(results: ToolExecutionResult[]): ToolExecutionResult[];
1247
+ /**
1248
+ * Creates tool result messages for retryable errors, formatted to help the model correct them.
1249
+ *
1250
+ * @example
1251
+ * ```typescript
1252
+ * const results = await registry.executeAll(toolCalls);
1253
+ * if (hasRetryableErrors(results)) {
1254
+ * const retryMessages = createRetryMessages(results);
1255
+ * messages.push(...retryMessages);
1256
+ * // Make another API call to let model retry
1257
+ * }
1258
+ * ```
1259
+ */
1260
+ declare function createRetryMessages(results: ToolExecutionResult[]): ChatMessage[];
1261
+ /**
1262
+ * Options for executeWithRetry.
1263
+ */
1264
+ interface RetryOptions {
1265
+ /**
1266
+ * Maximum number of retry attempts for parse/validation errors.
1267
+ * @default 2
1268
+ */
1269
+ maxRetries?: number;
1270
+ /**
1271
+ * Callback invoked when a retryable error occurs.
1272
+ * Should return new tool calls from the model's response.
1273
+ * If not provided, executeWithRetry will not retry automatically.
1274
+ *
1275
+ * @param errorMessages - Messages to send back to the model
1276
+ * @param attempt - Current attempt number (1-based)
1277
+ * @returns New tool calls from the model, or empty array to stop retrying
1278
+ */
1279
+ onRetry?: (errorMessages: ChatMessage[], attempt: number) => Promise<ToolCall[]>;
1280
+ }
1281
+ /**
1282
+ * Executes tool calls with automatic retry on parse/validation errors.
1283
+ *
1284
+ * This is a higher-level utility that wraps registry.executeAll with retry logic.
1285
+ * When a retryable error occurs, it calls the onRetry callback to get new tool calls
1286
+ * from the model and continues execution.
1287
+ *
1288
+ * **Result Preservation**: Successful results are preserved across retries. If you
1289
+ * execute multiple tool calls and only some fail, the successful results are kept
1290
+ * and merged with the results from retry attempts. Results are keyed by toolCallId,
1291
+ * so if a retry returns a call with the same ID as a previous result, the newer
1292
+ * result will replace it.
1293
+ *
1294
+ * @example
1295
+ * ```typescript
1296
+ * const results = await executeWithRetry(registry, toolCalls, {
1297
+ * maxRetries: 2,
1298
+ * onRetry: async (errorMessages, attempt) => {
1299
+ * console.log(`Retry attempt ${attempt}`);
1300
+ * // Add error messages to conversation and call the model again
1301
+ * messages.push(assistantMessageWithToolCalls("", toolCalls));
1302
+ * messages.push(...errorMessages);
1303
+ * const response = await client.chat.completions.create({ messages, tools });
1304
+ * return response.toolCalls ?? [];
1305
+ * },
1306
+ * });
1307
+ * ```
1308
+ *
1309
+ * @param registry - The tool registry to use for execution
1310
+ * @param toolCalls - Initial tool calls to execute
1311
+ * @param options - Retry configuration
1312
+ * @returns Final execution results after all retries, including preserved successes
1313
+ */
1314
+ declare function executeWithRetry(registry: ToolRegistry, toolCalls: ToolCall[], options?: RetryOptions): Promise<ToolExecutionResult[]>;
1315
+
703
1316
  declare class ModelRelay {
704
1317
  readonly chat: ChatClient;
705
1318
  readonly auth: AuthClient;
706
1319
  readonly customers: CustomersClient;
1320
+ readonly tiers: TiersClient;
707
1321
  readonly baseUrl: string;
708
1322
  constructor(options: ModelRelayOptions);
709
1323
  }
710
1324
 
711
- export { type APIChatResponse, type APIChatUsage, type APICheckoutSession, type APICustomerRef, APIError, type APIFrontendToken, type APIKey, AuthClient, ChatClient, type ChatCompletionCreateParams, type ChatCompletionEvent, type ChatCompletionResponse, ChatCompletionsStream, type ChatEventType, type ChatMessage, type CheckoutSession, type CheckoutSessionRequest, ConfigError, type Customer, type CustomerCreateRequest, type CustomerMetadata, type CustomerUpsertRequest, CustomersClient, DEFAULT_BASE_URL, DEFAULT_CLIENT_HEADER, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, type Environment, type ErrorCategory, type FieldError, type FrontendCustomer, type FrontendToken, type FrontendTokenRequest, type HttpRequestMetrics, type KnownModel, type KnownProvider, type KnownStopReason, type MessageDeltaData, type MessageStartData, type MessageStopData, type MetricsCallbacks, type ModelId, ModelRelay, ModelRelayError, type ModelRelayOptions, Models, type NonEmptyArray, type Project, type ProviderId, Providers, type RequestContext, type RetryConfig, type RetryMetadata, SANDBOX_BASE_URL, SDK_VERSION, STAGING_BASE_URL, type StopReason, StopReasons, type StreamFirstTokenMetrics, type SubscriptionStatus, type TokenUsageMetrics, type TraceCallbacks, TransportError, type TransportErrorKind, type Usage, type UsageSummary, isPublishableKey, mergeMetrics, mergeTrace, modelToString, normalizeModelId, normalizeProvider, normalizeStopReason, parseErrorResponse, providerToString, stopReasonToString };
1325
+ export { type APIChatResponse, type APIChatUsage, type APICheckoutSession, type APICustomerRef, APIError, type APIFrontendToken, type APIKey, AuthClient, ChatClient, type ChatCompletionCreateParams, type ChatCompletionEvent, type ChatCompletionResponse, ChatCompletionsStream, type ChatEventType, type ChatMessage, type CheckoutSession, type CheckoutSessionRequest, type CodeExecConfig, ConfigError, type Customer, type CustomerCreateRequest, type CustomerMetadata, type CustomerUpsertRequest, CustomersClient, DEFAULT_BASE_URL, DEFAULT_CLIENT_HEADER, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, type ErrorCategory, type FieldError, type FrontendCustomer, type FrontendToken, type FrontendTokenRequest, type FunctionCall, type FunctionCallDelta, type FunctionTool, type HttpRequestMetrics, type JsonSchemaOptions, type KnownModel, type KnownProvider, type KnownStopReason, type MessageDeltaData, type MessageStartData, type MessageStopData, type MetricsCallbacks, type ModelId, ModelRelay, type ModelRelayBaseOptions, ModelRelayError, type ModelRelayKeyOptions, type ModelRelayOptions, type ModelRelayOptionsLegacy, type ModelRelayTokenOptions, Models, type NonEmptyArray, type PriceInterval, type Project, type ProviderId, Providers, type RequestContext, type RetryConfig, type RetryMetadata, type RetryOptions, SDK_VERSION, type Schema, type StopReason, StopReasons, type StreamFirstTokenMetrics, type SubscriptionStatus, type Tier, TiersClient, type TokenUsageMetrics, type Tool, ToolArgsError, type ToolCall, ToolCallAccumulator, type ToolCallDelta, type ToolChoice, type ToolChoiceType, ToolChoiceTypes, type ToolExecutionResult, type ToolHandler, ToolRegistry, type ToolType, ToolTypes, type TraceCallbacks, TransportError, type TransportErrorKind, type Usage, type UsageSummary, type WebSearchConfig, type XSearchConfig, type ZodLikeSchema, assistantMessageWithToolCalls, createFunctionTool, createFunctionToolFromSchema, createRetryMessages, createWebSearchTool, executeWithRetry, firstToolCall, formatToolErrorForModel, getRetryableErrors, hasRetryableErrors, hasToolCalls, isPublishableKey, mergeMetrics, mergeTrace, modelToString, normalizeModelId, normalizeProvider, normalizeStopReason, parseErrorResponse, parseToolArgs, parseToolArgsRaw, providerToString, respondToToolCall, stopReasonToString, toolChoiceAuto, toolChoiceNone, toolChoiceRequired, toolResultMessage, tryParseToolArgs, zodToJsonSchema };