-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathnative-ollama.spec.ts
More file actions
1242 lines (1061 loc) · 34 KB
/
Copy pathnative-ollama.spec.ts
File metadata and controls
1242 lines (1061 loc) · 34 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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// pnpm exec vitest run api/providers/__tests__/native-ollama.spec.ts
import { Anthropic } from "@anthropic-ai/sdk"
import { NativeOllamaHandler } from "../native-ollama"
import { ApiHandlerOptions } from "../../../shared/api"
import { getOllamaModels } from "../fetchers/ollama"
// Mock the ollama package
const mockChat = vitest.fn()
vitest.mock("ollama", () => {
return {
Ollama: vitest.fn().mockImplementation(function () {
return {
chat: mockChat,
}
}),
Message: vitest.fn(),
}
})
// Mock the getOllamaModels function
vitest.mock("../fetchers/ollama", () => ({
getOllamaModels: vitest.fn(),
}))
const mockGetOllamaModels = vitest.mocked(getOllamaModels)
describe("NativeOllamaHandler", () => {
let handler: NativeOllamaHandler
beforeEach(() => {
vitest.clearAllMocks()
// Default mock for getOllamaModels
mockGetOllamaModels.mockResolvedValue({
llama2: {
contextWindow: 4096,
maxTokens: 4096,
supportsImages: false,
supportsPromptCache: false,
},
})
const options: ApiHandlerOptions = {
apiModelId: "llama2",
ollamaModelId: "llama2",
ollamaBaseUrl: "http://localhost:11434",
}
handler = new NativeOllamaHandler(options)
})
describe("createMessage", () => {
it("should stream messages from Ollama", async () => {
// Mock the chat response as an async generator
mockChat.mockImplementation(async function* () {
yield {
message: { content: "Hello" },
eval_count: undefined,
prompt_eval_count: undefined,
}
yield {
message: { content: " world" },
eval_count: 2,
prompt_eval_count: 10,
}
})
const systemPrompt = "You are a helpful assistant"
const messages = [{ role: "user" as const, content: "Hi there" }]
const stream = handler.createMessage(systemPrompt, messages)
const results = []
for await (const chunk of stream) {
results.push(chunk)
}
expect(results).toHaveLength(3)
expect(results[0]).toEqual({ type: "text", text: "Hello" })
expect(results[1]).toEqual({ type: "text", text: " world" })
expect(results[2]).toEqual({ type: "usage", inputTokens: 10, outputTokens: 2 })
})
it("should map tool_result array content to a concatenated string, flushing base64 images", async () => {
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "tool-1",
content: [
{ type: "text", text: "line one" },
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "imgdata",
},
},
{ type: "text", text: "line two" },
],
},
],
},
]
const stream = handler.createMessage("System", messages)
for await (const _ of stream) {
// consume stream
}
// Text blocks are joined with "\n"; the image emits a placeholder and is
// flushed separately via the `images` field rather than inlined.
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "user",
content: "line one\n(see following user message for image)\nline two",
images: ["imgdata"],
}),
]),
}),
)
})
it("should drop unknown block types in tool_result content (empty string contribution)", async () => {
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "tool-1",
content: [
{ type: "text", text: "before" },
{ type: "document" } as any,
{ type: "text", text: "after" },
],
},
],
},
]
const stream = handler.createMessage("System", messages)
for await (const _ of stream) {
// consume
}
// The unknown block contributes "" so the join produces "before\n\nafter"
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "user",
content: "before\n\nafter",
}),
]),
}),
)
})
it("should not include num_ctx by default", async () => {
// Mock the chat response
mockChat.mockImplementation(async function* () {
yield { message: { content: "Response" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }])
// Consume the stream
for await (const _ of stream) {
// consume stream
}
// Verify that num_ctx was NOT included in the options
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.not.objectContaining({
num_ctx: expect.anything(),
}),
}),
)
})
it("should include num_ctx when explicitly set via ollamaNumCtx", async () => {
const options: ApiHandlerOptions = {
apiModelId: "llama2",
ollamaModelId: "llama2",
ollamaBaseUrl: "http://localhost:11434",
ollamaNumCtx: 8192, // Explicitly set num_ctx
}
handler = new NativeOllamaHandler(options)
// Mock the chat response
mockChat.mockImplementation(async function* () {
yield { message: { content: "Response" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }])
// Consume the stream
for await (const _ of stream) {
// consume stream
}
// Verify that num_ctx was included with the specified value
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.objectContaining({
num_ctx: 8192,
}),
}),
)
})
it("should handle DeepSeek R1 models with reasoning detection", async () => {
const options: ApiHandlerOptions = {
apiModelId: "deepseek-r1",
ollamaModelId: "deepseek-r1",
ollamaBaseUrl: "http://localhost:11434",
}
handler = new NativeOllamaHandler(options)
// Mock response with thinking tags
mockChat.mockImplementation(async function* () {
yield { message: { content: "<think>Let me think" } }
yield { message: { content: " about this</think>" } }
yield { message: { content: "The answer is 42" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Question?" }])
const results = []
for await (const chunk of stream) {
results.push(chunk)
}
// Should detect reasoning vs regular text
expect(results.some((r) => r.type === "reasoning")).toBe(true)
expect(results.some((r) => r.type === "text")).toBe(true)
})
it("should surface Ollama's native message.thinking field as reasoning", async () => {
mockChat.mockImplementation(async function* () {
yield { message: { content: "", thinking: "Reasoning step one" } }
yield { message: { content: "", thinking: " step two" } }
yield { message: { content: "The answer" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Question?" }])
const results = []
for await (const chunk of stream) {
results.push(chunk)
}
const reasoningChunks = results.filter((r) => r.type === "reasoning")
expect(reasoningChunks).toHaveLength(2)
expect(reasoningChunks[0]).toEqual({ type: "reasoning", text: "Reasoning step one" })
expect(reasoningChunks[1]).toEqual({ type: "reasoning", text: " step two" })
expect(results.some((r) => r.type === "text" && r.text === "The answer")).toBe(true)
})
it("should send think parameter when reasoningEffort is set", async () => {
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: true,
reasoningEffort: "high",
}
handler = new NativeOllamaHandler(options)
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok", thinking: "hmm" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
think: "high",
}),
)
})
it("should map reasoningEffort levels to Ollama think values", async () => {
const cases: Array<
[NonNullable<ApiHandlerOptions["reasoningEffort"]>, boolean | "high" | "medium" | "low"]
> = [
["low", "low"],
["medium", "medium"],
["high", "high"],
["xhigh", "high"],
["max", "high"],
["none", true],
["minimal", true],
["disable", false],
]
for (const [effort, expected] of cases) {
vitest.clearAllMocks()
mockGetOllamaModels.mockResolvedValue({
qwen3: { contextWindow: 4096, maxTokens: 4096, supportsImages: false, supportsPromptCache: false },
})
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: true,
reasoningEffort: effort,
}
handler = new NativeOllamaHandler(options)
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
think: expected,
}),
)
}
})
it("should not send think parameter when reasoningEffort is undefined", async () => {
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
const callArgs = mockChat.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.think).toBeUndefined()
})
it("should not send think parameter when enableReasoningEffort is false", async () => {
// When the Ollama UI checkbox is unchecked, enableReasoningEffort
// is false. The handler must not send any think param (undefined),
// leaving the model/Modelfile in control rather than forcing
// thinking off. A stale reasoningEffort value must not override
// the explicit opt-out.
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: false,
reasoningEffort: "high",
}
handler = new NativeOllamaHandler(options)
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
const callArgs = mockChat.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.think).toBeUndefined()
})
it("should not send think parameter when enableReasoningEffort is undefined but reasoningEffort is set", async () => {
// This guards against a stale reasoningEffort inherited from
// another provider config. Without an explicit Ollama opt-in,
// the handler must not emit a think param.
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
// enableReasoningEffort intentionally undefined
reasoningEffort: "high",
}
handler = new NativeOllamaHandler(options)
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
const callArgs = mockChat.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.think).toBeUndefined()
})
it("should send think=false when reasoningEffort is disable and enableReasoningEffort is true", async () => {
// The only way to explicitly force thinking off via the think
// parameter is to set reasoningEffort to "disable" while opted in.
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: true,
reasoningEffort: "disable",
}
handler = new NativeOllamaHandler(options)
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
think: false,
}),
)
})
it("should round-trip reasoning blocks as the thinking field on assistant messages", async () => {
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{ type: "reasoning", text: "Prior reasoning", summary: [] } as any,
{ type: "text", text: "Prior answer" },
],
},
{ role: "user" as const, content: "Follow up" },
]
const stream = handler.createMessage("System", messages)
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "assistant",
thinking: "Prior reasoning",
}),
]),
}),
)
})
it("should round-trip Anthropic-protocol thinking blocks as the thinking field on assistant messages", async () => {
// Covers the `block.type === "thinking"` branch in the assistant
// message converter. Anthropic-protocol thinking blocks carry the
// reasoning text in a `thinking` field (not `text`).
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{ type: "thinking", thinking: "Anthropic thinking text" } as any,
{ type: "text", text: "Prior answer" },
],
},
{ role: "user" as const, content: "Follow up" },
]
const stream = handler.createMessage("System", messages)
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "assistant",
thinking: "Anthropic thinking text",
}),
]),
}),
)
})
it("should concatenate multiple reasoning and thinking blocks into the thinking field", async () => {
// Multiple reasoning/thinking blocks are joined with newlines so the
// full thinking context is preserved across turns.
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{ type: "reasoning", text: "First reasoning", summary: [] } as any,
{ type: "thinking", thinking: "Second thinking" } as any,
{ type: "text", text: "Answer" },
],
},
{ role: "user" as const, content: "Follow up" },
]
const stream = handler.createMessage("System", messages)
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "assistant",
thinking: "First reasoning\nSecond thinking",
}),
]),
}),
)
})
it("should not set thinking field when assistant reasoning/thinking blocks are empty", async () => {
// Covers the `block.text.length > 0` and `block.thinking.length > 0`
// false branches, and the `reasoningText || undefined` falsy branch.
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{ type: "reasoning", text: "", summary: [] } as any,
{ type: "thinking", thinking: "" } as any,
{ type: "text", text: "Answer" },
],
},
{ role: "user" as const, content: "Follow up" },
]
const stream = handler.createMessage("System", messages)
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "assistant",
thinking: undefined,
}),
]),
}),
)
})
it("should not set thinking field on assistant messages without reasoning blocks", async () => {
// Covers the `reasoningText || undefined` falsy branch for a plain
// assistant text+tool_use message (no reasoning/thinking blocks).
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{ type: "text", text: "Answer" },
{
type: "tool_use",
id: "tool-1",
name: "get_weather",
input: { location: "SF" },
},
],
},
{ role: "user" as const, content: "Follow up" },
]
const stream = handler.createMessage("System", messages)
for await (const _ of stream) {
// consume
}
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
messages: expect.arrayContaining([
expect.objectContaining({
role: "assistant",
thinking: undefined,
}),
]),
}),
)
})
it("should not send think parameter for an unknown reasoningEffort value", async () => {
// Covers the `default` branch of getOllamaThinkParam's switch,
// which returns undefined for unrecognized effort values.
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: true,
reasoningEffort: "bogus" as any,
}
handler = new NativeOllamaHandler(options)
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
const callArgs = mockChat.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.think).toBeUndefined()
})
})
it("should not send think parameter when enableReasoningEffort is true but reasoningEffort is undefined", async () => {
// This is the state the UI checkbox would produce if it only set
// enableReasoningEffort without a default reasoningEffort. The
// handler must not send a think param in that case.
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: true,
// reasoningEffort intentionally undefined
}
handler = new NativeOllamaHandler(options)
mockChat.mockImplementation(async function* () {
yield { message: { content: "ok" } }
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])
for await (const _ of stream) {
// consume
}
const callArgs = mockChat.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.think).toBeUndefined()
})
describe("completePrompt", () => {
it("should complete a prompt without streaming", async () => {
mockChat.mockResolvedValue({
message: { content: "This is the response" },
})
const result = await handler.completePrompt("Tell me a joke")
expect(mockChat).toHaveBeenCalledWith({
model: "llama2",
messages: [{ role: "user", content: "Tell me a joke" }],
stream: false,
options: {
temperature: 0,
},
})
expect(result).toBe("This is the response")
})
it("should not include num_ctx in completePrompt by default", async () => {
mockChat.mockResolvedValue({
message: { content: "Response" },
})
await handler.completePrompt("Test prompt")
// Verify that num_ctx was NOT included in the options
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.not.objectContaining({
num_ctx: expect.anything(),
}),
}),
)
})
it("should include num_ctx in completePrompt when explicitly set", async () => {
const options: ApiHandlerOptions = {
apiModelId: "llama2",
ollamaModelId: "llama2",
ollamaBaseUrl: "http://localhost:11434",
ollamaNumCtx: 4096, // Explicitly set num_ctx
}
handler = new NativeOllamaHandler(options)
mockChat.mockResolvedValue({
message: { content: "Response" },
})
await handler.completePrompt("Test prompt")
// Verify that num_ctx was included with the specified value
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.objectContaining({
num_ctx: 4096,
}),
}),
)
})
})
it("should send think parameter in completePrompt when reasoningEffort is set", async () => {
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: true,
reasoningEffort: "high",
}
handler = new NativeOllamaHandler(options)
mockChat.mockResolvedValue({
message: { content: "Response" },
})
await handler.completePrompt("Test prompt")
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
think: "high",
}),
)
})
it("should not send think parameter in completePrompt when reasoningEffort is undefined", async () => {
mockChat.mockResolvedValue({
message: { content: "Response" },
})
await handler.completePrompt("Test prompt")
const callArgs = mockChat.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.think).toBeUndefined()
})
it("should not send think parameter in completePrompt when enableReasoningEffort is false", async () => {
const options: ApiHandlerOptions = {
apiModelId: "qwen3",
ollamaModelId: "qwen3",
ollamaBaseUrl: "http://localhost:11434",
enableReasoningEffort: false,
reasoningEffort: "high",
}
handler = new NativeOllamaHandler(options)
mockChat.mockResolvedValue({
message: { content: "Response" },
})
await handler.completePrompt("Test prompt")
const callArgs = mockChat.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.think).toBeUndefined()
})
it("should wrap non-Error throws from completePrompt", async () => {
// Covers the `throw error` branch when the rejected value is not an
// Error instance (e.g. a plain object or string).
mockChat.mockRejectedValue("boom")
await expect(handler.completePrompt("Test prompt")).rejects.toBe("boom")
})
describe("error handling", () => {
it("should handle connection refused errors", async () => {
const error = new Error("ECONNREFUSED") as any
error.code = "ECONNREFUSED"
mockChat.mockRejectedValue(error)
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }])
await expect(async () => {
for await (const _ of stream) {
// consume stream
}
}).rejects.toThrow("Ollama service is not running")
})
it("should handle model not found errors", async () => {
const error = new Error("Not found") as any
error.status = 404
mockChat.mockRejectedValue(error)
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }])
await expect(async () => {
for await (const _ of stream) {
// consume stream
}
}).rejects.toThrow("Model llama2 not found in Ollama")
})
it("should wrap stream processing errors with a descriptive message", async () => {
// Covers the `catch (streamError)` branch: the chat() call
// resolves and returns an async iterable, but iterating it throws.
// The handler must wrap the error with "Ollama stream processing
// error: ..." and rethrow.
mockChat.mockImplementation(async function* () {
yield { message: { content: "partial" } }
throw new Error("stream blew up")
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }])
await expect(async () => {
for await (const _ of stream) {
// consume stream
}
}).rejects.toThrow("Ollama stream processing error: stream blew up")
})
it("should wrap stream processing errors with unknown message fallback", async () => {
// Covers the `streamError.message || "Unknown error"` fallback in
// the stream processing catch block when the error has no message.
mockChat.mockImplementation(async function* () {
yield { message: { content: "partial" } }
throw {}
})
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }])
await expect(async () => {
for await (const _ of stream) {
// consume stream
}
}).rejects.toThrow("Ollama stream processing error: Unknown error")
})
it("should rethrow non-ECONNREFUSED non-404 errors from chat()", async () => {
// Covers the fall-through `throw error` branch in the outer catch
// when the error is neither ECONNREFUSED nor a 404.
const error = new Error("something else") as any
error.status = 500
mockChat.mockRejectedValue(error)
const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }])
await expect(async () => {
for await (const _ of stream) {
// consume stream
}
}).rejects.toThrow("something else")
})
})
describe("getModel", () => {
it("should return the configured model", () => {
const model = handler.getModel()
expect(model.id).toBe("llama2")
expect(model.info).toBeDefined()
})
})
describe("tool calling", () => {
it("should include tools when tools are provided", async () => {
// Model metadata should not gate tool inclusion; metadata.tools controls it.
mockGetOllamaModels.mockResolvedValue({
"llama3.2": {
contextWindow: 128000,
maxTokens: 4096,
supportsImages: true,
supportsPromptCache: false,
},
})
const options: ApiHandlerOptions = {
apiModelId: "llama3.2",
ollamaModelId: "llama3.2",
ollamaBaseUrl: "http://localhost:11434",
}
handler = new NativeOllamaHandler(options)
// Mock the chat response
mockChat.mockImplementation(async function* () {
yield { message: { content: "I will use the tool" } }
})
const tools = [
{
type: "function" as const,
function: {
name: "get_weather",
description: "Get the weather for a location",
parameters: {
type: "object",
properties: {
location: { type: "string", description: "The city name" },
},
required: ["location"],
},
},
},
]
const stream = handler.createMessage(
"System",
[{ role: "user" as const, content: "What's the weather?" }],
{ taskId: "test", tools },
)
// Consume the stream
for await (const _ of stream) {
// consume stream
}
// Verify tools were passed to the API
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
tools: [
{
type: "function",
function: {
name: "get_weather",
description: "Get the weather for a location",
parameters: {
type: "object",
properties: {
location: { type: "string", description: "The city name" },
},
required: ["location"],
},
},
},
],
}),
)
})
it("should include tools even when model metadata doesn't advertise tool support", async () => {
// Model metadata should not gate tool inclusion; metadata.tools controls it.
mockGetOllamaModels.mockResolvedValue({
llama2: {
contextWindow: 4096,
maxTokens: 4096,
supportsImages: false,
supportsPromptCache: false,
},
})
// Mock the chat response
mockChat.mockImplementation(async function* () {
yield { message: { content: "Response without tools" } }
})
const tools = [
{
type: "function" as const,
function: {
name: "get_weather",
description: "Get the weather",
parameters: { type: "object", properties: {} },
},