mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-27 10:20:54 +08:00
fix(llm): honor max_tokens_field in the connection test
The Test button on System -> LLM always sent the output cap as max_tokens, because POST /api/llm/test never read the profile's max_tokens_field. OpenAI reasoning models (o-series, GPT-5) reject max_tokens with unsupported_parameter, so a profile set to max_completion_tokens failed the test with HTTP 400 while conversations with the same profile worked. testLLM now accepts max_tokens_field from the form and falls back to the stored profile's value when the field is omitted (list-view test). It is normalized like profile saves: only the openai format with max_completion_tokens keeps it. The form passes its current selection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
3cb06383fd
commit
8e3d17136e
@@ -0,0 +1,125 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// The llm/test button must send the output cap under the key the profile is
|
||||
// configured with. OpenAI reasoning models reject max_tokens with
|
||||
// unsupported_parameter, so a profile set to max_completion_tokens used to fail
|
||||
// the connection test with a 400 while conversations with it worked.
|
||||
func TestLLMTestHonorsMaxTokensField(t *testing.T) {
|
||||
skipWithoutDSN(t)
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { m.Close() })
|
||||
if m.pg == nil {
|
||||
db.SkipNoPG(t)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
|
||||
var mu sync.Mutex
|
||||
var lastBody map[string]any
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
mu.Lock()
|
||||
lastBody = body
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"c","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`))
|
||||
}))
|
||||
t.Cleanup(fake.Close)
|
||||
|
||||
pid, err := m.pg.SaveProfile(&db.LLMProfile{
|
||||
Name: "mct-field", Format: "openai", Model: "gpt-x",
|
||||
BaseURL: fake.URL, APIKey: "k1", MaxTokensField: "max_completion_tokens",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = m.pg.Exec("DELETE FROM llm_profiles WHERE id=$1", pid) })
|
||||
|
||||
run := func(t *testing.T, form map[string]any) map[string]any {
|
||||
t.Helper()
|
||||
mu.Lock()
|
||||
lastBody = nil
|
||||
mu.Unlock()
|
||||
body, _ := json.Marshal(form)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/llm/test", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
s.testLLM(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("handler status %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if lastBody == nil {
|
||||
t.Fatalf("the test request never reached the endpoint: %s", rec.Body.String())
|
||||
}
|
||||
return lastBody
|
||||
}
|
||||
wantKey := func(t *testing.T, body map[string]any, want, absent string) {
|
||||
t.Helper()
|
||||
if _, ok := body[want]; !ok {
|
||||
t.Fatalf("request must carry %q, body keys: %v", want, bodyKeys(body))
|
||||
}
|
||||
if _, ok := body[absent]; ok {
|
||||
t.Fatalf("request must not carry %q, body keys: %v", absent, bodyKeys(body))
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("form value", func(t *testing.T) {
|
||||
body := run(t, map[string]any{
|
||||
"provider": "openai", "model": "gpt-x", "base_url": fake.URL,
|
||||
"api_key": "k1", "streaming": false, "max_tokens_field": "max_completion_tokens",
|
||||
})
|
||||
wantKey(t, body, "max_completion_tokens", "max_tokens")
|
||||
})
|
||||
|
||||
t.Run("stored profile fallback", func(t *testing.T) {
|
||||
// List-view test button: only the profile id, the field comes from the row.
|
||||
body := run(t, map[string]any{"profile_id": pid, "api_key": "", "streaming": false})
|
||||
wantKey(t, body, "max_completion_tokens", "max_tokens")
|
||||
})
|
||||
|
||||
t.Run("form override to default", func(t *testing.T) {
|
||||
// An explicit empty value in the form wins over the stored choice.
|
||||
body := run(t, map[string]any{
|
||||
"provider": "openai", "model": "gpt-x", "base_url": fake.URL,
|
||||
"api_key": "", "profile_id": pid, "streaming": false, "max_tokens_field": "",
|
||||
})
|
||||
wantKey(t, body, "max_tokens", "max_completion_tokens")
|
||||
})
|
||||
|
||||
t.Run("unknown value falls back to default", func(t *testing.T) {
|
||||
body := run(t, map[string]any{
|
||||
"provider": "openai", "model": "gpt-x", "base_url": fake.URL,
|
||||
"api_key": "k1", "streaming": false, "max_tokens_field": "bogus",
|
||||
})
|
||||
wantKey(t, body, "max_tokens", "max_completion_tokens")
|
||||
})
|
||||
}
|
||||
|
||||
func bodyKeys(m map[string]any) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1583,6 +1583,9 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) {
|
||||
SessionHeaderKey string `json:"session_header_key"` // non-empty = the test also sends this custom session header, with a one-off random session id as the value
|
||||
UserAgent string `json:"user_agent"` // non-empty = the test overrides the User-Agent header with this value (mirrors production)
|
||||
CustomHeaders string `json:"custom_headers"`
|
||||
// Which request key carries the output cap (openai format only): "" = max_tokens,
|
||||
// "max_completion_tokens" = the newer key. Omitted (nil) = the stored profile's choice.
|
||||
MaxTokensField *string `json:"max_tokens_field"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
@@ -1641,6 +1644,18 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) {
|
||||
if req.Streaming != nil {
|
||||
cfg.Stream = *req.Streaming
|
||||
}
|
||||
// The output-cap key follows the profile as well: OpenAI reasoning models reject
|
||||
// max_tokens with unsupported_parameter, so a profile set to max_completion_tokens
|
||||
// must be tested with that key, or the test 400s while conversations would work.
|
||||
// Same normalization as saving a profile: only openai + the known value survives.
|
||||
if req.MaxTokensField != nil {
|
||||
cfg.MaxTokensField = strings.TrimSpace(*req.MaxTokensField)
|
||||
} else if stored != nil {
|
||||
cfg.MaxTokensField = stored.MaxTokensField
|
||||
}
|
||||
if cfg.Format != llm.FormatOpenAI || cfg.MaxTokensField != llm.MaxTokensFieldCompletion {
|
||||
cfg.MaxTokensField = ""
|
||||
}
|
||||
// The custom session header name follows that profile too: when non-empty, the test request also sends it (value is a one-off random session id,
|
||||
// see TestConnection). Endpoints like opencode zen that mandate x-opencode-session return
|
||||
// 400 without it, so the test path must send it too — otherwise "chat works, test 400s".
|
||||
|
||||
@@ -449,6 +449,8 @@ function ProfileSheet({
|
||||
sessionHeaderKey.trim(),
|
||||
userAgent.trim(),
|
||||
customHeaders,
|
||||
// Test with the output-cap key the profile would actually send (OpenAI reasoning models reject max_tokens).
|
||||
format === "openai" ? toStore(maxTokensField) : "",
|
||||
);
|
||||
// Show the reply too: only when the model demonstrably spoke is this the same as working inside a session.
|
||||
if (r.ok)
|
||||
|
||||
@@ -1145,6 +1145,7 @@ export const api = {
|
||||
session_header_key = "", // non-empty = the test request also carries this custom session header (value is a one-off session id)
|
||||
user_agent = "", // non-empty = the test overrides the User-Agent header with this value
|
||||
custom_headers = "",
|
||||
max_tokens_field?: string, // ""=max_tokens | "max_completion_tokens"; omitted = the stored profile's choice
|
||||
) =>
|
||||
// reply = the model's actual reply (truncated); the backend marks a profile that replies with nothing as failed
|
||||
post<{ ok: boolean; error?: string; latency_ms?: number; model?: string; reply?: string }>("/llm/test", {
|
||||
@@ -1160,6 +1161,7 @@ export const api = {
|
||||
session_header_key,
|
||||
user_agent,
|
||||
custom_headers,
|
||||
max_tokens_field,
|
||||
}),
|
||||
llmProfiles: () => get<{ profiles: LLMProfile[] }>("/llm/profiles").then((r) => arr(r.profiles)),
|
||||
saveLLMProfile: (p: {
|
||||
|
||||
Reference in New Issue
Block a user