@modelrelay/sdk 0.7.0 → 0.17.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.cts CHANGED
@@ -22,33 +22,8 @@ type KnownStopReason = (typeof StopReasons)[keyof typeof StopReasons];
22
22
  type StopReason = KnownStopReason | {
23
23
  other: string;
24
24
  };
25
- declare const Providers: {
26
- readonly OpenAI: "openai";
27
- readonly Anthropic: "anthropic";
28
- readonly Grok: "grok";
29
- readonly Echo: "echo";
30
- };
31
- type KnownProvider = (typeof Providers)[keyof typeof Providers];
32
- type ProviderId = KnownProvider | {
33
- other: string;
34
- };
35
- declare const Models: {
36
- readonly OpenAIGpt4o: "openai/gpt-4o";
37
- readonly OpenAIGpt4oMini: "openai/gpt-4o-mini";
38
- readonly OpenAIGpt51: "openai/gpt-5.1";
39
- readonly AnthropicClaude35HaikuLatest: "anthropic/claude-3-5-haiku-latest";
40
- readonly AnthropicClaude35SonnetLatest: "anthropic/claude-3-5-sonnet-latest";
41
- readonly AnthropicClaudeOpus45: "anthropic/claude-opus-4-5-20251101";
42
- readonly AnthropicClaude35Haiku: "anthropic/claude-3.5-haiku";
43
- readonly Grok2: "grok-2";
44
- readonly Grok4_1FastNonReasoning: "grok-4-1-fast-non-reasoning";
45
- readonly Grok4_1FastReasoning: "grok-4-1-fast-reasoning";
46
- readonly Echo1: "echo-1";
47
- };
48
- type KnownModel = (typeof Models)[keyof typeof Models];
49
- type ModelId = KnownModel | {
50
- other: string;
51
- } | string;
25
+ type ProviderId = string;
26
+ type ModelId = string;
52
27
  /**
53
28
  * Common configuration options for the ModelRelay client.
54
29
  */
@@ -238,6 +213,10 @@ interface Usage {
238
213
  outputTokens: number;
239
214
  totalTokens: number;
240
215
  }
