-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathopenrouter.spec.ts
More file actions
827 lines (720 loc) · 25.2 KB
/
openrouter.spec.ts
File metadata and controls
827 lines (720 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
// pnpm --filter roo-cline test api/providers/__tests__/openrouter.spec.ts
vitest.mock("vscode", () => ({}))
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { OpenRouterHandler } from "../openrouter"
import { ApiHandlerOptions } from "../../../shared/api"
import { Package } from "../../../shared/package"
vitest.mock("openai")
vitest.mock("delay", () => ({ default: vitest.fn(() => Promise.resolve()) }))
const mockCaptureException = vitest.fn()
vitest.mock("@roo-code/telemetry", () => ({
TelemetryService: {
instance: {
captureException: (...args: unknown[]) => mockCaptureException(...args),
},
},
}))
vitest.mock("../fetchers/modelCache", () => ({
getModels: vitest.fn().mockImplementation(() => {
return Promise.resolve({
"anthropic/claude-sonnet-4": {
maxTokens: 8192,
contextWindow: 200000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 3,
outputPrice: 15,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description: "Claude 3.7 Sonnet",
thinking: false,
},
"anthropic/claude-sonnet-4.5": {
maxTokens: 8192,
contextWindow: 200000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 3,
outputPrice: 15,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description: "Claude 4.5 Sonnet",
thinking: false,
},
"anthropic/claude-3.7-sonnet:thinking": {
maxTokens: 128000,
contextWindow: 200000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 3,
outputPrice: 15,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description: "Claude 3.7 Sonnet with thinking",
},
"openai/gpt-4o": {
maxTokens: 16384,
contextWindow: 128000,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 2.5,
outputPrice: 10,
description: "GPT-4o",
},
"openai/o1": {
maxTokens: 100000,
contextWindow: 200000,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 15,
outputPrice: 60,
description: "OpenAI o1",
excludedTools: ["existing_excluded"],
includedTools: ["existing_included"],
},
"mistralai/devstral-2512": {
maxTokens: 16384,
contextWindow: 128000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.1,
outputPrice: 0.3,
description: "Devstral 2512",
},
})
}),
}))
describe("OpenRouterHandler", () => {
const mockOptions: ApiHandlerOptions = {
openRouterApiKey: "test-key",
openRouterModelId: "anthropic/claude-sonnet-4",
}
beforeEach(() => vitest.clearAllMocks())
it("initializes with correct options", () => {
const handler = new OpenRouterHandler(mockOptions)
expect(handler).toBeInstanceOf(OpenRouterHandler)
expect(OpenAI).toHaveBeenCalledWith({
baseURL: "https://openrouter.ai/api/v1",
apiKey: mockOptions.openRouterApiKey,
defaultHeaders: {
"HTTP-Referer": "https://github.com/RooVetGit/Roo-Cline",
"X-Title": "Roo Code",
"User-Agent": `RooCode/${Package.version}`,
},
})
})
describe("fetchModel", () => {
it("returns correct model info when options are provided", async () => {
const handler = new OpenRouterHandler(mockOptions)
const result = await handler.fetchModel()
expect(result).toMatchObject({
id: mockOptions.openRouterModelId,
maxTokens: 8192,
temperature: 0,
reasoningEffort: undefined,
topP: undefined,
})
})
it("returns default model info when options are not provided", async () => {
const handler = new OpenRouterHandler({})
const result = await handler.fetchModel()
expect(result.id).toBe("anthropic/claude-sonnet-4.5")
expect(result.info.supportsPromptCache).toBe(true)
})
it("honors custom maxTokens for thinking models", async () => {
const handler = new OpenRouterHandler({
openRouterApiKey: "test-key",
openRouterModelId: "anthropic/claude-3.7-sonnet:thinking",
modelMaxTokens: 32_768,
modelMaxThinkingTokens: 16_384,
})
const result = await handler.fetchModel()
// With the new clamping logic, 128000 tokens (64% of 200000 context window)
// gets clamped to 20% of context window: 200000 * 0.2 = 40000
expect(result.maxTokens).toBe(40000)
expect(result.reasoningBudget).toBeUndefined()
expect(result.temperature).toBe(0)
})
it("does not honor custom maxTokens for non-thinking models", async () => {
const handler = new OpenRouterHandler({
...mockOptions,
modelMaxTokens: 32_768,
modelMaxThinkingTokens: 16_384,
})
const result = await handler.fetchModel()
expect(result.maxTokens).toBe(8192)
expect(result.reasoningBudget).toBeUndefined()
expect(result.temperature).toBe(0)
})
it("adds excludedTools and includedTools for OpenAI models", async () => {
const handler = new OpenRouterHandler({
openRouterApiKey: "test-key",
openRouterModelId: "openai/gpt-4o",
})
const result = await handler.fetchModel()
expect(result.id).toBe("openai/gpt-4o")
expect(result.info.excludedTools).toContain("apply_diff")
expect(result.info.excludedTools).toContain("write_to_file")
expect(result.info.includedTools).toContain("apply_patch")
})
it("merges excludedTools and includedTools with existing values for OpenAI models", async () => {
const handler = new OpenRouterHandler({
openRouterApiKey: "test-key",
openRouterModelId: "openai/o1",
})
const result = await handler.fetchModel()
expect(result.id).toBe("openai/o1")
// Should have the new exclusions
expect(result.info.excludedTools).toContain("apply_diff")
expect(result.info.excludedTools).toContain("write_to_file")
// Should preserve existing exclusions
expect(result.info.excludedTools).toContain("existing_excluded")
// Should have the new inclusions
expect(result.info.includedTools).toContain("apply_patch")
// Should preserve existing inclusions
expect(result.info.includedTools).toContain("existing_included")
})
it("does not add excludedTools or includedTools for non-OpenAI models", async () => {
const handler = new OpenRouterHandler({
openRouterApiKey: "test-key",
openRouterModelId: "anthropic/claude-sonnet-4",
})
const result = await handler.fetchModel()
expect(result.id).toBe("anthropic/claude-sonnet-4")
// Should NOT have the tool exclusions/inclusions
expect(result.info.excludedTools).toBeUndefined()
expect(result.info.includedTools).toBeUndefined()
})
})
describe("createMessage", () => {
it("generates correct stream chunks", async () => {
const handler = new OpenRouterHandler(mockOptions)
const mockStream = {
async *[Symbol.asyncIterator]() {
yield {
id: mockOptions.openRouterModelId,
choices: [{ delta: { content: "test response" } }],
}
yield {
id: "test-id",
choices: [{ delta: {} }],
usage: { prompt_tokens: 10, completion_tokens: 20, cost: 0.001 },
}
},
}
// Mock OpenAI chat.completions.create
const mockCreate = vitest.fn().mockResolvedValue(mockStream)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const systemPrompt = "test system prompt"
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user" as const, content: "test message" }]
const generator = handler.createMessage(systemPrompt, messages)
const chunks = []
for await (const chunk of generator) {
chunks.push(chunk)
}
// Verify stream chunks
expect(chunks).toHaveLength(2) // One text chunk and one usage chunk
expect(chunks[0]).toEqual({ type: "text", text: "test response" })
expect(chunks[1]).toEqual({ type: "usage", inputTokens: 10, outputTokens: 20, totalCost: 0.001 })
// Verify OpenAI client was called with correct parameters.
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
max_tokens: 8192,
messages: [
{
content: [
{ cache_control: { type: "ephemeral" }, text: "test system prompt", type: "text" },
],
role: "system",
},
{
content: [{ cache_control: { type: "ephemeral" }, text: "test message", type: "text" }],
role: "user",
},
],
model: "anthropic/claude-sonnet-4",
stream: true,
stream_options: { include_usage: true },
temperature: 0,
top_p: undefined,
}),
{ headers: { "x-anthropic-beta": "fine-grained-tool-streaming-2025-05-14" } },
)
})
it("adds cache control for supported models", async () => {
const handler = new OpenRouterHandler({
...mockOptions,
openRouterModelId: "anthropic/claude-3.5-sonnet",
})
const mockStream = {
async *[Symbol.asyncIterator]() {
yield {
id: "test-id",
choices: [{ delta: { content: "test response" } }],
}
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockStream)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "message 1" },
{ role: "assistant", content: "response 1" },
{ role: "user", content: "message 2" },
]
await handler.createMessage("test system", messages).next()
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "system",
content: expect.arrayContaining([
expect.objectContaining({ cache_control: { type: "ephemeral" } }),
]),
}),
]),
}),
{ headers: { "x-anthropic-beta": "fine-grained-tool-streaming-2025-05-14" } },
)
})
it("handles API errors and captures telemetry", async () => {
const handler = new OpenRouterHandler(mockOptions)
const mockStream = {
async *[Symbol.asyncIterator]() {
yield { error: { message: "API Error", code: 500 } }
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockStream)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const generator = handler.createMessage("test", [])
await expect(generator.next()).rejects.toThrow("OpenRouter API Error 500: API Error")
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "API Error",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "createMessage",
errorCode: 500,
status: 500,
}),
)
})
it("captures telemetry when createMessage throws an exception", async () => {
const handler = new OpenRouterHandler(mockOptions)
const mockCreate = vitest.fn().mockRejectedValue(new Error("Connection failed"))
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const generator = handler.createMessage("test", [])
await expect(generator.next()).rejects.toThrow()
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Connection failed",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "createMessage",
}),
)
})
it("passes SDK exceptions with status 429 to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const error = new Error("Rate limit exceeded: free-models-per-day") as any
error.status = 429
const mockCreate = vitest.fn().mockRejectedValue(error)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const generator = handler.createMessage("test", [])
await expect(generator.next()).rejects.toThrow("Rate limit exceeded")
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Rate limit exceeded: free-models-per-day",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "createMessage",
}),
)
})
it("passes SDK exceptions with 429 in message to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const error = new Error("429 Rate limit exceeded: free-models-per-day")
const mockCreate = vitest.fn().mockRejectedValue(error)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const generator = handler.createMessage("test", [])
await expect(generator.next()).rejects.toThrow("429 Rate limit exceeded")
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "429 Rate limit exceeded: free-models-per-day",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "createMessage",
}),
)
})
it("passes SDK exceptions containing 'rate limit' to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const error = new Error("Request failed due to rate limit")
const mockCreate = vitest.fn().mockRejectedValue(error)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const generator = handler.createMessage("test", [])
await expect(generator.next()).rejects.toThrow("rate limit")
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Request failed due to rate limit",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "createMessage",
}),
)
})
it("passes 429 rate limit errors from stream to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const mockStream = {
async *[Symbol.asyncIterator]() {
yield { error: { message: "Rate limit exceeded", code: 429 } }
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockStream)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const generator = handler.createMessage("test", [])
await expect(generator.next()).rejects.toThrow("OpenRouter API Error 429: Rate limit exceeded")
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Rate limit exceeded",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "createMessage",
errorCode: 429,
status: 429,
}),
)
})
it("yields tool_call_end events when finish_reason is tool_calls", async () => {
// Import NativeToolCallParser to set up state
const { NativeToolCallParser } = await import("../../../core/assistant-message/NativeToolCallParser")
// Clear any previous state
NativeToolCallParser.clearRawChunkState()
const handler = new OpenRouterHandler(mockOptions)
const mockStream = {
async *[Symbol.asyncIterator]() {
yield {
id: "test-id",
choices: [
{
delta: {
tool_calls: [
{
index: 0,
id: "call_openrouter_test",
function: { name: "read_file", arguments: '{"path":"test.ts"}' },
},
],
},
index: 0,
},
],
}
yield {
id: "test-id",
choices: [
{
delta: {},
finish_reason: "tool_calls",
index: 0,
},
],
usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
}
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockStream)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const generator = handler.createMessage("test", [])
const chunks = []
for await (const chunk of generator) {
// Simulate what Task.ts does: when we receive tool_call_partial,
// process it through NativeToolCallParser to populate rawChunkTracker
if (chunk.type === "tool_call_partial") {
NativeToolCallParser.processRawChunk({
index: chunk.index,
id: chunk.id,
name: chunk.name,
arguments: chunk.arguments,
})
}
chunks.push(chunk)
}
// Should have tool_call_partial and tool_call_end
const partialChunks = chunks.filter((chunk) => chunk.type === "tool_call_partial")
const endChunks = chunks.filter((chunk) => chunk.type === "tool_call_end")
expect(partialChunks).toHaveLength(1)
expect(endChunks).toHaveLength(1)
expect(endChunks[0].id).toBe("call_openrouter_test")
})
})
describe("Mistral/Devstral message formatting", () => {
it("merges tool result text into tool messages for devstral models to avoid user-after-tool error", async () => {
const handler = new OpenRouterHandler({
...mockOptions,
openRouterModelId: "mistralai/devstral-2512",
})
const mockStream = {
async *[Symbol.asyncIterator]() {
yield {
id: "test-id",
choices: [{ delta: { content: "test response" } }],
}
yield {
id: "test-id",
choices: [{ delta: {} }],
usage: { prompt_tokens: 10, completion_tokens: 20 },
}
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockStream)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
// Simulate messages with tool results followed by text content in same user message
// This is the pattern that causes "Unexpected role 'user' after role 'tool'" errors
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Use the read_file tool" },
{
role: "assistant",
content: [
{
type: "tool_use",
id: "tool_call_1",
name: "read_file",
input: { path: "test.ts" },
},
],
},
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "tool_call_1",
content: "file contents here",
},
{
type: "text",
text: "Now analyze this file",
},
],
},
]
const generator = handler.createMessage("test system", messages)
for await (const _chunk of generator) {
// consume the stream
}
// Verify the messages sent to OpenAI API
const callArgs = mockCreate.mock.calls[0][0]
const apiMessages = callArgs.messages
// After tool messages, the text should NOT appear as a separate user message.
// Instead it should be merged into the last tool message content.
// Check that no user message directly follows a tool message
for (let i = 1; i < apiMessages.length; i++) {
if (apiMessages[i].role === "user" && apiMessages[i - 1].role === "tool") {
throw new Error(
"Found user message directly after tool message - mergeToolResultText is not working",
)
}
}
})
it("detects models with 'mistral' in the model ID (e.g. mistralai/mistral-large)", async () => {
const handler = new OpenRouterHandler({
...mockOptions,
openRouterModelId: "mistralai/devstral-2512",
})
const mockStream = {
async *[Symbol.asyncIterator]() {
yield {
id: "test-id",
choices: [{ delta: { content: "ok" } }],
}
yield {
id: "test-id",
choices: [{ delta: {} }],
usage: { prompt_tokens: 5, completion_tokens: 5 },
}
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockStream)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
// Simple message without tool results - just verify it works
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const generator = handler.createMessage("test", messages)
for await (const _chunk of generator) {
// consume
}
expect(mockCreate).toHaveBeenCalled()
const callArgs = mockCreate.mock.calls[0][0]
expect(callArgs.model).toBe("mistralai/devstral-2512")
})
})
describe("completePrompt", () => {
it("returns correct response", async () => {
const handler = new OpenRouterHandler(mockOptions)
const mockResponse = { choices: [{ message: { content: "test completion" } }] }
const mockCreate = vitest.fn().mockResolvedValue(mockResponse)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
const result = await handler.completePrompt("test prompt")
expect(result).toBe("test completion")
expect(mockCreate).toHaveBeenCalledWith(
{
model: mockOptions.openRouterModelId,
max_tokens: 8192,
temperature: 0,
messages: [{ role: "user", content: "test prompt" }],
stream: false,
},
{ headers: { "x-anthropic-beta": "fine-grained-tool-streaming-2025-05-14" } },
)
})
it("handles API errors and captures telemetry", async () => {
const handler = new OpenRouterHandler(mockOptions)
const mockError = {
error: {
message: "API Error",
code: 500,
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockError)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
await expect(handler.completePrompt("test prompt")).rejects.toThrow("OpenRouter API Error 500: API Error")
// Verify telemetry was captured
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "API Error",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "completePrompt",
errorCode: 500,
status: 500,
}),
)
})
it("handles unexpected errors and captures telemetry", async () => {
const handler = new OpenRouterHandler(mockOptions)
const error = new Error("Unexpected error")
const mockCreate = vitest.fn().mockRejectedValue(error)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
await expect(handler.completePrompt("test prompt")).rejects.toThrow("Unexpected error")
// Verify telemetry was captured (filtering now happens inside PostHogTelemetryClient)
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Unexpected error",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "completePrompt",
}),
)
})
it("passes SDK exceptions with status 429 to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const error = new Error("Rate limit exceeded: free-models-per-day") as any
error.status = 429
const mockCreate = vitest.fn().mockRejectedValue(error)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
await expect(handler.completePrompt("test prompt")).rejects.toThrow("Rate limit exceeded")
// captureException is called, but PostHogTelemetryClient filters out 429 errors internally
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Rate limit exceeded: free-models-per-day",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "completePrompt",
}),
)
})
it("passes SDK exceptions with 429 in message to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const error = new Error("429 Rate limit exceeded: free-models-per-day")
const mockCreate = vitest.fn().mockRejectedValue(error)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
await expect(handler.completePrompt("test prompt")).rejects.toThrow("429 Rate limit exceeded")
// captureException is called, but PostHogTelemetryClient filters out 429 errors internally
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "429 Rate limit exceeded: free-models-per-day",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "completePrompt",
}),
)
})
it("passes SDK exceptions containing 'rate limit' to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const error = new Error("Request failed due to rate limit")
const mockCreate = vitest.fn().mockRejectedValue(error)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
await expect(handler.completePrompt("test prompt")).rejects.toThrow("rate limit")
// captureException is called, but PostHogTelemetryClient filters out rate limit errors internally
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Request failed due to rate limit",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "completePrompt",
}),
)
})
it("passes 429 rate limit errors from response to telemetry (filtering happens in PostHogTelemetryClient)", async () => {
const handler = new OpenRouterHandler(mockOptions)
const mockError = {
error: {
message: "Rate limit exceeded",
code: 429,
},
}
const mockCreate = vitest.fn().mockResolvedValue(mockError)
;(OpenAI as any).prototype.chat = {
completions: { create: mockCreate },
} as any
await expect(handler.completePrompt("test prompt")).rejects.toThrow(
"OpenRouter API Error 429: Rate limit exceeded",
)
// captureException is called, but PostHogTelemetryClient filters out 429 errors internally
expect(mockCaptureException).toHaveBeenCalledWith(
expect.objectContaining({
message: "Rate limit exceeded",
provider: "OpenRouter",
modelId: mockOptions.openRouterModelId,
operation: "completePrompt",
errorCode: 429,
status: 429,
}),
)
})
})
})