@openrouter/sdk 0.0.1-beta.14 → 0.0.1-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,29 +1,14 @@
1
+ ![hero illustration](./assets/banner.png)
2
+
1
3
  # OpenRouter SDK (Beta)
2
4
 
3
- The [OpenRouter](https://openrouter.ai/) SDK gives access to over 300 large language models on the OpenRouter chat and completion APIs, as well as the rest of our full API. For more information about the API: [OpenRouter Documentation](https://openrouter.ai/docs)
5
+ The [OpenRouter SDK](https://openrouter.ai/docs/sdks/typescript) is a TypeScript toolkit designed to help you build AI-powered features and solutions in any JS or TS based runtime. Giving you easy access to over 300 models across providers in an easy and type-safe way.
4
6
 
5
- <!-- No Summary [summary] -->
7
+ To learn more about how to use the OpenRouter SDK, check out our [API Reference](https://openrouter.ai/docs/sdks/typescript/reference) and [Documentation](https://openrouter.ai/docs/sdks/typescript).
6
8
 
7
- <!-- Start Table of Contents [toc] -->
8
- ## Table of Contents
9
- <!-- $toc-max-depth=2 -->
10
- * [OpenRouter SDK (Beta)](#openrouter-sdk-beta)
11
- * [SDK Installation](#sdk-installation)
12
- * [Requirements](#requirements)
13
- * [SDK Example Usage](#sdk-example-usage)
14
- * [Authentication](#authentication)
15
- * [Available Resources and Operations](#available-resources-and-operations)
16
- * [Standalone functions](#standalone-functions)
17
- * [React hooks with TanStack Query](#react-hooks-with-tanstack-query)
18
- * [Server-sent event streaming](#server-sent-event-streaming)
19
- * [Retries](#retries)
20
- * [Error Handling](#error-handling)
21
- * [Debugging](#debugging)
22
- * [Development](#development)
23
- * [Maturity](#maturity)
24
- * [Contributions](#contributions)
9
+ <!-- No Summary [summary] -->
25
10
 
26
- <!-- End Table of Contents [toc] -->
11
+ <!-- No Table of Contents [toc] -->
27
12
 
28
13
  <!-- Start SDK Installation [installation] -->
29
14
  ## SDK Installation
@@ -73,1067 +58,48 @@ yarn add @tanstack/react-query react react-dom
73
58
  For supported JavaScript runtimes, please consult [RUNTIMES.md](RUNTIMES.md).
74
59
  <!-- End Requirements [requirements] -->
75
60
 
76
- <!-- Start SDK Example Usage [usage] -->
77
- ## SDK Example Usage
78
-
79
- ### Example
80
-
81
- ```typescript
82
- import { OpenRouter } from "@openrouter/sdk";
83
-
84
- const openRouter = new OpenRouter({
85
- apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
86
- });
87
-
88
- async function run() {
89
- const result = await openRouter.beta.responses.send({
90
- input: [
91
- {
92
- type: "message",
93
- role: "user",
94
- content: "Hello, how are you?",
95
- },
96
- ],
97
- instructions: "<value>",
98
- metadata: {
99
- "user_id": "123",
100
- "session_id": "abc-def-ghi",
101
- },
102
- tools: [
103
- {
104
- type: "function",
105
- name: "get_current_weather",
106
- description: "Get the current weather in a given location",
107
- strict: true,
108
- parameters: {
109
- "type": "object",
110
- "properties": {
111
- "location": {
112
- "type": "string",
113
- },
114
- },
115
- },
116
- },
117
- ],
118
- toolChoice: {
119
- type: "function",
120
- name: "<value>",
121
- },
122
- parallelToolCalls: true,
123
- model: "anthropic/claude-4.5-sonnet-20250929",
124
- models: [
125
- "<value 1>",
126
- ],
127
- text: {
128
- format: {
129
- type: "text",
130
- },
131
- verbosity: "medium",
132
- },
133
- reasoning: {
134
- effort: "high",
135
- summary: "auto",
136
- maxTokens: 8661.16,
137
- enabled: true,
138
- },
139
- maxOutputTokens: null,
140
- temperature: 0.7,
141
- topP: 0.9,
142
- topK: 193.77,
143
- promptCacheKey: "<value>",
144
- previousResponseId: "<id>",
145
- prompt: {
146
- id: "<id>",
147
- variables: {
148
- "key": {
149
- type: "input_text",
150
- text: "Hello, how can I help you?",
151
- },
152
- },
153
- },
154
- include: [
155
- "reasoning.encrypted_content",
156
- ],
157
- background: true,
158
- safetyIdentifier: "<value>",
159
- store: true,
160
- serviceTier: "auto",
161
- truncation: "auto",
162
- provider: {
163
- allowFallbacks: null,
164
- requireParameters: true,
165
- dataCollection: "deny",
166
- zdr: true,
167
- order: [
168
- "OpenAI",
169
- ],
170
- only: [
171
- "OpenAI",
172
- ],
173
- ignore: null,
174
- quantizations: [
175
- "fp16",
176
- ],
177
- sort: "price",
178
- maxPrice: {
179
- prompt: "1000",
180
- completion: 1000,
181
- image: 1000,
182
- audio: "1000",
183
- request: 1000,
184
- },
185
- experimental: {},
186
- },
187
- plugins: [
188
- {
189
- id: "file-parser",
190
- maxFiles: 4870.55,
191
- pdf: {
192
- engine: "mistral-ocr",
193
- },
194
- },
195
- ],
196
- user: "Elmer_Yundt72",
197
- });
198
-
199
- console.log(result);
200
- }
201
-
202
- run();
203
-
204
- ```
205
- <!-- End SDK Example Usage [usage] -->
206
-
207
- <!-- Start Authentication [security] -->
208
- ## Authentication
209
-
210
- ### Per-Client Security Schemes
211
-
212
- This SDK supports the following security scheme globally:
213
-
214
- | Name | Type | Scheme | Environment Variable |
215
- | -------- | ---- | ----------- | -------------------- |
216
- | `apiKey` | http | HTTP Bearer | `OPENROUTER_API_KEY` |
217
-
218
- To authenticate with the API the `apiKey` parameter must be set when initializing the SDK client instance. For example:
219
- ```typescript
220
- import { OpenRouter } from "@openrouter/sdk";
221
-
222
- const openRouter = new OpenRouter({
223
- apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
224
- });
225
-
226
- async function run() {
227
- const result = await openRouter.beta.responses.send({
228
- input: [
229
- {
230
- type: "message",
231
- role: "user",
232
- content: "Hello, how are you?",
233
- },
234
- ],
235
- instructions: "<value>",
236
- metadata: {
237
- "user_id": "123",
238
- "session_id": "abc-def-ghi",
239
- },
240
- tools: [
241
- {
242
- type: "function",
243
- name: "get_current_weather",
244
- description: "Get the current weather in a given location",
245
- strict: true,
246
- parameters: {
247
- "type": "object",
248
- "properties": {
249
- "location": {
250
- "type": "string",
251
- },
252
- },
253
- },
254
- },
255
- ],
256
- toolChoice: {
257
- type: "function",
258
- name: "<value>",
259
- },
260
- parallelToolCalls: true,
261
- model: "anthropic/claude-4.5-sonnet-20250929",
262
- models: [
263
- "<value 1>",
264
- ],
265
- text: {
266
- format: {
267
- type: "text",
268
- },
269
- verbosity: "medium",
270
- },
271
- reasoning: {
272
- effort: "high",
273
- summary: "auto",
274
- maxTokens: 8661.16,
275
- enabled: true,
276
- },
277
- maxOutputTokens: null,
278
- temperature: 0.7,
279
- topP: 0.9,
280
- topK: 193.77,
281
- promptCacheKey: "<value>",
282
- previousResponseId: "<id>",
283
- prompt: {
284
- id: "<id>",
285
- variables: {
286
- "key": {
287
- type: "input_text",
288
- text: "Hello, how can I help you?",
289
- },
290
- },
291
- },
292
- include: [
293
- "reasoning.encrypted_content",
294
- ],
295
- background: true,
296
- safetyIdentifier: "<value>",
297
- store: true,
298
- serviceTier: "auto",
299
- truncation: "auto",
300
- provider: {
301
- allowFallbacks: null,
302
- requireParameters: true,
303
- dataCollection: "deny",
304
- zdr: true,
305
- order: [
306
- "OpenAI",
307
- ],
308
- only: [
309
- "OpenAI",
310
- ],
311
- ignore: null,
312
- quantizations: [
313
- "fp16",
314
- ],
315
- sort: "price",
316
- maxPrice: {
317
- prompt: "1000",
318
- completion: 1000,
319
- image: 1000,
320
- audio: "1000",
321
- request: 1000,
322
- },
323
- experimental: {},
324
- },
325
- plugins: [
326
- {
327
- id: "file-parser",
328
- maxFiles: 4870.55,
329
- pdf: {
330
- engine: "mistral-ocr",
331
- },
332
- },
333
- ],
334
- user: "Elmer_Yundt72",
335
- });
336
-
337
- console.log(result);
338
- }
339
-
340
- run();
341
-
342
- ```
343
-
344
- ### Per-Operation Security Schemes
61
+ <!-- No SDK Example Usage [usage] -->
62
+ ## SDK Usage
345
63
 
346
- Some operations in this SDK require the security scheme to be specified at the request level. For example:
347
64
  ```typescript
348
65
  import { OpenRouter } from "@openrouter/sdk";
349
66
 
350
67
  const openRouter = new OpenRouter();
351
68
 
352
- async function run() {
353
- const result = await openRouter.credits.createCoinbaseCharge({
354
- bearer: process.env["OPENROUTER_BEARER"] ?? "",
355
- }, {
356
- amount: 100,
357
- sender: "0x1234567890123456789012345678901234567890",
358
- chainId: 1,
359
- });
360
-
361
- console.log(result);
362
- }
363
-
364
- run();
365
-
366
- ```
367
- <!-- End Authentication [security] -->
368
-
369
- <!-- Start Available Resources and Operations [operations] -->
370
- ## Available Resources and Operations
371
-
372
- <details open>
373
- <summary>Available methods</summary>
374
-
375
- ### [analytics](docs/sdks/analytics/README.md)
376
-
377
- * [getUserActivity](docs/sdks/analytics/README.md#getuseractivity) - Get user activity grouped by endpoint
378
-
379
- ### [apiKeys](docs/sdks/apikeys/README.md)
380
-
381
- * [list](docs/sdks/apikeys/README.md#list) - List API keys
382
- * [create](docs/sdks/apikeys/README.md#create) - Create a new API key
383
- * [update](docs/sdks/apikeys/README.md#update) - Update an API key
384
- * [delete](docs/sdks/apikeys/README.md#delete) - Delete an API key
385
- * [get](docs/sdks/apikeys/README.md#get) - Get a single API key
386
- * [getCurrentKeyMetadata](docs/sdks/apikeys/README.md#getcurrentkeymetadata) - Get current API key
387
-
388
- #### [beta.responses](docs/sdks/responses/README.md)
389
-
390
- * [send](docs/sdks/responses/README.md#send) - Create a response
391
-
392
- ### [chat](docs/sdks/chat/README.md)
393
-
394
- * [send](docs/sdks/chat/README.md#send) - Create a chat completion
395
-
396
- ### [completions](docs/sdks/completions/README.md)
397
-
398
- * [generate](docs/sdks/completions/README.md#generate) - Create a completion
399
-
400
- ### [credits](docs/sdks/credits/README.md)
401
-
402
- * [getCredits](docs/sdks/credits/README.md#getcredits) - Get remaining credits
403
- * [createCoinbaseCharge](docs/sdks/credits/README.md#createcoinbasecharge) - Create a Coinbase charge for crypto payment
404
-
405
- ### [endpoints](docs/sdks/endpoints/README.md)
406
-
407
- * [list](docs/sdks/endpoints/README.md#list) - List all endpoints for a model
408
- * [listZdrEndpoints](docs/sdks/endpoints/README.md#listzdrendpoints) - Preview the impact of ZDR on the available endpoints
409
-
410
- ### [generations](docs/sdks/generations/README.md)
411
-
412
- * [getGeneration](docs/sdks/generations/README.md#getgeneration) - Get request & usage metadata for a generation
413
-
414
- ### [models](docs/sdks/models/README.md)
415
-
416
- * [count](docs/sdks/models/README.md#count) - Get total count of available models
417
- * [list](docs/sdks/models/README.md#list) - List all models and their properties
418
- * [listForUser](docs/sdks/models/README.md#listforuser) - List models filtered by user provider preferences
419
-
420
- ### [oAuth](docs/sdks/oauth/README.md)
421
-
422
- * [exchangeAuthCodeForAPIKey](docs/sdks/oauth/README.md#exchangeauthcodeforapikey) - Exchange authorization code for API key
423
- * [createAuthCode](docs/sdks/oauth/README.md#createauthcode) - Create authorization code
424
-
425
- ### [parameters](docs/sdks/parameters/README.md)
426
-
427
- * [getParameters](docs/sdks/parameters/README.md#getparameters) - Get a model's supported parameters and data about which are most popular
428
-
429
- ### [providers](docs/sdks/providers/README.md)
430
-
431
- * [list](docs/sdks/providers/README.md#list) - List all providers
432
-
433
- </details>
434
- <!-- End Available Resources and Operations [operations] -->
435
-
436
- <!-- Start Standalone functions [standalone-funcs] -->
437
- ## Standalone functions
438
-
439
- All the methods listed above are available as standalone functions. These
440
- functions are ideal for use in applications running in the browser, serverless
441
- runtimes or other environments where application bundle size is a primary
442
- concern. When using a bundler to build your application, all unused
443
- functionality will be either excluded from the final bundle or tree-shaken away.
444
-
445
- To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md).
446
-
447
- <details>
448
-
449
- <summary>Available standalone functions</summary>
450
-
451
- - [`analyticsGetUserActivity`](docs/sdks/analytics/README.md#getuseractivity) - Get user activity grouped by endpoint
452
- - [`apiKeysCreate`](docs/sdks/apikeys/README.md#create) - Create a new API key
453
- - [`apiKeysDelete`](docs/sdks/apikeys/README.md#delete) - Delete an API key
454
- - [`apiKeysGet`](docs/sdks/apikeys/README.md#get) - Get a single API key
455
- - [`apiKeysGetCurrentKeyMetadata`](docs/sdks/apikeys/README.md#getcurrentkeymetadata) - Get current API key
456
- - [`apiKeysList`](docs/sdks/apikeys/README.md#list) - List API keys
457
- - [`apiKeysUpdate`](docs/sdks/apikeys/README.md#update) - Update an API key
458
- - [`betaResponsesSend`](docs/sdks/responses/README.md#send) - Create a response
459
- - [`chatSend`](docs/sdks/chat/README.md#send) - Create a chat completion
460
- - [`completionsGenerate`](docs/sdks/completions/README.md#generate) - Create a completion
461
- - [`creditsCreateCoinbaseCharge`](docs/sdks/credits/README.md#createcoinbasecharge) - Create a Coinbase charge for crypto payment
462
- - [`creditsGetCredits`](docs/sdks/credits/README.md#getcredits) - Get remaining credits
463
- - [`endpointsList`](docs/sdks/endpoints/README.md#list) - List all endpoints for a model
464
- - [`endpointsListZdrEndpoints`](docs/sdks/endpoints/README.md#listzdrendpoints) - Preview the impact of ZDR on the available endpoints
465
- - [`generationsGetGeneration`](docs/sdks/generations/README.md#getgeneration) - Get request & usage metadata for a generation
466
- - [`modelsCount`](docs/sdks/models/README.md#count) - Get total count of available models
467
- - [`modelsList`](docs/sdks/models/README.md#list) - List all models and their properties
468
- - [`modelsListForUser`](docs/sdks/models/README.md#listforuser) - List models filtered by user provider preferences
469
- - [`oAuthCreateAuthCode`](docs/sdks/oauth/README.md#createauthcode) - Create authorization code
470
- - [`oAuthExchangeAuthCodeForAPIKey`](docs/sdks/oauth/README.md#exchangeauthcodeforapikey) - Exchange authorization code for API key
471
- - [`parametersGetParameters`](docs/sdks/parameters/README.md#getparameters) - Get a model's supported parameters and data about which are most popular
472
- - [`providersList`](docs/sdks/providers/README.md#list) - List all providers
473
-
474
- </details>
475
- <!-- End Standalone functions [standalone-funcs] -->
476
-
477
- <!-- Start React hooks with TanStack Query [react-query] -->
478
- ## React hooks with TanStack Query
479
-
480
- React hooks built on [TanStack Query][tanstack-query] are included in this SDK.
481
- These hooks and the utility functions provided alongside them can be used to
482
- build rich applications that pull data from the API using one of the most
483
- popular asynchronous state management library.
484
-
485
- [tanstack-query]: https://tanstack.com/query/v5/docs/framework/react/overview
486
-
487
- To learn about this feature and how to get started, check
488
- [REACT_QUERY.md](./REACT_QUERY.md).
489
-
490
- > [!WARNING]
491
- >
492
- > This feature is currently in **preview** and is subject to breaking changes
493
- > within the current major version of the SDK as we gather user feedback on it.
494
-
495
- <details>
496
-
497
- <summary>Available React hooks</summary>
498
-
499
- - [`useAnalyticsGetUserActivity`](docs/sdks/analytics/README.md#getuseractivity) - Get user activity grouped by endpoint
500
- - [`useApiKeysCreateMutation`](docs/sdks/apikeys/README.md#create) - Create a new API key
501
- - [`useApiKeysDeleteMutation`](docs/sdks/apikeys/README.md#delete) - Delete an API key
502
- - [`useApiKeysGet`](docs/sdks/apikeys/README.md#get) - Get a single API key
503
- - [`useApiKeysGetCurrentKeyMetadata`](docs/sdks/apikeys/README.md#getcurrentkeymetadata) - Get current API key
504
- - [`useApiKeysList`](docs/sdks/apikeys/README.md#list) - List API keys
505
- - [`useApiKeysUpdateMutation`](docs/sdks/apikeys/README.md#update) - Update an API key
506
- - [`useBetaResponsesSendMutation`](docs/sdks/responses/README.md#send) - Create a response
507
- - [`useChatSendMutation`](docs/sdks/chat/README.md#send) - Create a chat completion
508
- - [`useCompletionsGenerateMutation`](docs/sdks/completions/README.md#generate) - Create a completion
509
- - [`useCreditsCreateCoinbaseChargeMutation`](docs/sdks/credits/README.md#createcoinbasecharge) - Create a Coinbase charge for crypto payment
510
- - [`useCreditsGetCredits`](docs/sdks/credits/README.md#getcredits) - Get remaining credits
511
- - [`useEndpointsList`](docs/sdks/endpoints/README.md#list) - List all endpoints for a model
512
- - [`useEndpointsListZdrEndpoints`](docs/sdks/endpoints/README.md#listzdrendpoints) - Preview the impact of ZDR on the available endpoints
513
- - [`useGenerationsGetGeneration`](docs/sdks/generations/README.md#getgeneration) - Get request & usage metadata for a generation
514
- - [`useModelsCount`](docs/sdks/models/README.md#count) - Get total count of available models
515
- - [`useModelsList`](docs/sdks/models/README.md#list) - List all models and their properties
516
- - [`useModelsListForUser`](docs/sdks/models/README.md#listforuser) - List models filtered by user provider preferences
517
- - [`useOAuthCreateAuthCodeMutation`](docs/sdks/oauth/README.md#createauthcode) - Create authorization code
518
- - [`useOAuthExchangeAuthCodeForAPIKeyMutation`](docs/sdks/oauth/README.md#exchangeauthcodeforapikey) - Exchange authorization code for API key
519
- - [`useParametersGetParameters`](docs/sdks/parameters/README.md#getparameters) - Get a model's supported parameters and data about which are most popular
520
- - [`useProvidersList`](docs/sdks/providers/README.md#list) - List all providers
521
-
522
- </details>
523
- <!-- End React hooks with TanStack Query [react-query] -->
524
-
525
- <!-- Start Server-sent event streaming [eventstream] -->
526
- ## Server-sent event streaming
527
-
528
- [Server-sent events][mdn-sse] are used to stream content from certain
529
- operations. These operations will expose the stream as an async iterable that
530
- can be consumed using a [`for await...of`][mdn-for-await-of] loop. The loop will
531
- terminate when the server no longer has any events to send and closes the
532
- underlying connection.
533
-
534
- ```typescript
535
- import { OpenRouter } from "@openrouter/sdk";
536
-
537
- const openRouter = new OpenRouter({
538
- apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
539
- });
540
-
541
- async function run() {
542
- const result = await openRouter.beta.responses.send({
543
- input: [
544
- {
545
- type: "message",
546
- role: "user",
547
- content: "Hello, how are you?",
548
- },
549
- ],
550
- instructions: "<value>",
551
- metadata: {
552
- "user_id": "123",
553
- "session_id": "abc-def-ghi",
554
- },
555
- tools: [
556
- {
557
- type: "function",
558
- name: "get_current_weather",
559
- description: "Get the current weather in a given location",
560
- strict: true,
561
- parameters: {
562
- "type": "object",
563
- "properties": {
564
- "location": {
565
- "type": "string",
566
- },
567
- },
568
- },
569
- },
570
- ],
571
- toolChoice: {
572
- type: "function",
573
- name: "<value>",
574
- },
575
- parallelToolCalls: true,
576
- model: "anthropic/claude-4.5-sonnet-20250929",
577
- models: [
578
- "<value 1>",
579
- ],
580
- text: {
581
- format: {
582
- type: "text",
583
- },
584
- verbosity: "medium",
585
- },
586
- reasoning: {
587
- effort: "high",
588
- summary: "auto",
589
- maxTokens: 8661.16,
590
- enabled: true,
591
- },
592
- maxOutputTokens: null,
593
- temperature: 0.7,
594
- topP: 0.9,
595
- topK: 193.77,
596
- promptCacheKey: "<value>",
597
- previousResponseId: "<id>",
598
- prompt: {
599
- id: "<id>",
600
- variables: {
601
- "key": {
602
- type: "input_text",
603
- text: "Hello, how can I help you?",
604
- },
605
- },
606
- },
607
- include: [
608
- "reasoning.encrypted_content",
609
- ],
610
- background: true,
611
- safetyIdentifier: "<value>",
612
- store: true,
613
- serviceTier: "auto",
614
- truncation: "auto",
615
- provider: {
616
- allowFallbacks: null,
617
- requireParameters: true,
618
- dataCollection: "deny",
619
- zdr: true,
620
- order: [
621
- "OpenAI",
622
- ],
623
- only: [
624
- "OpenAI",
625
- ],
626
- ignore: null,
627
- quantizations: [
628
- "fp16",
629
- ],
630
- sort: "price",
631
- maxPrice: {
632
- prompt: "1000",
633
- completion: 1000,
634
- image: 1000,
635
- audio: "1000",
636
- request: 1000,
637
- },
638
- experimental: {},
639
- },
640
- plugins: [
641
- {
642
- id: "file-parser",
643
- maxFiles: 4870.55,
644
- pdf: {
645
- engine: "mistral-ocr",
646
- },
647
- },
648
- ],
649
- user: "Elmer_Yundt72",
650
- });
651
-
652
- console.log(result);
653
- }
654
-
655
- run();
656
-
657
- ```
658
-
659
- [mdn-sse]: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
660
- [mdn-for-await-of]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
661
- <!-- End Server-sent event streaming [eventstream] -->
662
-
663
- <!-- Start Retries [retries] -->
664
- ## Retries
665
-
666
- Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
667
-
668
- To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
669
- ```typescript
670
- import { OpenRouter } from "@openrouter/sdk";
671
-
672
- const openRouter = new OpenRouter({
673
- apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
674
- });
675
-
676
- async function run() {
677
- const result = await openRouter.beta.responses.send({
678
- input: [
679
- {
680
- type: "message",
681
- role: "user",
682
- content: "Hello, how are you?",
683
- },
684
- ],
685
- instructions: "<value>",
686
- metadata: {
687
- "user_id": "123",
688
- "session_id": "abc-def-ghi",
689
- },
690
- tools: [
691
- {
692
- type: "function",
693
- name: "get_current_weather",
694
- description: "Get the current weather in a given location",
695
- strict: true,
696
- parameters: {
697
- "type": "object",
698
- "properties": {
699
- "location": {
700
- "type": "string",
701
- },
702
- },
703
- },
704
- },
705
- ],
706
- toolChoice: {
707
- type: "function",
708
- name: "<value>",
709
- },
710
- parallelToolCalls: true,
711
- model: "anthropic/claude-4.5-sonnet-20250929",
712
- models: [
713
- "<value 1>",
714
- ],
715
- text: {
716
- format: {
717
- type: "text",
718
- },
719
- verbosity: "medium",
720
- },
721
- reasoning: {
722
- effort: "high",
723
- summary: "auto",
724
- maxTokens: 8661.16,
725
- enabled: true,
726
- },
727
- maxOutputTokens: null,
728
- temperature: 0.7,
729
- topP: 0.9,
730
- topK: 193.77,
731
- promptCacheKey: "<value>",
732
- previousResponseId: "<id>",
733
- prompt: {
734
- id: "<id>",
735
- variables: {
736
- "key": {
737
- type: "input_text",
738
- text: "Hello, how can I help you?",
739
- },
740
- },
741
- },
742
- include: [
743
- "reasoning.encrypted_content",
744
- ],
745
- background: true,
746
- safetyIdentifier: "<value>",
747
- store: true,
748
- serviceTier: "auto",
749
- truncation: "auto",
750
- provider: {
751
- allowFallbacks: null,
752
- requireParameters: true,
753
- dataCollection: "deny",
754
- zdr: true,
755
- order: [
756
- "OpenAI",
757
- ],
758
- only: [
759
- "OpenAI",
760
- ],
761
- ignore: null,
762
- quantizations: [
763
- "fp16",
764
- ],
765
- sort: "price",
766
- maxPrice: {
767
- prompt: "1000",
768
- completion: 1000,
769
- image: 1000,
770
- audio: "1000",
771
- request: 1000,
772
- },
773
- experimental: {},
774
- },
775
- plugins: [
776
- {
777
- id: "file-parser",
778
- maxFiles: 4870.55,
779
- pdf: {
780
- engine: "mistral-ocr",
781
- },
782
- },
783
- ],
784
- user: "Elmer_Yundt72",
785
- }, {
786
- retries: {
787
- strategy: "backoff",
788
- backoff: {
789
- initialInterval: 1,
790
- maxInterval: 50,
791
- exponent: 1.1,
792
- maxElapsedTime: 100,
793
- },
794
- retryConnectionErrors: false,
795
- },
796
- });
797
-
798
- console.log(result);
799
- }
800
-
801
- run();
802
-
803
- ```
804
-
805
- If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
806
- ```typescript
807
- import { OpenRouter } from "@openrouter/sdk";
808
-
809
- const openRouter = new OpenRouter({
810
- retryConfig: {
811
- strategy: "backoff",
812
- backoff: {
813
- initialInterval: 1,
814
- maxInterval: 50,
815
- exponent: 1.1,
816
- maxElapsedTime: 100,
817
- },
818
- retryConnectionErrors: false,
69
+ const result = await openRouter.chat.send({
70
+ messages: [
71
+ {
72
+ role: "user",
73
+ content: "Hello, how are you?",
74
+ },
75
+ ],
76
+ model: "openai/gpt-5"
77
+ provider: {
78
+ zdr: true,
79
+ sort: "price",
819
80
  },
820
- apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
81
+ stream: true
821
82
  });
822
83
 
823
- async function run() {
824
- const result = await openRouter.beta.responses.send({
825
- input: [
826
- {
827
- type: "message",
828
- role: "user",
829
- content: "Hello, how are you?",
830
- },
831
- ],
832
- instructions: "<value>",
833
- metadata: {
834
- "user_id": "123",
835
- "session_id": "abc-def-ghi",
836
- },
837
- tools: [
838
- {
839
- type: "function",
840
- name: "get_current_weather",
841
- description: "Get the current weather in a given location",
842
- strict: true,
843
- parameters: {
844
- "type": "object",
845
- "properties": {
846
- "location": {
847
- "type": "string",
848
- },
849
- },
850
- },
851
- },
852
- ],
853
- toolChoice: {
854
- type: "function",
855
- name: "<value>",
856
- },
857
- parallelToolCalls: true,
858
- model: "anthropic/claude-4.5-sonnet-20250929",
859
- models: [
860
- "<value 1>",
861
- ],
862
- text: {
863
- format: {
864
- type: "text",
865
- },
866
- verbosity: "medium",
867
- },
868
- reasoning: {
869
- effort: "high",
870
- summary: "auto",
871
- maxTokens: 8661.16,
872
- enabled: true,
873
- },
874
- maxOutputTokens: null,
875
- temperature: 0.7,
876
- topP: 0.9,
877
- topK: 193.77,
878
- promptCacheKey: "<value>",
879
- previousResponseId: "<id>",
880
- prompt: {
881
- id: "<id>",
882
- variables: {
883
- "key": {
884
- type: "input_text",
885
- text: "Hello, how can I help you?",
886
- },
887
- },
888
- },
889
- include: [
890
- "reasoning.encrypted_content",
891
- ],
892
- background: true,
893
- safetyIdentifier: "<value>",
894
- store: true,
895
- serviceTier: "auto",
896
- truncation: "auto",
897
- provider: {
898
- allowFallbacks: null,
899
- requireParameters: true,
900
- dataCollection: "deny",
901
- zdr: true,
902
- order: [
903
- "OpenAI",
904
- ],
905
- only: [
906
- "OpenAI",
907
- ],
908
- ignore: null,
909
- quantizations: [
910
- "fp16",
911
- ],
912
- sort: "price",
913
- maxPrice: {
914
- prompt: "1000",
915
- completion: 1000,
916
- image: 1000,
917
- audio: "1000",
918
- request: 1000,
919
- },
920
- experimental: {},
921
- },
922
- plugins: [
923
- {
924
- id: "file-parser",
925
- maxFiles: 4870.55,
926
- pdf: {
927
- engine: "mistral-ocr",
928
- },
929
- },
930
- ],
931
- user: "Elmer_Yundt72",
932
- });
933
-
934
- console.log(result);
84
+ for await (const chunk of stream) {
85
+ console.log(hunk.choices[0].delta.content)
935
86
  }
936
87
 
937
- run();
938
-
939
88
  ```
940
- <!-- End Retries [retries] -->
941
89
 
942
- <!-- Start Error Handling [errors] -->
943
- ## Error Handling
90
+ <!-- No Authentication [security] -->
944
91
 
945
- [`OpenRouterError`](./src/models/errors/openroutererror.ts) is the base class for all HTTP error responses. It has the following properties:
92
+ <!-- No Available Resources and Operations [operations] -->
946
93
 
947
- | Property | Type | Description |
948
- | ------------------- | ---------- | --------------------------------------------------------------------------------------- |
949
- | `error.message` | `string` | Error message |
950
- | `error.statusCode` | `number` | HTTP response status code eg `404` |
951
- | `error.headers` | `Headers` | HTTP response headers |
952
- | `error.body` | `string` | HTTP body. Can be empty string if no body is returned. |
953
- | `error.rawResponse` | `Response` | Raw HTTP response |
954
- | `error.data$` | | Optional. Some errors may contain structured data. [See Error Classes](#error-classes). |
94
+ <!-- No Standalone functions [standalone-funcs] -->
955
95
 
956
- ### Example
957
- ```typescript
958
- import { OpenRouter } from "@openrouter/sdk";
959
- import * as errors from "@openrouter/sdk/models/errors";
960
-
961
- const openRouter = new OpenRouter({
962
- apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
963
- });
96
+ <!-- No React hooks with TanStack Query [react-query] -->
964
97
 
965
- async function run() {
966
- try {
967
- const result = await openRouter.beta.responses.send({
968
- input: [
969
- {
970
- type: "message",
971
- role: "user",
972
- content: "Hello, how are you?",
973
- },
974
- ],
975
- instructions: "<value>",
976
- metadata: {
977
- "user_id": "123",
978
- "session_id": "abc-def-ghi",
979
- },
980
- tools: [
981
- {
982
- type: "function",
983
- name: "get_current_weather",
984
- description: "Get the current weather in a given location",
985
- strict: true,
986
- parameters: {
987
- "type": "object",
988
- "properties": {
989
- "location": {
990
- "type": "string",
991
- },
992
- },
993
- },
994
- },
995
- ],
996
- toolChoice: {
997
- type: "function",
998
- name: "<value>",
999
- },
1000
- parallelToolCalls: true,
1001
- model: "anthropic/claude-4.5-sonnet-20250929",
1002
- models: [
1003
- "<value 1>",
1004
- ],
1005
- text: {
1006
- format: {
1007
- type: "text",
1008
- },
1009
- verbosity: "medium",
1010
- },
1011
- reasoning: {
1012
- effort: "high",
1013
- summary: "auto",
1014
- maxTokens: 8661.16,
1015
- enabled: true,
1016
- },
1017
- maxOutputTokens: null,
1018
- temperature: 0.7,
1019
- topP: 0.9,
1020
- topK: 193.77,
1021
- promptCacheKey: "<value>",
1022
- previousResponseId: "<id>",
1023
- prompt: {
1024
- id: "<id>",
1025
- variables: {
1026
- "key": {
1027
- type: "input_text",
1028
- text: "Hello, how can I help you?",
1029
- },
1030
- },
1031
- },
1032
- include: [
1033
- "reasoning.encrypted_content",
1034
- ],
1035
- background: true,
1036
- safetyIdentifier: "<value>",
1037
- store: true,
1038
- serviceTier: "auto",
1039
- truncation: "auto",
1040
- provider: {
1041
- allowFallbacks: null,
1042
- requireParameters: true,
1043
- dataCollection: "deny",
1044
- zdr: true,
1045
- order: [
1046
- "OpenAI",
1047
- ],
1048
- only: [
1049
- "OpenAI",
1050
- ],
1051
- ignore: null,
1052
- quantizations: [
1053
- "fp16",
1054
- ],
1055
- sort: "price",
1056
- maxPrice: {
1057
- prompt: "1000",
1058
- completion: 1000,
1059
- image: 1000,
1060
- audio: "1000",
1061
- request: 1000,
1062
- },
1063
- experimental: {},
1064
- },
1065
- plugins: [
1066
- {
1067
- id: "file-parser",
1068
- maxFiles: 4870.55,
1069
- pdf: {
1070
- engine: "mistral-ocr",
1071
- },
1072
- },
1073
- ],
1074
- user: "Elmer_Yundt72",
1075
- });
98
+ <!-- No Server-sent event streaming [eventstream] -->
1076
99
 
1077
- console.log(result);
1078
- } catch (error) {
1079
- // The base class for HTTP error responses
1080
- if (error instanceof errors.OpenRouterError) {
1081
- console.log(error.message);
1082
- console.log(error.statusCode);
1083
- console.log(error.body);
1084
- console.log(error.headers);
1085
-
1086
- // Depending on the method different errors may be thrown
1087
- if (error instanceof errors.BadRequestResponseError) {
1088
- console.log(error.data$.error); // models.BadRequestResponseErrorData
1089
- console.log(error.data$.userId); // string
1090
- }
1091
- }
1092
- }
1093
- }
100
+ <!-- No Retries [retries] -->
1094
101
 
1095
- run();
1096
-
1097
- ```
1098
-
1099
- ### Error Classes
1100
- **Primary errors:**
1101
- * [`OpenRouterError`](./src/models/errors/openroutererror.ts): The base class for HTTP error responses.
1102
- * [`InternalServerResponseError`](./src/models/errors/internalserverresponseerror.ts): Internal Server Error - Unexpected server error. Status code `500`. *
1103
-
1104
- <details><summary>Less common errors (20)</summary>
1105
-
1106
- <br />
1107
-
1108
- **Network errors:**
1109
- * [`ConnectionError`](./src/models/errors/httpclienterrors.ts): HTTP client was unable to make a request to a server.
1110
- * [`RequestTimeoutError`](./src/models/errors/httpclienterrors.ts): HTTP request timed out due to an AbortSignal signal.
1111
- * [`RequestAbortedError`](./src/models/errors/httpclienterrors.ts): HTTP request was aborted by the client.
1112
- * [`InvalidRequestError`](./src/models/errors/httpclienterrors.ts): Any input used to create a request is invalid.
1113
- * [`UnexpectedClientError`](./src/models/errors/httpclienterrors.ts): Unrecognised or unexpected error.
1114
-
1115
-
1116
- **Inherit from [`OpenRouterError`](./src/models/errors/openroutererror.ts)**:
1117
- * [`UnauthorizedResponseError`](./src/models/errors/unauthorizedresponseerror.ts): Unauthorized - Authentication required or invalid credentials. Status code `401`. Applicable to 14 of 22 methods.*
1118
- * [`BadRequestResponseError`](./src/models/errors/badrequestresponseerror.ts): Bad Request - Invalid request parameters or malformed input. Status code `400`. Applicable to 8 of 22 methods.*
1119
- * [`TooManyRequestsResponseError`](./src/models/errors/toomanyrequestsresponseerror.ts): Too Many Requests - Rate limit exceeded. Status code `429`. Applicable to 8 of 22 methods.*
1120
- * [`NotFoundResponseError`](./src/models/errors/notfoundresponseerror.ts): Not Found - Resource does not exist. Status code `404`. Applicable to 7 of 22 methods.*
1121
- * [`ForbiddenResponseError`](./src/models/errors/forbiddenresponseerror.ts): Forbidden - Authentication successful but insufficient permissions. Status code `403`. Applicable to 3 of 22 methods.*
1122
- * [`ChatError`](./src/models/errors/chaterror.ts): Bad request - invalid parameters. Applicable to 2 of 22 methods.*
1123
- * [`PaymentRequiredResponseError`](./src/models/errors/paymentrequiredresponseerror.ts): Payment Required - Insufficient credits or quota to complete request. Status code `402`. Applicable to 2 of 22 methods.*
1124
- * [`BadGatewayResponseError`](./src/models/errors/badgatewayresponseerror.ts): Bad Gateway - Provider/upstream API failure. Status code `502`. Applicable to 2 of 22 methods.*
1125
- * [`EdgeNetworkTimeoutResponseError`](./src/models/errors/edgenetworktimeoutresponseerror.ts): Infrastructure Timeout - Provider request timed out at edge network. Status code `524`. Applicable to 2 of 22 methods.*
1126
- * [`ProviderOverloadedResponseError`](./src/models/errors/provideroverloadedresponseerror.ts): Provider Overloaded - Provider is temporarily overloaded. Status code `529`. Applicable to 2 of 22 methods.*
1127
- * [`RequestTimeoutResponseError`](./src/models/errors/requesttimeoutresponseerror.ts): Request Timeout - Operation exceeded time limit. Status code `408`. Applicable to 1 of 22 methods.*
1128
- * [`PayloadTooLargeResponseError`](./src/models/errors/payloadtoolargeresponseerror.ts): Payload Too Large - Request payload exceeds size limits. Status code `413`. Applicable to 1 of 22 methods.*
1129
- * [`UnprocessableEntityResponseError`](./src/models/errors/unprocessableentityresponseerror.ts): Unprocessable Entity - Semantic validation failure. Status code `422`. Applicable to 1 of 22 methods.*
1130
- * [`ServiceUnavailableResponseError`](./src/models/errors/serviceunavailableresponseerror.ts): Service Unavailable - Service temporarily unavailable. Status code `503`. Applicable to 1 of 22 methods.*
1131
- * [`ResponseValidationError`](./src/models/errors/responsevalidationerror.ts): Type mismatch between the data returned from the server and the structure expected by the SDK. See `error.rawValue` for the raw value and `error.pretty()` for a nicely formatted multi-line string.
1132
-
1133
- </details>
1134
-
1135
- \* Check [the method documentation](#available-resources-and-operations) to see if the error is applicable.
1136
- <!-- End Error Handling [errors] -->
102
+ <!-- No Error Handling [errors] -->
1137
103
 
1138
104
  <!-- No Server Selection [server] -->
1139
105
 
@@ -1162,13 +128,32 @@ You can also enable a default debug logger by setting an environment variable `O
1162
128
 
1163
129
  # Development
1164
130
 
131
+ ## Running Tests
132
+
133
+ To run the test suite, you'll need to set up your environment with an OpenRouter API key.
134
+
135
+ ### Local Development
136
+
137
+ 1. Copy the example environment file:
138
+
139
+ ```bash
140
+ cp .env.example .env
141
+ ```
142
+
143
+ 2. Edit `.env` and add your OpenRouter API key:
144
+
145
+ ```bash
146
+ OPENROUTER_API_KEY=your_api_key_here
147
+ ```
148
+
149
+ 3. Run the tests:
150
+
151
+ ```bash
152
+ npx vitest
153
+ ```
154
+
1165
155
  ## Maturity
1166
156
 
1167
157
  This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage
1168
158
  to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally
1169
159
  looking for the latest version.
1170
-
1171
- ## Contributions
1172
-
1173
- While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation.
1174
- We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
@@ -37,8 +37,8 @@ export declare function serverURLFromOptions(options: SDKOptions): URL | null;
37
37
  export declare const SDK_METADATA: {
38
38
  readonly language: "typescript";
39
39
  readonly openapiDocVersion: "1.0.0";
40
- readonly sdkVersion: "0.0.1-beta.14";
41
- readonly genVersion: "2.731.4";
42
- readonly userAgent: "speakeasy-sdk/typescript 0.0.1-beta.14 2.731.4 1.0.0 @openrouter/sdk";
40
+ readonly sdkVersion: "0.0.1-beta.18";
41
+ readonly genVersion: "2.731.6";
42
+ readonly userAgent: "speakeasy-sdk/typescript 0.0.1-beta.18 2.731.6 1.0.0 @openrouter/sdk";
43
43
  };
44
44
  //# sourceMappingURL=config.d.ts.map
package/esm/lib/config.js CHANGED
@@ -25,8 +25,8 @@ export function serverURLFromOptions(options) {
25
25
  export const SDK_METADATA = {
26
26
  language: "typescript",
27
27
  openapiDocVersion: "1.0.0",
28
- sdkVersion: "0.0.1-beta.14",
29
- genVersion: "2.731.4",
30
- userAgent: "speakeasy-sdk/typescript 0.0.1-beta.14 2.731.4 1.0.0 @openrouter/sdk",
28
+ sdkVersion: "0.0.1-beta.18",
29
+ genVersion: "2.731.6",
30
+ userAgent: "speakeasy-sdk/typescript 0.0.1-beta.18 2.731.6 1.0.0 @openrouter/sdk",
31
31
  };
32
32
  //# sourceMappingURL=config.js.map
@@ -16,7 +16,7 @@ export type ChatGenerationTokenUsage = {
16
16
  promptTokens: number;
17
17
  totalTokens: number;
18
18
  completionTokensDetails?: CompletionTokensDetails | undefined;
19
- promptTokensDetails?: PromptTokensDetails | undefined;
19
+ promptTokensDetails?: PromptTokensDetails | null | undefined;
20
20
  };
21
21
  /** @internal */
22
22
  export declare const CompletionTokensDetails$inboundSchema: z.ZodType<CompletionTokensDetails, unknown>;
@@ -74,7 +74,7 @@ export type ChatGenerationTokenUsage$Outbound = {
74
74
  prompt_tokens: number;
75
75
  total_tokens: number;
76
76
  completion_tokens_details?: CompletionTokensDetails$Outbound | undefined;
77
- prompt_tokens_details?: PromptTokensDetails$Outbound | undefined;
77
+ prompt_tokens_details?: PromptTokensDetails$Outbound | null | undefined;
78
78
  };
79
79
  /** @internal */
80
80
  export declare const ChatGenerationTokenUsage$outboundSchema: z.ZodType<ChatGenerationTokenUsage$Outbound, ChatGenerationTokenUsage>;
@@ -93,8 +93,7 @@ export const ChatGenerationTokenUsage$inboundSchema = z.object({
93
93
  total_tokens: z.number(),
94
94
  completion_tokens_details: z.lazy(() => CompletionTokensDetails$inboundSchema)
95
95
  .optional(),
96
- prompt_tokens_details: z.lazy(() => PromptTokensDetails$inboundSchema)
97
- .optional(),
96
+ prompt_tokens_details: z.nullable(z.lazy(() => PromptTokensDetails$inboundSchema)).optional(),
98
97
  }).transform((v) => {
99
98
  return remap$(v, {
100
99
  "completion_tokens": "completionTokens",
@@ -111,8 +110,7 @@ export const ChatGenerationTokenUsage$outboundSchema = z.object({
111
110
  totalTokens: z.number(),
112
111
  completionTokensDetails: z.lazy(() => CompletionTokensDetails$outboundSchema)
113
112
  .optional(),
114
- promptTokensDetails: z.lazy(() => PromptTokensDetails$outboundSchema)
115
- .optional(),
113
+ promptTokensDetails: z.nullable(z.lazy(() => PromptTokensDetails$outboundSchema)).optional(),
116
114
  }).transform((v) => {
117
115
  return remap$(v, {
118
116
  completionTokens: "completion_tokens",
@@ -5,6 +5,7 @@ export declare const InputModality: {
5
5
  readonly Image: "image";
6
6
  readonly File: "file";
7
7
  readonly Audio: "audio";
8
+ readonly Video: "video";
8
9
  };
9
10
  export type InputModality = OpenEnum<typeof InputModality>;
10
11
  /** @internal */
@@ -8,6 +8,7 @@ export const InputModality = {
8
8
  Image: "image",
9
9
  File: "file",
10
10
  Audio: "audio",
11
+ Video: "video",
11
12
  };
12
13
  /** @internal */
13
14
  export const InputModality$inboundSchema = z
package/jsr.json CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  {
4
4
  "name": "@openrouter/sdk",
5
- "version": "0.0.1-beta.14",
5
+ "version": "0.0.1-beta.18",
6
6
  "exports": {
7
7
  ".": "./src/index.ts",
8
8
  "./models/errors": "./src/models/errors/index.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openrouter/sdk",
3
- "version": "0.0.1-beta.14",
3
+ "version": "0.0.1-beta.18",
4
4
  "author": "OpenRouter",
5
5
  "type": "module",
6
6
  "main": "./esm/index.js",
package/vitest.config.ts CHANGED
@@ -1,15 +1,23 @@
1
1
  import { config } from "dotenv";
2
2
  import { defineConfig } from "vitest/config";
3
+ import { fileURLToPath } from "url";
4
+ import { dirname, join } from "path";
3
5
 
4
- // Load environment variables from .env file
5
- config();
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = dirname(__filename);
8
+
9
+ // Load environment variables from .env file if it exists
10
+ // This will not override existing environment variables
11
+ config({ path: join(__dirname, ".env") });
6
12
 
7
13
  export default defineConfig({
8
14
  test: {
9
15
  globals: true,
10
16
  environment: "node",
17
+ // Don't override env vars - just let them pass through from the system
18
+ // The env object here will be merged with process.env
11
19
  env: {
12
- OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY || "",
20
+ OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY,
13
21
  },
14
22
  include: ["tests/**/*.test.ts"],
15
23
  hookTimeout: 30000,