-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathrequest_test.go
More file actions
767 lines (648 loc) · 27.9 KB
/
Copy pathrequest_test.go
File metadata and controls
767 lines (648 loc) · 27.9 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
package middleware_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"github.com/labstack/echo/v4"
"github.com/mudler/LocalAI/core/config"
. "github.com/mudler/LocalAI/core/http/middleware"
"github.com/mudler/LocalAI/core/schema"
"github.com/mudler/LocalAI/pkg/model"
"github.com/mudler/LocalAI/pkg/system"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// newRequestApp creates a minimal Echo app with SetModelAndConfig middleware.
func newRequestApp(re *RequestExtractor) *echo.Echo {
e := echo.New()
e.POST("/v1/chat/completions",
func(c echo.Context) error {
return c.String(http.StatusOK, "ok")
},
re.SetModelAndConfig(func() schema.LocalAIRequest {
return new(schema.OpenAIRequest)
}),
)
return e
}
func postJSON(e *echo.Echo, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
return rec
}
var _ = Describe("SetModelAndConfig middleware", func() {
var (
app *echo.Echo
modelDir string
)
BeforeEach(func() {
var err error
modelDir, err = os.MkdirTemp("", "localai-test-models-*")
Expect(err).ToNot(HaveOccurred())
ss := &system.SystemState{
Model: system.Model{ModelsPath: modelDir},
}
appConfig := config.NewApplicationConfig()
appConfig.SystemState = ss
mcl := config.NewModelConfigLoader(modelDir)
ml := model.NewModelLoader(ss)
re := NewRequestExtractor(mcl, ml, appConfig)
app = newRequestApp(re)
})
AfterEach(func() {
os.RemoveAll(modelDir)
})
Context("when the model does not exist", func() {
It("returns 404 with a helpful error message", func() {
rec := postJSON(app, "/v1/chat/completions",
`{"model":"nonexistent-model","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusNotFound))
var resp schema.ErrorResponse
Expect(json.Unmarshal(rec.Body.Bytes(), &resp)).To(Succeed())
Expect(resp.Error).ToNot(BeNil())
Expect(resp.Error.Message).To(ContainSubstring("nonexistent-model"))
Expect(resp.Error.Message).To(ContainSubstring("not found"))
Expect(resp.Error.Type).To(Equal("invalid_request_error"))
})
})
Context("when the model exists as a config file", func() {
BeforeEach(func() {
cfgContent := []byte("name: test-model\nbackend: llama-cpp\n")
err := os.WriteFile(filepath.Join(modelDir, "test-model.yaml"), cfgContent, 0644)
Expect(err).ToNot(HaveOccurred())
})
It("passes through to the handler", func() {
rec := postJSON(app, "/v1/chat/completions",
`{"model":"test-model","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusOK))
})
})
Context("when the model exists as a pre-loaded config", func() {
var mcl *config.ModelConfigLoader
BeforeEach(func() {
// Simulate a model installed via gallery: config is loaded in memory
// (not just a YAML file on disk). Recreate the app with the pre-loaded config.
ss := &system.SystemState{
Model: system.Model{ModelsPath: modelDir},
}
appConfig := config.NewApplicationConfig()
appConfig.SystemState = ss
mcl = config.NewModelConfigLoader(modelDir)
// Pre-load a config as if installed via gallery
cfgContent := []byte("name: gallery-model\nbackend: llama-cpp\nmodel: gallery-model\n")
err := os.WriteFile(filepath.Join(modelDir, "gallery-model.yaml"), cfgContent, 0644)
Expect(err).ToNot(HaveOccurred())
Expect(mcl.ReadModelConfig(filepath.Join(modelDir, "gallery-model.yaml"))).To(Succeed())
ml := model.NewModelLoader(ss)
re := NewRequestExtractor(mcl, ml, appConfig)
app = newRequestApp(re)
})
It("passes through to the handler", func() {
rec := postJSON(app, "/v1/chat/completions",
`{"model":"gallery-model","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusOK))
})
})
Context("when the model name contains a slash (HuggingFace ID)", func() {
It("skips the existence check and passes through", func() {
rec := postJSON(app, "/v1/chat/completions",
`{"model":"stabilityai/stable-diffusion-xl-base-1.0","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusOK))
})
})
Context("when the model name is a file path to a weight that does not exist", func() {
// A name like "local/model.gguf" is the parameters.model weight path, not a
// HuggingFace org/repo ID. The slash must not exempt it from the existence
// check, otherwise a wrong name silently falls through to the gallery
// autoloader and triggers a surprising download (issue #10162).
It("returns 404 instead of passing through", func() {
rec := postJSON(app, "/v1/chat/completions",
`{"model":"local/missing-model.gguf","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusNotFound))
var resp schema.ErrorResponse
Expect(json.Unmarshal(rec.Body.Bytes(), &resp)).To(Succeed())
Expect(resp.Error).ToNot(BeNil())
Expect(resp.Error.Message).To(ContainSubstring("local/missing-model.gguf"))
Expect(resp.Error.Message).To(ContainSubstring("not found"))
})
})
Context("when the model name is a file path to a weight that exists on disk", func() {
// The same path, but the loose weight file is actually present in a
// subdirectory of the models path: the request must pass through so users
// can address a raw weight file by its relative path.
It("passes through to the handler", func() {
Expect(os.MkdirAll(filepath.Join(modelDir, "local"), 0755)).To(Succeed())
Expect(os.WriteFile(filepath.Join(modelDir, "local", "present-model.gguf"), []byte("weights"), 0644)).To(Succeed())
rec := postJSON(app, "/v1/chat/completions",
`{"model":"local/present-model.gguf","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusOK))
})
})
Context("when no model is specified", func() {
It("passes through without checking", func() {
rec := postJSON(app, "/v1/chat/completions",
`{"messages":[{"role":"user","content":"hi"}]}`)
// No model name → middleware doesn't reject, handler runs
Expect(rec.Code).To(Equal(http.StatusOK))
})
})
})
// ---------------------------------------------------------------------------
// MergeOpenResponsesConfig — tool_choice parsing
// ---------------------------------------------------------------------------
//
// The OpenAI chat/completions spec nests the function name under "function":
//
// {"type":"function", "function":{"name":"my_function"}}
//
// The legacy Anthropic-compat shape puts it at the top level:
//
// {"type":"function", "name":"my_function"}
//
// Both need to reach SetFunctionCallNameString (not SetFunctionCallString,
// which is the mode field "none"/"auto"/"required").
//
// These specs assert both shapes populate the specific-function name and that
// downstream predicates (ShouldCallSpecificFunction, FunctionToCall) return
// the expected values so grammar-based forcing actually engages.
var _ = Describe("MergeOpenResponsesConfig tool_choice parsing", func() {
var cfg *config.ModelConfig
BeforeEach(func() {
cfg = &config.ModelConfig{}
})
Context("string tool_choice", func() {
It("sets mode to required for tool_choice=\"required\"", func() {
req := &schema.OpenResponsesRequest{ToolChoice: "required"}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
// "required" is a mode, not a specific function.
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
// ShouldUseFunctions must be true so tools are sent to the model.
Expect(cfg.ShouldUseFunctions()).To(BeTrue())
})
It("leaves config untouched for tool_choice=\"auto\"", func() {
req := &schema.OpenResponsesRequest{ToolChoice: "auto"}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
Expect(cfg.FunctionToCall()).To(Equal(""))
})
It("leaves config untouched for tool_choice=\"none\"", func() {
req := &schema.OpenResponsesRequest{ToolChoice: "none"}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
Expect(cfg.FunctionToCall()).To(Equal(""))
})
})
Context("specific-function tool_choice (OpenAI spec shape)", func() {
It("parses {type:function, function:{name:...}} and sets the specific-function name", func() {
req := &schema.OpenResponsesRequest{
ToolChoice: map[string]any{
"type": "function",
"function": map[string]any{"name": "get_weather"},
},
}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
// This is the key invariant the fix restores: a correctly-formed
// OpenAI tool_choice must result in ShouldCallSpecificFunction()=true.
Expect(cfg.ShouldCallSpecificFunction()).To(BeTrue())
Expect(cfg.FunctionToCall()).To(Equal("get_weather"))
})
It("prefers the nested function.name over a stray top-level name", func() {
// Defense-in-depth: both shapes present, OpenAI spec wins.
req := &schema.OpenResponsesRequest{
ToolChoice: map[string]any{
"type": "function",
"function": map[string]any{"name": "correct_name"},
"name": "legacy_name",
},
}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.FunctionToCall()).To(Equal("correct_name"))
})
})
Context("specific-function tool_choice (legacy Anthropic-compat shape)", func() {
It("parses {type:function, name:...} and sets the specific-function name", func() {
req := &schema.OpenResponsesRequest{
ToolChoice: map[string]any{
"type": "function",
"name": "get_weather",
},
}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeTrue())
Expect(cfg.FunctionToCall()).To(Equal("get_weather"))
})
})
Context("malformed tool_choice", func() {
It("is a no-op when type is missing", func() {
req := &schema.OpenResponsesRequest{
ToolChoice: map[string]any{
"function": map[string]any{"name": "get_weather"},
},
}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
})
It("is a no-op when type is not \"function\"", func() {
req := &schema.OpenResponsesRequest{
ToolChoice: map[string]any{
"type": "object",
"function": map[string]any{"name": "get_weather"},
},
}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
})
It("is a no-op when name is missing from both shapes", func() {
req := &schema.OpenResponsesRequest{
ToolChoice: map[string]any{
"type": "function",
"function": map[string]any{},
},
}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
Expect(cfg.FunctionToCall()).To(Equal(""))
})
It("is a no-op when name is empty string", func() {
req := &schema.OpenResponsesRequest{
ToolChoice: map[string]any{
"type": "function",
"function": map[string]any{"name": ""},
},
}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
})
})
Context("nil tool_choice", func() {
It("is a no-op", func() {
req := &schema.OpenResponsesRequest{ToolChoice: nil}
Expect(MergeOpenResponsesConfig(cfg, req)).To(Succeed())
Expect(cfg.ShouldCallSpecificFunction()).To(BeFalse())
Expect(cfg.FunctionToCall()).To(Equal(""))
})
})
})
// ---------------------------------------------------------------------------
// SetModelAndConfig + SetOpenAIRequest - /v1/chat/completions tool_choice parsing
// ---------------------------------------------------------------------------
//
// Parallel to the MergeOpenResponsesConfig specs above, but for the chat
// completions path. The parsing block lives in mergeOpenAIRequestAndModelConfig
// (called from SetOpenAIRequest), so these tests drive the full middleware
// chain the way the production /v1/chat/completions route does.
//
// What we assert per shape:
// - "required" -> ShouldUseFunctions=true, no specific name
// - "none" -> ShouldUseFunctions=false (tools disabled)
// - "auto" -> ShouldUseFunctions=true, no specific name
// - {type:function, function:{name:"X"}} (spec) -> ShouldCallSpecificFunction=true, FunctionToCall="X"
// - {type:function, name:"X"} (legacy) -> ShouldCallSpecificFunction=true, FunctionToCall="X"
// - nested+flat both present -> nested wins
// - malformed (no type / no name) -> no-op
var _ = Describe("SetModelAndConfig tool_choice parsing (chat completions)", func() {
var (
app *echo.Echo
modelDir string
capturedConfig *config.ModelConfig
)
BeforeEach(func() {
var err error
modelDir, err = os.MkdirTemp("", "localai-test-models-*")
Expect(err).ToNot(HaveOccurred())
cfgContent := []byte("name: test-model\nbackend: llama-cpp\n")
Expect(os.WriteFile(filepath.Join(modelDir, "test-model.yaml"), cfgContent, 0644)).To(Succeed())
ss := &system.SystemState{
Model: system.Model{ModelsPath: modelDir},
}
appConfig := config.NewApplicationConfig()
appConfig.SystemState = ss
mcl := config.NewModelConfigLoader(modelDir)
ml := model.NewModelLoader(ss)
re := NewRequestExtractor(mcl, ml, appConfig)
capturedConfig = nil
app = echo.New()
app.POST("/v1/chat/completions",
func(c echo.Context) error {
if cfg, ok := c.Get(CONTEXT_LOCALS_KEY_MODEL_CONFIG).(*config.ModelConfig); ok {
capturedConfig = cfg
}
return c.String(http.StatusOK, "ok")
},
re.SetModelAndConfig(func() schema.LocalAIRequest { return new(schema.OpenAIRequest) }),
func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if err := re.SetOpenAIRequest(c); err != nil {
return err
}
return next(c)
}
},
)
})
AfterEach(func() {
_ = os.RemoveAll(modelDir)
})
// chatReq wraps a tool_choice JSON fragment in a minimal valid chat-completions
// payload. The tools array is non-empty so downstream code paths that gate on
// len(input.Functions) see something to work with.
chatReq := func(toolChoiceJSON string) string {
return `{"model":"test-model",` +
`"messages":[{"role":"user","content":"hi"}],` +
`"tools":[{"type":"function","function":{"name":"get_weather"}}],` +
`"tool_choice":` + toolChoiceJSON + `}`
}
Context("string tool_choice", func() {
It("engages mode for tool_choice=\"required\"", func() {
rec := postJSON(app, "/v1/chat/completions", chatReq(`"required"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
Expect(capturedConfig.ShouldUseFunctions()).To(BeTrue())
})
It("disables tools for tool_choice=\"none\"", func() {
// Before #9559 this was a silent no-op (json.Unmarshal of "none"
// into functions.Tool failed); now "none" is honored per OpenAI spec.
rec := postJSON(app, "/v1/chat/completions", chatReq(`"none"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldUseFunctions()).To(BeFalse())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
})
It("leaves config untouched for tool_choice=\"auto\"", func() {
rec := postJSON(app, "/v1/chat/completions", chatReq(`"auto"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
// "auto" is the default: tools available, model decides.
Expect(capturedConfig.ShouldUseFunctions()).To(BeTrue())
Expect(capturedConfig.FunctionToCall()).To(Equal(""))
})
})
Context("specific-function tool_choice (OpenAI spec shape)", func() {
It("parses {type:function, function:{name:...}} and forces the named function", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReq(`{"type":"function","function":{"name":"get_weather"}}`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
// Key invariant: a correctly-formed OpenAI tool_choice must engage
// grammar-based forcing via SetFunctionCallNameString.
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeTrue())
Expect(capturedConfig.FunctionToCall()).To(Equal("get_weather"))
})
It("prefers the nested function.name over a stray top-level name", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReq(`{"type":"function","function":{"name":"correct_name"},"name":"legacy_name"}`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.FunctionToCall()).To(Equal("correct_name"))
})
})
Context("specific-function tool_choice (legacy Anthropic-compat shape)", func() {
It("parses {type:function, name:...} and forces the named function", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReq(`{"type":"function","name":"get_weather"}`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeTrue())
Expect(capturedConfig.FunctionToCall()).To(Equal("get_weather"))
})
})
// Some non-spec clients send the object form serialized as a JSON string.
// The pre-#9559 code accepted that by accident; this Context locks in
// continued tolerance so those clients do not silently regress.
Context("double-encoded tool_choice (JSON string of an object, non-spec)", func() {
It("parses a serialized OpenAI-spec nested object", func() {
// tool_choice value is itself a JSON-encoded string containing the
// object form. Use json.Marshal of the inner blob so the escapes
// are correct regardless of the test reader.
inner := `{"type":"function","function":{"name":"get_weather"}}`
encoded, err := json.Marshal(inner)
Expect(err).ToNot(HaveOccurred())
rec := postJSON(app, "/v1/chat/completions", chatReq(string(encoded)))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeTrue())
Expect(capturedConfig.FunctionToCall()).To(Equal("get_weather"))
})
It("parses a serialized legacy/Anthropic flat object", func() {
inner := `{"type":"function","name":"get_weather"}`
encoded, err := json.Marshal(inner)
Expect(err).ToNot(HaveOccurred())
rec := postJSON(app, "/v1/chat/completions", chatReq(string(encoded)))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeTrue())
Expect(capturedConfig.FunctionToCall()).To(Equal("get_weather"))
})
It("falls back to mode-string handling when the JSON string parses but has no usable name", func() {
// A JSON-string that decodes to a map without a function name
// should not engage specific-function forcing. We expect it to
// fall through to the mode-string path; the resulting mode is
// the raw blob (nonsense), but ShouldCallSpecificFunction stays
// false - the invariant that matters.
inner := `{"type":"function"}`
encoded, err := json.Marshal(inner)
Expect(err).ToNot(HaveOccurred())
rec := postJSON(app, "/v1/chat/completions", chatReq(string(encoded)))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
})
})
Context("malformed tool_choice", func() {
It("is a no-op when type is missing", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReq(`{"function":{"name":"get_weather"}}`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
})
It("is a no-op when type is not \"function\"", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReq(`{"type":"object","function":{"name":"get_weather"}}`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
})
It("is a no-op when name is missing from both shapes", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReq(`{"type":"function","function":{}}`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
Expect(capturedConfig.FunctionToCall()).To(Equal(""))
})
It("is a no-op when name is empty string", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReq(`{"type":"function","function":{"name":""}}`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
})
})
Context("nil tool_choice", func() {
It("is a no-op", func() {
rec := postJSON(app, "/v1/chat/completions",
`{"model":"test-model","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.ShouldCallSpecificFunction()).To(BeFalse())
Expect(capturedConfig.FunctionToCall()).To(Equal(""))
})
})
// OpenAI deprecated max_tokens in favour of max_completion_tokens
// (gpt-5 / o-series reject the legacy name). The middleware accepts
// both and collapses to the legacy internal Maxtokens field so
// downstream code reads exactly one.
Context("max_completion_tokens alias", func() {
chatReqMaxTokens := func(fields string) string {
return `{"model":"test-model",` +
`"messages":[{"role":"user","content":"hi"}],` +
fields + `}`
}
It("accepts the modern max_completion_tokens name", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReqMaxTokens(`"max_completion_tokens":64`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.Maxtokens).ToNot(BeNil())
Expect(*capturedConfig.Maxtokens).To(Equal(64))
})
It("still accepts the legacy max_tokens name", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReqMaxTokens(`"max_tokens":48`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.Maxtokens).ToNot(BeNil())
Expect(*capturedConfig.Maxtokens).To(Equal(48))
})
It("prefers max_completion_tokens when both are set", func() {
rec := postJSON(app, "/v1/chat/completions",
chatReqMaxTokens(`"max_tokens":48,"max_completion_tokens":64`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(capturedConfig).ToNot(BeNil())
Expect(capturedConfig.Maxtokens).ToNot(BeNil())
Expect(*capturedConfig.Maxtokens).To(Equal(64))
})
})
})
// These tests cover the per-request reasoning_effort -> enable_thinking mapping.
// The merge lives in mergeOpenAIRequestAndModelConfig (called from
// SetOpenAIRequest), so they drive the full middleware chain like the
// production /v1/chat/completions route does. The block builds its own app per
// test so the model config can be varied (some cases need reasoning.disable set
// in the model YAML to assert that an explicit config disable wins).
//
// Mapping under test (issue #10072):
// - reasoning_effort=none -> DisableReasoning=true
// - reasoning_effort=low/medium/high -> DisableReasoning=false, UNLESS the
// model config explicitly set true
// - empty / unrecognized -> no change
var _ = Describe("SetModelAndConfig reasoning_effort parsing (chat completions)", func() {
var modelDir string
BeforeEach(func() {
var err error
modelDir, err = os.MkdirTemp("", "localai-test-models-*")
Expect(err).ToNot(HaveOccurred())
})
AfterEach(func() {
_ = os.RemoveAll(modelDir)
})
// buildApp writes a model config with the given YAML body and returns an app
// plus a pointer to the captured per-request config.
buildApp := func(cfgYAML string) (*echo.Echo, **config.ModelConfig) {
Expect(os.WriteFile(filepath.Join(modelDir, "test-model.yaml"), []byte(cfgYAML), 0644)).To(Succeed())
ss := &system.SystemState{Model: system.Model{ModelsPath: modelDir}}
appConfig := config.NewApplicationConfig()
appConfig.SystemState = ss
mcl := config.NewModelConfigLoader(modelDir)
ml := model.NewModelLoader(ss)
re := NewRequestExtractor(mcl, ml, appConfig)
captured := new(*config.ModelConfig)
app := echo.New()
app.POST("/v1/chat/completions",
func(c echo.Context) error {
if cfg, ok := c.Get(CONTEXT_LOCALS_KEY_MODEL_CONFIG).(*config.ModelConfig); ok {
*captured = cfg
}
return c.String(http.StatusOK, "ok")
},
re.SetModelAndConfig(func() schema.LocalAIRequest { return new(schema.OpenAIRequest) }),
func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if err := re.SetOpenAIRequest(c); err != nil {
return err
}
return next(c)
}
},
)
return app, captured
}
chatReq := func(effort string) string {
return `{"model":"test-model",` +
`"messages":[{"role":"user","content":"hi"}],` +
`"reasoning_effort":` + effort + `}`
}
plainCfg := "name: test-model\nbackend: llama-cpp\n"
It("disables thinking for reasoning_effort=none", func() {
app, captured := buildApp(plainCfg)
rec := postJSON(app, "/v1/chat/completions", chatReq(`"none"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(*captured).ToNot(BeNil())
Expect((*captured).ReasoningConfig.DisableReasoning).ToNot(BeNil())
Expect(*(*captured).ReasoningConfig.DisableReasoning).To(BeTrue())
})
It("enables thinking for reasoning_effort=high when config is unset", func() {
app, captured := buildApp(plainCfg)
rec := postJSON(app, "/v1/chat/completions", chatReq(`"high"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(*captured).ToNot(BeNil())
Expect((*captured).ReasoningConfig.DisableReasoning).ToNot(BeNil())
Expect(*(*captured).ReasoningConfig.DisableReasoning).To(BeFalse())
})
It("enables thinking for reasoning_effort=high when config explicitly set false", func() {
app, captured := buildApp(plainCfg + "reasoning:\n disable: false\n")
rec := postJSON(app, "/v1/chat/completions", chatReq(`"high"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(*captured).ToNot(BeNil())
Expect((*captured).ReasoningConfig.DisableReasoning).ToNot(BeNil())
Expect(*(*captured).ReasoningConfig.DisableReasoning).To(BeFalse())
})
It("config wins: reasoning_effort=high cannot re-enable when config explicitly disabled", func() {
app, captured := buildApp(plainCfg + "reasoning:\n disable: true\n")
rec := postJSON(app, "/v1/chat/completions", chatReq(`"high"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(*captured).ToNot(BeNil())
Expect((*captured).ReasoningConfig.DisableReasoning).ToNot(BeNil())
Expect(*(*captured).ReasoningConfig.DisableReasoning).To(BeTrue())
})
It("is a no-op when reasoning_effort is empty", func() {
app, captured := buildApp(plainCfg)
rec := postJSON(app, "/v1/chat/completions",
`{"model":"test-model","messages":[{"role":"user","content":"hi"}]}`)
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(*captured).ToNot(BeNil())
Expect((*captured).ReasoningConfig.DisableReasoning).To(BeNil())
})
It("is case-insensitive (None disables, HIGH enables)", func() {
app, captured := buildApp(plainCfg)
rec := postJSON(app, "/v1/chat/completions", chatReq(`"None"`))
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(*captured).ToNot(BeNil())
Expect((*captured).ReasoningConfig.DisableReasoning).ToNot(BeNil())
Expect(*(*captured).ReasoningConfig.DisableReasoning).To(BeTrue())
app2, captured2 := buildApp(plainCfg)
rec2 := postJSON(app2, "/v1/chat/completions", chatReq(`"HIGH"`))
Expect(rec2.Code).To(Equal(http.StatusOK))
Expect(*captured2).ToNot(BeNil())
Expect((*captured2).ReasoningConfig.DisableReasoning).ToNot(BeNil())
Expect(*(*captured2).ReasoningConfig.DisableReasoning).To(BeFalse())
})
})