forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanthropic-request.test.ts
More file actions
814 lines (762 loc) · 26.4 KB
/
anthropic-request.test.ts
File metadata and controls
814 lines (762 loc) · 26.4 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
import { describe, test, expect } from "bun:test"
import { z } from "zod"
import {
isTypedTool,
type AnthropicMessagesPayload,
type AnthropicTool,
} from "~/routes/messages/anthropic-types"
import { translateToOpenAI } from "~/routes/messages/non-stream-translation"
// Zod schema for a single message in the chat completion request.
const messageSchema = z.object({
role: z.enum([
"system",
"user",
"assistant",
"tool",
"function",
"developer",
]),
content: z.union([z.string(), z.object({}), z.array(z.any())]),
name: z.string().optional(),
tool_calls: z.array(z.any()).optional(),
tool_call_id: z.string().optional(),
})
// Zod schema for the entire chat completion request payload.
// This is derived from the openapi.documented.yml specification.
const chatCompletionRequestSchema = z.object({
messages: z.array(messageSchema).min(1, "Messages array cannot be empty."),
model: z.string(),
frequency_penalty: z.number().min(-2).max(2).optional().nullable(),
logit_bias: z.record(z.string(), z.number()).optional().nullable(),
logprobs: z.boolean().optional().nullable(),
top_logprobs: z.number().int().min(0).max(20).optional().nullable(),
max_tokens: z.number().int().optional().nullable(),
n: z.number().int().min(1).max(128).optional().nullable(),
presence_penalty: z.number().min(-2).max(2).optional().nullable(),
response_format: z
.object({
type: z.enum(["text", "json_object", "json_schema"]),
json_schema: z.object({}).optional(),
})
.optional(),
seed: z.number().int().optional().nullable(),
stop: z
.union([z.string(), z.array(z.string())])
.optional()
.nullable(),
stream: z.boolean().optional().nullable(),
temperature: z.number().min(0).max(2).optional().nullable(),
top_p: z.number().min(0).max(1).optional().nullable(),
tools: z.array(z.any()).optional(),
tool_choice: z.union([z.string(), z.object({})]).optional(),
user: z.string().optional(),
})
/**
* Validates if a request payload conforms to the OpenAI Chat Completion v1 shape using Zod.
* @param payload The request payload to validate.
* @returns True if the payload is valid, false otherwise.
*/
function isValidChatCompletionRequest(payload: unknown): boolean {
const result = chatCompletionRequestSchema.safeParse(payload)
return result.success
}
describe("Anthropic to OpenAI translation logic", () => {
test("should translate minimal Anthropic payload to valid OpenAI payload", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
max_tokens: 0,
}
const openAIPayload = translateToOpenAI(anthropicPayload)
expect(isValidChatCompletionRequest(openAIPayload)).toBe(true)
})
test("should translate comprehensive Anthropic payload to valid OpenAI payload", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "gpt-4o",
system: "You are a helpful assistant.",
messages: [
{ role: "user", content: "What is the weather like in Boston?" },
{
role: "assistant",
content: "The weather in Boston is sunny and 75°F.",
},
],
temperature: 0.7,
max_tokens: 150,
top_p: 1,
stream: false,
metadata: { user_id: "user-123" },
tools: [
{
name: "getWeather",
description: "Gets weather info",
input_schema: { location: { type: "string" } },
},
],
tool_choice: { type: "auto" },
}
const openAIPayload = translateToOpenAI(anthropicPayload)
expect(isValidChatCompletionRequest(openAIPayload)).toBe(true)
})
test("should handle missing fields gracefully", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
max_tokens: 0,
}
const openAIPayload = translateToOpenAI(anthropicPayload)
expect(isValidChatCompletionRequest(openAIPayload)).toBe(true)
})
test("should handle invalid types in Anthropic payload", () => {
const anthropicPayload = {
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
temperature: "hot", // Should be a number
}
// @ts-expect-error intended to be invalid
const openAIPayload = translateToOpenAI(anthropicPayload)
// Should fail validation
expect(isValidChatCompletionRequest(openAIPayload)).toBe(false)
})
test("should handle thinking blocks in assistant messages", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-3-5-sonnet-20241022",
messages: [
{ role: "user", content: "What is 2+2?" },
{
role: "assistant",
content: [
{
type: "thinking",
thinking: "Let me think about this simple math problem...",
},
{ type: "text", text: "2+2 equals 4." },
],
},
],
max_tokens: 100,
}
const openAIPayload = translateToOpenAI(anthropicPayload)
expect(isValidChatCompletionRequest(openAIPayload)).toBe(true)
// Thinking blocks should be stripped — Copilot doesn't understand them
// and they inflate the prompt token count
const assistantMessage = openAIPayload.messages.find(
(m) => m.role === "assistant",
)
expect(assistantMessage?.content).not.toContain(
"Let me think about this simple math problem...",
)
expect(assistantMessage?.content).toContain("2+2 equals 4.")
})
test("should handle thinking blocks with tool calls", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-3-5-sonnet-20241022",
messages: [
{ role: "user", content: "What's the weather?" },
{
role: "assistant",
content: [
{
type: "thinking",
thinking:
"I need to call the weather API to get current weather information.",
},
{ type: "text", text: "I'll check the weather for you." },
{
type: "tool_use",
id: "call_123",
name: "get_weather",
input: { location: "New York" },
},
],
},
],
max_tokens: 100,
}
const openAIPayload = translateToOpenAI(anthropicPayload)
expect(isValidChatCompletionRequest(openAIPayload)).toBe(true)
// Thinking blocks should be stripped — only text content forwarded
const assistantMessage = openAIPayload.messages.find(
(m) => m.role === "assistant",
)
expect(assistantMessage?.content).not.toContain(
"I need to call the weather API",
)
expect(assistantMessage?.content).toContain(
"I'll check the weather for you.",
)
expect(assistantMessage?.tool_calls).toHaveLength(1)
expect(assistantMessage?.tool_calls?.[0].function.name).toBe("get_weather")
})
test("should filter out Anthropic typed tools (no input_schema) from tools array", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [{ role: "user", content: "Hello" }],
max_tokens: 100,
tools: [
// Custom tool — should be kept
{
name: "Bash",
description: "Run shell commands",
input_schema: {
type: "object",
properties: {},
additionalProperties: false,
},
},
// Anthropic-typed tool — should be filtered
{ type: "bash_20250124", name: "bash" } as unknown as AnthropicTool,
],
}
const result = translateToOpenAI(anthropicPayload)
// Only the custom "Bash" tool survives
expect(result.tools).toHaveLength(1)
expect(result.tools?.[0].function.name).toBe("Bash")
})
})
describe("Anthropic new content block types (Task 6)", () => {
test("document block in user message produces placeholder text", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{
role: "user",
content: [
{ type: "text", text: "Summarize this PDF." },
{
type: "document",
title: "My Report",
source: {
type: "base64",
media_type: "application/pdf",
data: "JVBERi0x",
},
},
],
},
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const userMsg = result.messages.find((m) => m.role === "user")
expect(typeof userMsg?.content).toBe("string")
const content = userMsg?.content as string
expect(content).toContain("Summarize this PDF.")
expect(content).toContain("[Document: PDF content not displayable]")
})
test("server_tool_use block in assistant message is serialized to text", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Search for something." },
{
role: "assistant",
content: [
{
type: "server_tool_use",
id: "srv_1",
name: "web_search",
input: { query: "test" },
},
{ type: "text", text: "I searched for you." },
],
},
{ role: "user", content: "Thanks." },
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const assistantMsg = result.messages.find((m) => m.role === "assistant")
const content = assistantMsg?.content as string
expect(content).toContain("[Server tool use:")
expect(content).toContain("web_search")
expect(content).toContain("I searched for you.")
})
})
describe("Anthropic new content block types (Task 2)", () => {
test("should handle document blocks in user messages", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{
role: "user",
content: [
{ type: "text", text: "What does this PDF say?" },
{
type: "document",
source: {
type: "base64",
media_type: "application/pdf",
data: "JVBERi0x",
},
},
],
},
],
max_tokens: 100,
}
// Should not throw; document block is converted to placeholder text
expect(() => translateToOpenAI(anthropicPayload)).not.toThrow()
const result = translateToOpenAI(anthropicPayload)
expect(isValidChatCompletionRequest(result)).toBe(true)
// Placeholder text must appear in the message content
const userMsg = result.messages.find((m) => m.role === "user")
expect(typeof userMsg?.content).toBe("string")
expect(userMsg?.content as string).toContain(
"[Document: PDF content not displayable]",
)
})
test("should handle redacted_thinking blocks in assistant messages", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Think hard about this." },
{
role: "assistant",
content: [
{ type: "redacted_thinking", data: "EncryptedThinkingData==" },
{ type: "text", text: "Here is my answer." },
],
},
{ role: "user", content: "Follow up." },
],
max_tokens: 100,
}
expect(() => translateToOpenAI(anthropicPayload)).not.toThrow()
const result = translateToOpenAI(anthropicPayload)
// The redacted_thinking block is stripped; only the text block survives
const assistantMsg = result.messages.find((m) => m.role === "assistant")
expect(assistantMsg?.content).toContain("Here is my answer.")
// redacted_thinking data must NOT appear as raw base64
expect(assistantMsg?.content as string).not.toContain(
"EncryptedThinkingData==",
)
})
})
describe("handleUserMessage array tool_result content and web_search_tool_result (Task 8)", () => {
test("tool_result with array content containing image is translated to vision ContentPart", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Take a screenshot." },
{
role: "assistant",
content: [
{
type: "tool_use",
id: "call_sc",
name: "computer",
input: { action: "screenshot" },
},
],
},
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "call_sc",
content: [
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "iVBORw0KGgo=",
},
},
],
},
],
},
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const toolMsg = result.messages.find((m) => m.role === "tool")
expect(typeof toolMsg?.content).toBe("string")
expect(toolMsg?.content).toContain(
"Non-text tool result forwarded in the following user message",
)
const userMsgs = result.messages.filter((m) => m.role === "user")
const followUpMsg = userMsgs.at(-1)
expect(Array.isArray(followUpMsg?.content)).toBe(true)
const parts = followUpMsg?.content as Array<{ type: string }>
expect(parts[0].type).toBe("image_url")
})
test("tool_result with array content containing text is translated to string", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Run a command." },
{
role: "assistant",
content: [
{
type: "tool_use",
id: "call_b",
name: "Bash",
input: { command: "ls" },
},
],
},
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "call_b",
content: [{ type: "text", text: "file1.txt\nfile2.txt" }],
},
],
},
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const toolMsg = result.messages.find((m) => m.role === "tool")
expect(typeof toolMsg?.content).toBe("string")
expect(toolMsg?.content).toContain("file1.txt")
})
test("oversized tool_result text is condensed with head, middle, tail, and compaction guidance", () => {
const largeText =
"A".repeat(9000)
+ "MIDDLE"
+ "B".repeat(9000)
+ "C".repeat(4500)
+ "TAILMARK"
+ "D".repeat(4500)
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Run a verbose command." },
{
role: "assistant",
content: [
{
type: "tool_use",
id: "call_large",
name: "Bash",
input: { command: "verbose" },
},
],
},
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "call_large",
content: [{ type: "text", text: largeText }],
},
],
},
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const toolMsg = result.messages.find((m) => m.role === "tool")
expect(typeof toolMsg?.content).toBe("string")
expect(toolMsg?.content).toContain("[Tool result condensed by proxy:")
expect(toolMsg?.content).toContain(
"compact older conversation state before discarding this fresh tool result",
)
expect(toolMsg?.content).toContain("=== BEGIN TOOL RESULT HEAD ===")
expect(toolMsg?.content).toContain(
"=== BEGIN TOOL RESULT MIDDLE SAMPLE ===",
)
expect(toolMsg?.content).toContain("=== BEGIN TOOL RESULT TAIL ===")
expect(toolMsg?.content).toContain("AAAA")
expect(toolMsg?.content).toContain("MIDDLE")
expect(toolMsg?.content).toContain("TAILMARK")
})
test("web_search_tool_result block is serialized as user message", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Search the web." },
{
role: "user",
content: [
{
type: "web_search_tool_result",
tool_use_id: "srv_ws_1",
content: [
{
type: "web_search_result",
url: "https://example.com",
title: "Example",
encrypted_content: "abc",
},
],
},
],
},
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const webResultMsg = result.messages.find(
(m) =>
m.role === "user"
&& typeof m.content === "string"
&& m.content.includes("[Web search result:"),
)
expect(webResultMsg).toBeDefined()
expect(webResultMsg?.content).toContain("example.com")
})
})
describe("handleAssistantMessage redacted_thinking and server_tool_use (Task 7)", () => {
test("redacted_thinking block is stripped from assistant message (Branch 2, no tool calls)", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Think hard." },
{
role: "assistant",
content: [
{ type: "redacted_thinking", data: "EncryptedBinaryData==" },
{ type: "text", text: "My considered answer." },
],
},
{ role: "user", content: "Follow up." },
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const assistantMsg = result.messages.find((m) => m.role === "assistant")
// Content must contain the text but NOT the redacted data
expect(assistantMsg?.content).toContain("My considered answer.")
expect(assistantMsg?.content).not.toContain("EncryptedBinaryData==")
})
test("server_tool_use block is serialized in assistant message with tool calls (Branch 1)", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [
{ role: "user", content: "Do something." },
{
role: "assistant",
content: [
{
type: "server_tool_use",
id: "srv_1",
name: "web_search",
input: { query: "test" },
},
{ type: "text", text: "Let me also call a tool." },
{
type: "tool_use",
id: "call_1",
name: "Bash",
input: { command: "ls" },
},
],
},
],
max_tokens: 100,
}
const result = translateToOpenAI(anthropicPayload)
const assistantMsg = result.messages.find((m) => m.role === "assistant")
// Branch 1: has tool_use, so content is the text + server_tool_use serialized
expect(assistantMsg?.content).toContain("Let me also call a tool.")
expect(assistantMsg?.content).toContain("[Server tool use:")
expect(assistantMsg?.tool_calls).toHaveLength(1)
expect(assistantMsg?.tool_calls?.[0].function.name).toBe("Bash")
})
})
describe("strict field forwarding (Task 3)", () => {
test("should forward strict:true from custom tool definitions to OpenAI", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [{ role: "user", content: "Hello" }],
max_tokens: 100,
tools: [
{
name: "getWeather",
description: "Get weather",
input_schema: {
type: "object",
properties: { location: { type: "string" } },
required: ["location"],
},
strict: true,
},
],
}
const result = translateToOpenAI(anthropicPayload)
expect(result.tools?.[0].function.strict).toBe(true)
})
test("should not add strict field when not provided", () => {
const anthropicPayload: AnthropicMessagesPayload = {
model: "claude-sonnet-4",
messages: [{ role: "user", content: "Hello" }],
max_tokens: 100,
tools: [
{
name: "getWeather",
description: "Get weather",
input_schema: { type: "object", properties: {} },
},
],
}
const result = translateToOpenAI(anthropicPayload)
expect(result.tools?.[0].function.strict).toBeUndefined()
})
})
function getTranslatedModel(model: string): string {
const result = translateToOpenAI({
model,
messages: [{ role: "user", content: "Hi" }],
max_tokens: 10,
})
return result.model
}
describe("translateModelName normalization", () => {
test("normalizes claude-sonnet-4-6 to claude-sonnet-4", () => {
expect(getTranslatedModel("claude-sonnet-4-6")).toBe("claude-sonnet-4")
})
test("normalizes claude-haiku-4-5 to claude-haiku-4 (was missing before)", () => {
expect(getTranslatedModel("claude-haiku-4-5")).toBe("claude-haiku-4")
})
test("normalizes claude-opus-4-6 to claude-opus-4", () => {
expect(getTranslatedModel("claude-opus-4-6")).toBe("claude-opus-4")
})
test("does NOT change claude-sonnet-3-5 (stable 3.x name)", () => {
expect(getTranslatedModel("claude-sonnet-3-5")).toBe("claude-sonnet-3-5")
})
test("does NOT change claude-haiku-3-5 (stable 3.x name)", () => {
expect(getTranslatedModel("claude-haiku-3-5")).toBe("claude-haiku-3-5")
})
test("normalizes long versioned names like claude-sonnet-4-6-20251231", () => {
expect(getTranslatedModel("claude-sonnet-4-6-20251231")).toBe(
"claude-sonnet-4",
)
})
test("does NOT change non-claude models", () => {
expect(getTranslatedModel("gpt-4o")).toBe("gpt-4o")
expect(getTranslatedModel("grok-2")).toBe("grok-2")
})
})
describe("OpenAI Chat Completion v1 Request Payload Validation with Zod", () => {
test("should return true for a minimal valid request payload", () => {
const validPayload = {
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
}
expect(isValidChatCompletionRequest(validPayload)).toBe(true)
})
test("should return true for a comprehensive valid request payload", () => {
const validPayload = {
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "What is the weather like in Boston?" },
],
temperature: 0.7,
max_tokens: 150,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
stream: false,
n: 1,
}
expect(isValidChatCompletionRequest(validPayload)).toBe(true)
})
test('should return false if the "model" field is missing', () => {
const invalidPayload = {
messages: [{ role: "user", content: "Hello!" }],
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test('should return false if the "messages" field is missing', () => {
const invalidPayload = {
model: "gpt-4o",
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test('should return false if the "messages" array is empty', () => {
const invalidPayload = {
model: "gpt-4o",
messages: [],
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test('should return false if "model" is not a string', () => {
const invalidPayload = {
model: 12345,
messages: [{ role: "user", content: "Hello!" }],
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test('should return false if "messages" is not an array', () => {
const invalidPayload = {
model: "gpt-4o",
messages: { role: "user", content: "Hello!" },
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test('should return false if a message in the "messages" array is missing a "role"', () => {
const invalidPayload = {
model: "gpt-4o",
messages: [{ content: "Hello!" }],
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test('should return false if a message in the "messages" array is missing "content"', () => {
const invalidPayload = {
model: "gpt-4o",
messages: [{ role: "user" }],
}
// Note: Zod considers 'undefined' as missing, so this will fail as expected.
const result = chatCompletionRequestSchema.safeParse(invalidPayload)
expect(result.success).toBe(false)
})
test('should return false if a message has an invalid "role"', () => {
const invalidPayload = {
model: "gpt-4o",
messages: [{ role: "customer", content: "Hello!" }],
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test("should return false if an optional field has an incorrect type", () => {
const invalidPayload = {
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
temperature: "hot", // Should be a number
}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test("should return false for a completely empty object", () => {
const invalidPayload = {}
expect(isValidChatCompletionRequest(invalidPayload)).toBe(false)
})
test("should return false for null or non-object payloads", () => {
expect(isValidChatCompletionRequest(null)).toBe(false)
expect(isValidChatCompletionRequest(undefined)).toBe(false)
expect(isValidChatCompletionRequest("a string")).toBe(false)
expect(isValidChatCompletionRequest(123)).toBe(false)
})
})
describe("isTypedTool discriminator", () => {
test("returns true for a typed tool (no input_schema)", () => {
const typedTool = { type: "bash_20250124", name: "bash" }
expect(isTypedTool(typedTool)).toBe(true)
})
test("returns false for a custom tool (has input_schema)", () => {
const customTool = {
name: "Bash",
description: "Run shell commands",
input_schema: {},
}
expect(isTypedTool(customTool)).toBe(false)
})
test("returns false for custom tool even if it has extra fields", () => {
const customTool = {
name: "Bash",
input_schema: {},
strict: true,
cache_control: { type: "ephemeral" },
}
expect(isTypedTool(customTool as AnthropicTool)).toBe(false)
})
})