216
+ /**
217
+ * Creates a Usage object with automatic totalTokens calculation if not provided.
218
+ */
219
+ declare function createUsage(inputTokens: number, outputTokens: number, totalTokens?: number): Usage;
241
220
  interface UsageSummary {
242
221
  plan: string;
243
222
  planType?: string;
@@ -265,11 +244,17 @@ interface ChatMessage {
265
244
  }
266
245
  declare const ToolTypes: {
267
246
  readonly Function: "function";
247
+ readonly Web: "web";
268
248
  readonly WebSearch: "web_search";
269
249
  readonly XSearch: "x_search";
270
250
  readonly CodeExecution: "code_execution";
271
251
  };
272
252
  type ToolType = (typeof ToolTypes)[keyof typeof ToolTypes];
253
+ declare const WebToolModes: {
254
+ readonly Search: "search";
255
+ readonly Browse: "browse";
256
+ };
257
+ type WebToolMode = (typeof WebToolModes)[keyof typeof WebToolModes];
273
258
  interface FunctionTool {
274
259
  name: string;
275
260
  description?: string;
@@ -279,6 +264,7 @@ interface WebSearchConfig {
279
264
  allowedDomains?: string[];
280
265
  excludedDomains?: string[];
281
266
  maxUses?: number;
267
+ mode?: string;
282
268
  }
283
269
  interface XSearchConfig {
284
270
  allowedHandles?: string[];
@@ -294,6 +280,8 @@ interface Tool {
294
280
  type: ToolType;
295
281
  function?: FunctionTool;
296
282
  webSearch?: WebSearchConfig;
283
+ /** Alias for webSearch - used in API normalization */
284
+ web?: WebSearchConfig;
297
285
  xSearch?: XSearchConfig;
298
286
  codeExecution?: CodeExecConfig;
299
287
  }
@@ -315,10 +303,25 @@ interface ToolCall {
315
303
  type: ToolType;
316
304
  function?: FunctionCall;
317
305
  }
306
+ declare const ResponseFormatTypes: {
307
+ readonly Text: "text";
308
+ readonly JsonObject: "json_object";
309
+ readonly JsonSchema: "json_schema";
310
+ };
311
+ type ResponseFormatType = (typeof ResponseFormatTypes)[keyof typeof ResponseFormatTypes];
312
+ interface ResponseJSONSchemaFormat {
313
+ name: string;
314
+ description?: string;
315
+ schema: Record<string, unknown>;
316
+ strict?: boolean;
317
+ }
318
+ interface ResponseFormat {
319
+ type: ResponseFormatType;
320
+ json_schema?: ResponseJSONSchemaFormat;
321
+ }
318
322
  interface ChatCompletionCreateParams {
319
323
  model: ModelId;
320
324
  messages: NonEmptyArray<ChatMessage>;
321
- provider?: ProviderId;
322
325
  maxTokens?: number;
323
326
  temperature?: number;
324
327
  metadata?: Record<string, string>;
@@ -336,6 +339,11 @@ interface ChatCompletionCreateParams {
336
339
  * When using publishable keys, a customer id is required to mint a frontend token.
337
340
  */
338
341
  customerId?: string;
342
+ /**
343
+ * Structured outputs configuration. When set with type `json_object` or
344
+ * `json_schema`, the backend validates and returns structured JSON.
345
+ */
346
+ responseFormat?: ResponseFormat;
339
347
  /**
340
348
  * Opt out of SSE streaming and request a blocking JSON response.
341
349
  */
@@ -347,7 +355,6 @@ interface ChatCompletionCreateParams {
347
355
  }
348
356
  interface ChatCompletionResponse {
349
357
  id: string;
350
- provider?: ProviderId;
351
358
  content: string[];
352
359
  stopReason?: StopReason;
353
360
  model?: ModelId;
@@ -374,7 +381,6 @@ type TransportErrorKind = "timeout" | "connect" | "request" | "other";
374
381
  interface RequestContext {
375
382
  method: string;
376
383
  path: string;
377
- provider?: ProviderId;
378
384
  model?: ModelId;
379
385
  requestId?: string;
380
386
  responseId?: string;
@@ -422,8 +428,6 @@ declare function mergeMetrics(base?: MetricsCallbacks, override?: MetricsCallbac
422
428
  declare function mergeTrace(base?: TraceCallbacks, override?: TraceCallbacks): TraceCallbacks | undefined;
423
429
  declare function normalizeStopReason(value?: unknown): StopReason | undefined;
424
430
  declare function stopReasonToString(value?: StopReason): string | undefined;
425
- declare function normalizeProvider(value?: unknown): ProviderId | undefined;
426
- declare function providerToString(value?: ProviderId): string | undefined;
427
431
  declare function normalizeModelId(value: unknown): ModelId | undefined;
428
432
  declare function modelToString(value: ModelId): string;
429
433
  type ChatEventType = "message_start" | "message_delta" | "message_stop" | "tool_use_start" | "tool_use_delta" | "tool_use_stop" | "ping" | "custom";
@@ -477,6 +481,12 @@ interface ChatCompletionEvent<T = unknown> {
477
481
  requestId?: string;
478
482
  raw: string;
479
483
  }
484
+ type StructuredJSONRecordType = "start" | "update" | "completion" | "error";
485
+ interface StructuredJSONEvent<T> {
486
+ type: "update" | "completion";
487
+ payload: T;
488
+ requestId?: string;
489
+ }
480
490
  interface APIFrontendToken {
481
491
  token: string;
482
492
  expires_at?: string;
@@ -507,7 +517,6 @@ interface APIChatUsage {
507
517
  }
508
518
  interface APIChatResponse {
509
519
  id?: string;
510
- provider?: string;
511
520
  content?: string | string[];
512
521
  stop_reason?: string;
513
522
  model?: string;
@@ -615,6 +624,14 @@ interface AuthHeaders {
615
624
  apiKey?: string;
616
625
  accessToken?: string;
617
626
  }
627
+ /**
628
+ * Creates AuthHeaders with an API key.
629
+ */
630
+ declare function createApiKeyAuth(apiKey: string): AuthHeaders;
631
+ /**
632
+ * Creates AuthHeaders with an access token.
633
+ */
634
+ declare function createAccessTokenAuth(accessToken: string): AuthHeaders;
618
635
  declare class AuthClient {
619
636
  private readonly http;
620
637
  private readonly apiKey?;
@@ -703,6 +720,13 @@ declare class ChatCompletionsClient {
703
720
  stream: false;
704
721
  }): Promise<ChatCompletionResponse>;
705
722
  create(params: ChatCompletionCreateParams, options?: ChatRequestOptions): Promise<ChatCompletionsStream>;
723
+ /**
724
+ * Stream structured JSON responses using the NDJSON contract defined for
725
+ * /llm/proxy. The request must include a structured responseFormat.
726
+ */
727
+ streamJSON<T>(params: ChatCompletionCreateParams & {
728
+ responseFormat: ResponseFormat;
729
+ }, options?: ChatRequestOptions): Promise<StructuredJSONStream<T>>;
706
730
  }
707
731
  declare class ChatCompletionsStream implements AsyncIterable<ChatCompletionEvent> {
708
732
  private readonly response;
@@ -720,6 +744,21 @@ declare class ChatCompletionsStream implements AsyncIterable<ChatCompletionEvent
720
744
  private enrichContext;
721
745
  private recordFirstToken;
722
746
  }
747
+ declare class StructuredJSONStream<T> implements AsyncIterable<StructuredJSONEvent<T>> {
748
+ private readonly response;
749
+ private readonly requestId?;
750
+ private context;
751
+ private readonly metrics?;
752
+ private readonly trace?;
753
+ private closed;
754
+ private sawTerminal;
755
+ constructor(response: Response, requestId: string | undefined, context: RequestContext, metrics?: MetricsCallbacks, trace?: TraceCallbacks);
756
+ cancel(reason?: unknown): Promise<void>;
757
+ [Symbol.asyncIterator](): AsyncIterator<StructuredJSONEvent<T>>;
758
+ collect(): Promise<T>;
759
+ private parseRecord;
760
+ private traceStructuredEvent;
761
+ }
723
762
 
724
763
  /**
725
764
  * Customer metadata as an arbitrary key-value object.
@@ -734,7 +773,7 @@ interface Customer {
734
773
  tier_id: string;
735
774
  tier_code?: string;
736
775
  external_id: string;
737
- email?: string;
776
+ email: string;
738
777
  metadata?: CustomerMetadata;
739
778
  stripe_customer_id?: string;
740
779
  stripe_subscription_id?: string;
@@ -750,7 +789,7 @@ interface Customer {
750
789
  interface CustomerCreateRequest {
751
790
  tier_id: string;
752
791
  external_id: string;
753
- email?: string;
792
+ email: string;
754
793
  metadata?: CustomerMetadata;
755
794
  }
756
795
  /**
@@ -759,9 +798,18 @@ interface CustomerCreateRequest {
759
798
  interface CustomerUpsertRequest {
760
799
  tier_id: string;
761
800
  external_id: string;
762
- email?: string;
801
+ email: string;
763
802
  metadata?: CustomerMetadata;
764
803
  }
804
+ /**
805
+ * Request to claim a customer by email, setting their external_id.
806
+ * Used when a customer subscribes via Stripe Checkout (email only) and later
807
+ * authenticates to the app, needing to link their identity.
808
+ */
809
+ interface CustomerClaimRequest {
810
+ email: string;
811
+ external_id: string;
812
+ }
765
813
  /**
766
814
  * Request to create a checkout session.
767
815
  */
@@ -816,6 +864,15 @@ declare class CustomersClient {
816
864
  * Otherwise, a new customer is created.
817
865
  */
818
866
  upsert(request: CustomerUpsertRequest): Promise<Customer>;
867
+ /**
868
+ * Claim a customer by email, setting their external_id.
869
+ * Used when a customer subscribes via Stripe Checkout (email only) and later
870
+ * authenticates to the app, needing to link their identity.
871
+ *
872
+ * @throws {APIError} with status 404 if customer not found by email
873
+ * @throws {APIError} with status 409 if customer already claimed or external_id in use
874
+ */
875
+ claim(request: CustomerClaimRequest): Promise<Customer>;
819
876
  /**
820
877
  * Delete a customer by ID.
821
878
  */
@@ -873,6 +930,24 @@ declare class TiersClient {
873
930
  get(tierId: string): Promise<Tier>;
874
931
  }
875
932
 
933
+ /**
934
+ * API error codes returned by the server.
935
+ * These constants can be used for programmatic error handling.
936
+ */
937
+ declare const ErrorCodes: {
938
+ readonly NOT_FOUND: "NOT_FOUND";
939
+ readonly VALIDATION_ERROR: "VALIDATION_ERROR";
940
+ readonly RATE_LIMIT: "RATE_LIMIT";
941
+ readonly UNAUTHORIZED: "UNAUTHORIZED";
942
+ readonly FORBIDDEN: "FORBIDDEN";
943
+ readonly CONFLICT: "CONFLICT";
944
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
945
+ readonly SERVICE_UNAVAILABLE: "SERVICE_UNAVAILABLE";
946
+ readonly INVALID_INPUT: "INVALID_INPUT";
947
+ readonly PAYMENT_REQUIRED: "PAYMENT_REQUIRED";
948
+ readonly METHOD_NOT_ALLOWED: "METHOD_NOT_ALLOWED";
949
+ };
950
+ type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
876
951
  type ErrorCategory = "config" | "transport" | "api";
877
952
  declare class ModelRelayError extends Error {
878
953
  category: ErrorCategory;
@@ -914,9 +989,41 @@ declare class APIError extends ModelRelayError {
914
989
  data?: unknown;
915
990
  retries?: RetryMetadata;
916
991
  });
992
+ /** Returns true if the error is a not found error. */
993
+ isNotFound(): boolean;
994
+ /** Returns true if the error is a validation error. */
995
+ isValidation(): boolean;
996
+ /** Returns true if the error is a rate limit error. */
997
+ isRateLimit(): boolean;
998
+ /** Returns true if the error is an unauthorized error. */
999
+ isUnauthorized(): boolean;
1000
+ /** Returns true if the error is a forbidden error. */
1001
+ isForbidden(): boolean;
1002
+ /** Returns true if the error is a service unavailable error. */
1003
+ isUnavailable(): boolean;
917
1004
  }
918
1005
  declare function parseErrorResponse(response: Response, retries?: RetryMetadata): Promise<APIError>;
919
1006
 
1007
+ /**
1008
+ * Creates a user message.
1009
+ */
1010
+ declare function createUserMessage(content: string): ChatMessage;
1011
+ /**
1012
+ * Creates an assistant message.
1013
+ */
1014
+ declare function createAssistantMessage(content: string): ChatMessage;
1015
+ /**
1016
+ * Creates a system message.
1017
+ */
1018
+ declare function createSystemMessage(content: string): ChatMessage;
1019
+ /**
1020
+ * Creates a tool call object.
1021
+ */
1022
+ declare function createToolCall(id: string, name: string, args: string, type?: ToolType): ToolCall;
1023
+ /**
1024
+ * Creates a function call object.
1025
+ */
1026
+ declare function createFunctionCall(name: string, args: string): FunctionCall;
920
1027
  /**
921
1028
  * Interface for Zod-like schema types.
922
1029
  * Compatible with Zod's ZodType and similar libraries.
@@ -988,9 +1095,10 @@ declare function createFunctionToolFromSchema(name: string, description: string,
988
1095
  */
989
1096
  declare function createFunctionTool(name: string, description: string, parameters?: Record<string, unknown>): Tool;
990
1097
  /**
991
- * Creates a web search tool with optional domain filters.
1098
+ * Creates a web tool with optional domain filters and mode.
992
1099
  */
993
- declare function createWebSearchTool(options?: {
1100
+ declare function createWebTool(options?: {
1101
+ mode?: WebToolMode;
994
1102
  allowedDomains?: string[];
995
1103
  excludedDomains?: string[];
996
1104
  maxUses?: number;
@@ -1322,4 +1430,4 @@ declare class ModelRelay {
1322
1430
  constructor(options: ModelRelayOptions);
1323
1431
  }
1324
1432
 
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 };
1433
+ export { type APIChatResponse, type APIChatUsage, type APICheckoutSession, type APICustomerRef, APIError, type APIFrontendToken, type APIKey, AuthClient, type AuthHeaders, ChatClient, type ChatCompletionCreateParams, type ChatCompletionEvent, type ChatCompletionResponse, ChatCompletionsStream, type ChatEventType, type ChatMessage, type CheckoutSession, type CheckoutSessionRequest, type CodeExecConfig, ConfigError, type Customer, type CustomerClaimRequest, type CustomerCreateRequest, type CustomerMetadata, type CustomerUpsertRequest, CustomersClient, DEFAULT_BASE_URL, DEFAULT_CLIENT_HEADER, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, type ErrorCategory, type ErrorCode, ErrorCodes, type FieldError, type FrontendCustomer, type FrontendToken, type FrontendTokenRequest, type FunctionCall, type FunctionCallDelta, type FunctionTool, type HttpRequestMetrics, type JsonSchemaOptions, type KnownStopReason, type MessageDeltaData, type MessageStartData, type MessageStopData, type MetricsCallbacks, type ModelId, ModelRelay, type ModelRelayBaseOptions, ModelRelayError, type ModelRelayKeyOptions, type ModelRelayOptions, type ModelRelayOptionsLegacy, type ModelRelayTokenOptions, type NonEmptyArray, type PriceInterval, type Project, type ProviderId, type RequestContext, type ResponseFormat, type ResponseFormatType, ResponseFormatTypes, type ResponseJSONSchemaFormat, type RetryConfig, type RetryMetadata, type RetryOptions, SDK_VERSION, type Schema, type StopReason, StopReasons, type StreamFirstTokenMetrics, type StructuredJSONEvent, type StructuredJSONRecordType, StructuredJSONStream, 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 WebToolMode, WebToolModes, type XSearchConfig, type ZodLikeSchema, assistantMessageWithToolCalls, createAccessTokenAuth, createApiKeyAuth, createAssistantMessage, createFunctionCall, createFunctionTool, createFunctionToolFromSchema, createRetryMessages, createSystemMessage, createToolCall, createUsage, createUserMessage, createWebTool, executeWithRetry, firstToolCall, formatToolErrorForModel, getRetryableErrors, hasRetryableErrors, hasToolCalls, isPublishableKey, mergeMetrics, mergeTrace, modelToString, normalizeModelId, normalizeStopReason, parseErrorResponse, parseToolArgs, parseToolArgsRaw, respondToToolCall, stopReasonToString, toolChoiceAuto, toolChoiceNone, toolChoiceRequired, toolResultMessage, tryParseToolArgs, zodToJsonSchema };