Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(llm): make quick actions GPT-5.6 compatible (MUL-5573) (#6243)
Multica Eve33a2743f9345
diff --git a/server/internal/service/chat_quick_actions_generate.go b/server/internal/service/chat_quick_actions_generate.goindex d3d3618d7a..a2703766c5 100644--- a/server/internal/service/chat_quick_actions_generate.go+++ b/server/internal/service/chat_quick_actions_generate.go@@ -25,11 +25,12 @@ import (const (chatQuickActionsTimeout = 8 * time.SecondchatQuickActionsTemperature = 0.3- // Output cap. Three actions at the sanitizer's ceilings (80-rune label,- // 500-rune prompt) fit comfortably; the headroom exists so a verbose model- // is truncated by sanitizeChatQuickActions rather than by the upstream- // mid-JSON, which would fail the parse outright.- chatQuickActionsMaxTokens = 800+ // Output cap. GenerateJSON disables GPT-5.6 reasoning for this+ // latency-sensitive utility call, so the whole budget is available for the+ // JSON response. The headroom keeps verbose or multibyte actions from being+ // cut off mid-object; sanitizeChatQuickActions still applies the product's+ // visible size limits.+ chatQuickActionsMaxCompletionTokens = 2048)// Context window for the pass. Suggestions are about where the conversation@@ -86,7 +87,7 @@ const (// already degrades.type ChatQuickActionsLLM interface {Enabled() bool- GenerateJSON(ctx context.Context, model, systemPrompt, userPrompt string, temperature float64, maxTokens int64) (string, error)+ GenerateJSON(ctx context.Context, model, systemPrompt, userPrompt string, temperature float64, maxCompletionTokens int64) (string, error)}// chatQuickActionsSystemPrompt is the entire instruction set for the pass. It@@ -185,7 +186,7 @@ func (s *TaskService) GenerateChatQuickActionsForTask(ctx context.Context, taskchatQuickActionsSystemPrompt,prompt,chatQuickActionsTemperature,- chatQuickActionsMaxTokens,+ chatQuickActionsMaxCompletionTokens,)if err != nil {// Resolve the placeholder either way; only an explicit refresh reportsdiff --git a/server/pkg/llm/client.go b/server/pkg/llm/client.goindex 28d09f816c..655f959706 100644--- a/server/pkg/llm/client.go+++ b/server/pkg/llm/client.go@@ -29,6 +29,7 @@ import (openai "github.com/openai/openai-go/v3""github.com/openai/openai-go/v3/option"+ "github.com/openai/openai-go/v3/packages/param""github.com/openai/openai-go/v3/packages/ssestream""github.com/openai/openai-go/v3/shared")@@ -201,9 +202,15 @@ func (c *Client) GenerateText(ctx context.Context, model, systemPrompt, userProm// word "JSON" has to appear somewhere in the prompt, or OpenAI-compatible// endpoints reject the request outright.//-// temperature and maxTokens apply only when positive; zero leaves the upstream-// default in place. Model empty -> the configured default.-func (c *Client) GenerateJSON(ctx context.Context, model, systemPrompt, userPrompt string, temperature float64, maxTokens int64) (string, error) {+// This helper is for small, latency-sensitive utility work. For the GPT-5.6+// family it explicitly disables reasoning and leaves sampling controls at the+// model default. That keeps maxCompletionTokens available to the visible JSON+// instead of spending it on reasoning, and avoids sampling parameters that+// those models may reject. Other models keep the caller's temperature so a+// configurable deployment does not change behavior. temperature and+// maxCompletionTokens apply only when positive; zero leaves the corresponding+// upstream default in place. Model empty -> the configured default.+func (c *Client) GenerateJSON(ctx context.Context, model, systemPrompt, userPrompt string, temperature float64, maxCompletionTokens int64) (string, error) {if !c.Enabled() {return "", ErrNotConfigured}@@ -221,21 +228,83 @@ func (c *Client) GenerateJSON(ctx context.Context, model, systemPrompt, userPromOfJSONObject: &shared.ResponseFormatJSONObjectParam{},},}- if temperature > 0 {+ effectiveModel := strings.TrimSpace(model)+ if effectiveModel == "" {+ effectiveModel = c.defaultModel+ }+ if isGPT56Family(effectiveModel) {+ // GPT-5.6 defaults to medium reasoning. This path generates a tiny JSON+ // object under a strict wall-clock budget, so reasoning would add latency+ // and consume the completion-token limit without improving the contract.+ params.ReasoningEffort = shared.ReasoningEffortNone+ } else if temperature > 0 {params.Temperature = openai.Float(temperature)}- if maxTokens > 0 {- params.MaxTokens = openai.Int(maxTokens)+ if maxCompletionTokens > 0 {+ // max_tokens is deprecated and rejected by current reasoning models,+ // including the GPT-5.6 family. Prefer the replacement field for every+ // upstream; a narrow compatibility retry below covers older gateways+ // that have not implemented it yet.+ params.MaxCompletionTokens = openai.Int(maxCompletionTokens)}- completion, err := c.Chat(ctx, params)- if err != nil {- return "", err+ // The preferred request and its optional compatibility retry share one+ // deadline, so a legacy gateway cannot double the caller's time budget.+ ctx, cancel := withDefaultTimeout(ctx)+ defer cancel()++ // Some older OpenAI-compatible gateways have not implemented one or both+ // modern fields. Negotiate only when the upstream explicitly identifies an+ // unsupported parameter: validation fails before generation, and each field+ // can be removed or replaced at most once under the shared deadline.+ var completion *openai.ChatCompletion+ for compatibilityRetries := 0; ; compatibilityRetries++ {+ var err error+ completion, err = c.Chat(ctx, params)+ if err == nil {+ break+ }+ if compatibilityRetries >= 2 {+ return "", err+ }++ switch {+ case params.MaxCompletionTokens.Valid() && isUnsupportedParameter(err, "max_completion_tokens"):+ params.MaxCompletionTokens = param.Opt[int64]{}+ params.MaxTokens = openai.Int(maxCompletionTokens)+ case params.ReasoningEffort != "" && isUnsupportedParameter(err, "reasoning_effort"):+ params.ReasoningEffort = ""+ default:+ return "", err+ }}if len(completion.Choices) == 0 {return "", errors.New("llm: upstream returned no choices")}- return completion.Choices[0].Message.Content, nil+ choice := completion.Choices[0]+ if choice.FinishReason == "length" {+ return "", errors.New("llm: upstream reached the max completion token limit before producing complete JSON")+ }+ if strings.TrimSpace(choice.Message.Content) == "" {+ return "", errors.New("llm: upstream returned empty JSON content")+ }+ return choice.Message.Content, nil+}++func isUnsupportedParameter(err error, parameter string) bool {+ var apiErr *openai.Error+ if !errors.As(err, &apiErr) ||+ apiErr.StatusCode != http.StatusBadRequest ||+ apiErr.Param != parameter {+ return false+ }+ return apiErr.Code == "unsupported_parameter" ||+ (apiErr.Code == "" && strings.HasPrefix(strings.ToLower(strings.TrimSpace(apiErr.Message)), "unsupported parameter"))+}++func isGPT56Family(model string) bool {+ model = strings.ToLower(strings.TrimSpace(model))+ return model == "gpt-5.6" || strings.HasPrefix(model, "gpt-5.6-")}// withDefaultTimeout returns ctx unchanged (with a no-op cancel) when it alreadydiff --git a/server/pkg/llm/client_test.go b/server/pkg/llm/client_test.goindex c8abbc41db..086bc53640 100644--- a/server/pkg/llm/client_test.go+++ b/server/pkg/llm/client_test.go@@ -132,6 +132,195 @@ func TestGenerateText(t *testing.T) {}}+func TestGenerateJSONUsesGPT56CompatibleParameters(t *testing.T) {+ var gotBody map[string]any+ srv := stubUpstream(t, func(w http.ResponseWriter, body map[string]any) {+ gotBody = body+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{\"actions\":[]}"},"finish_reason":"stop"}]}`)+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL, DefaultModel: "gpt-5.6-luna"})+ out, err := c.GenerateJSON(context.Background(), "", "Return JSON.", "Generate actions.", 0.3, 2048)+ if err != nil {+ t.Fatalf("GenerateJSON failed: %v", err)+ }+ if out != `{"actions":[]}` {+ t.Fatalf("unexpected output %q", out)+ }+ if gotBody["max_completion_tokens"] != float64(2048) {+ t.Fatalf("expected max_completion_tokens=2048, got %#v", gotBody["max_completion_tokens"])+ }+ if _, ok := gotBody["max_tokens"]; ok {+ t.Fatalf("deprecated max_tokens must be omitted, got body %#v", gotBody)+ }+ if gotBody["reasoning_effort"] != "none" {+ t.Fatalf("expected reasoning_effort=none, got body %#v", gotBody)+ }+ if _, ok := gotBody["temperature"]; ok {+ t.Fatalf("temperature must be omitted for reasoning-model compatibility, got body %#v", gotBody)+ }+ if gotBody["model"] != "gpt-5.6-luna" {+ t.Fatalf("expected configured GPT-5.6 model, got body %#v", gotBody)+ }+}++func TestGenerateJSONFallsBackToLegacyMaxTokens(t *testing.T) {+ var bodies []map[string]any+ srv := stubUpstream(t, func(w http.ResponseWriter, body map[string]any) {+ bodies = append(bodies, body)+ w.Header().Set("Content-Type", "application/json")+ if len(bodies) == 1 {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":{"message":"Unsupported parameter: max_completion_tokens","type":"invalid_request_error","param":"max_completion_tokens","code":"unsupported_parameter"}}`)+ return+ }+ _, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{\"actions\":[]}"},"finish_reason":"stop"}]}`)+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})+ if _, err := c.GenerateJSON(context.Background(), "legacy-model", "Return JSON.", "Generate actions.", 0.3, 800); err != nil {+ t.Fatalf("GenerateJSON failed: %v", err)+ }+ if len(bodies) != 2 {+ t.Fatalf("expected one compatibility retry, got %d requests", len(bodies))+ }+ if bodies[0]["max_completion_tokens"] != float64(800) {+ t.Fatalf("first request must use max_completion_tokens, got %#v", bodies[0])+ }+ if _, ok := bodies[0]["max_tokens"]; ok {+ t.Fatalf("first request must omit max_tokens, got %#v", bodies[0])+ }+ if bodies[1]["max_tokens"] != float64(800) {+ t.Fatalf("fallback request must use max_tokens, got %#v", bodies[1])+ }+ if _, ok := bodies[1]["max_completion_tokens"]; ok {+ t.Fatalf("fallback request must omit max_completion_tokens, got %#v", bodies[1])+ }+ if bodies[1]["temperature"] != 0.3 {+ t.Fatalf("non-GPT-5.6 models must preserve temperature, got %#v", bodies[1])+ }+}++func TestGenerateJSONFallsBackFromUnsupportedReasoningEffort(t *testing.T) {+ var bodies []map[string]any+ srv := stubUpstream(t, func(w http.ResponseWriter, body map[string]any) {+ bodies = append(bodies, body)+ w.Header().Set("Content-Type", "application/json")+ if len(bodies) == 1 {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":{"message":"Unsupported parameter: reasoning_effort","type":"invalid_request_error","param":"reasoning_effort","code":"unsupported_parameter"}}`)+ return+ }+ _, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{\"actions\":[]}"},"finish_reason":"stop"}]}`)+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})+ if _, err := c.GenerateJSON(context.Background(), "gpt-5.6-luna", "Return JSON.", "Generate actions.", 0.3, 800); err != nil {+ t.Fatalf("GenerateJSON failed: %v", err)+ }+ if len(bodies) != 2 {+ t.Fatalf("expected one compatibility retry, got %d requests", len(bodies))+ }+ if bodies[0]["reasoning_effort"] != "none" {+ t.Fatalf("first request must disable reasoning, got %#v", bodies[0])+ }+ if _, ok := bodies[1]["reasoning_effort"]; ok {+ t.Fatalf("fallback request must omit reasoning_effort, got %#v", bodies[1])+ }+ if bodies[1]["max_completion_tokens"] != float64(800) {+ t.Fatalf("fallback must preserve the preferred token field, got %#v", bodies[1])+ }+}++func TestGenerateJSONNegotiatesBothLegacyParameters(t *testing.T) {+ var bodies []map[string]any+ srv := stubUpstream(t, func(w http.ResponseWriter, body map[string]any) {+ bodies = append(bodies, body)+ w.Header().Set("Content-Type", "application/json")+ switch len(bodies) {+ case 1:+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":{"message":"Unsupported parameter: max_completion_tokens","type":"invalid_request_error","param":"max_completion_tokens","code":"unsupported_parameter"}}`)+ case 2:+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":{"message":"Unsupported parameter: reasoning_effort","type":"invalid_request_error","param":"reasoning_effort","code":"unsupported_parameter"}}`)+ default:+ _, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{\"actions\":[]}"},"finish_reason":"stop"}]}`)+ }+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})+ if _, err := c.GenerateJSON(context.Background(), "gpt-5.6-luna", "Return JSON.", "Generate actions.", 0.3, 800); err != nil {+ t.Fatalf("GenerateJSON failed: %v", err)+ }+ if len(bodies) != 3 {+ t.Fatalf("expected two bounded compatibility retries, got %d requests", len(bodies))+ }+ last := bodies[2]+ if last["max_tokens"] != float64(800) {+ t.Fatalf("final request must use max_tokens, got %#v", last)+ }+ if _, ok := last["max_completion_tokens"]; ok {+ t.Fatalf("final request must omit max_completion_tokens, got %#v", last)+ }+ if _, ok := last["reasoning_effort"]; ok {+ t.Fatalf("final request must omit reasoning_effort, got %#v", last)+ }+}++func TestGenerateJSONDoesNotRetryInvalidTokenLimit(t *testing.T) {+ requests := 0+ srv := stubUpstream(t, func(w http.ResponseWriter, _ map[string]any) {+ requests+++ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":{"message":"Invalid max_completion_tokens value","type":"invalid_request_error","param":"max_completion_tokens","code":"invalid_value"}}`)+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})+ if _, err := c.GenerateJSON(context.Background(), "gpt-5.6-luna", "Return JSON.", "Generate actions.", 0.3, 800); err == nil {+ t.Fatal("expected invalid token limit error")+ }+ if requests != 1 {+ t.Fatalf("invalid values must not trigger a compatibility retry, got %d requests", requests)+ }+}++func TestGenerateJSONRejectsIncompleteOrEmptyOutput(t *testing.T) {+ for _, tc := range []struct {+ name string+ content string+ finishReason string+ wantError string+ }{+ {name: "token limit", content: "", finishReason: "length", wantError: "max completion token limit"},+ {name: "empty content", content: " ", finishReason: "stop", wantError: "empty JSON content"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ srv := stubUpstream(t, func(w http.ResponseWriter, _ map[string]any) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":`+mustJSON(t, tc.content)+`},"finish_reason":`+mustJSON(t, tc.finishReason)+`}]}`)+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL})+ _, err := c.GenerateJSON(context.Background(), "gpt-5.6-luna", "Return JSON.", "Generate actions.", 0.3, 800)+ if err == nil || !strings.Contains(err.Error(), tc.wantError) {+ t.Fatalf("error = %v, want substring %q", err, tc.wantError)+ }+ })+ }+}++func mustJSON(t *testing.T, value string) string {+ t.Helper()+ raw, err := json.Marshal(value)+ if err != nil {+ t.Fatalf("marshal test value: %v", err)+ }+ return string(raw)+}+func TestChatStream(t *testing.T) {srv := stubUpstream(t, func(w http.ResponseWriter, _ map[string]any) {w.Header().Set("Content-Type", "text/event-stream")