Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(llm): support MULTICA_LLM_DISABLE_THINKING env (MUL-7162) (#8657)
gogodjzhu1a09c65b1a94
diff --git a/.env.example b/.env.exampleindex b30e72bc27..0868943f29 100644--- a/.env.example+++ b/.env.example@@ -167,6 +167,20 @@ MULTICA_LLM_DEFAULT_MODEL=# other 4xx. This budget does not cover a stream that breaks mid-response,# and it is unrelated to task-level retries.MULTICA_LLM_MAX_RETRIES=+# - Ask an OpenAI-compatible gateway to turn the model's reasoning+# ("thinking") off by adding chat_template_kwargs: {"enable_thinking":+# false} to every request body this layer sends. Some gateways and+# GLM/Qwen-style model routes honor the field; there it removes the+# thinking pass that would otherwise dominate the latency budget of the+# assist calls above. Standard OpenAI endpoints reject unknown body+# fields, so only enable this when the upstream accepts it. GPT-5.6-family+# models already get reasoning_effort=none on the follow-up questions+# request. Chat auto-titling sends no reasoning field; this switch affects+# it only when the configured upstream accepts chat_template_kwargs.+# Accepted values are true/false and 1/0+# (case-insensitive); anything else fails the boot. The startup log+# ("llm retry policy") reports the effective state.+MULTICA_LLM_DISABLE_THINKING=MULTICA_DAEMON_CONFIG=MULTICA_WORKSPACE_ID=MULTICA_DAEMON_ID=diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 22396c8de1..6e6be9f550 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -206,9 +206,12 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s| `MULTICA_LLM_BASE_URL` | 空 | OpenAI 互換の endpoint || `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | リクエストがモデルを指定しない場合に使用 || `MULTICA_LLM_MAX_RETRIES` | `2` | 1 回の呼び出しあたりのリトライ上限。`0` はリトライ無効、`1`〜`5` は最大 N 回 |+| `MULTICA_LLM_DISABLE_THINKING` | `false` | すべてのリクエストに `chat_template_kwargs: {"enable_thinking": false}` を付加。このフィールドを解釈する gateway 用 |`MULTICA_LLM_MAX_RETRIES` はリトライポリシーの唯一の設定元です。未設定ならデフォルトの 2 回、`0` なら 1 回の呼び出しにつきリクエストは 1 回だけ、1〜5 ならリトライは最大その回数までになります。これは割り当てではなく上限です。消費するのはリトライ対象の失敗だけで、成功や呼び出し側自身のデッドラインによって早く終わることもあります。それ以外の値(負数、非数値、5 超過)は静かに補正されるのではなく起動に失敗します。上限はレイテンシ予算です。バックオフは 0.5 秒から始まり 8 秒を上限に倍増するため、これより大きい予算は呼び出し側自身のタイムアウトを超え、リトライ可能な失敗をタイムアウトに変えてしまいます。リトライの対象は接続失敗と HTTP 408、409、429、5xx で、それ以外の 4xx はそのまま返されます。サーバーは起動時に有効なポリシーを `llm retry policy` として記録しますが、その行に資格情報は含まれません。+`MULTICA_LLM_DISABLE_THINKING` は、モデルが推論(thinking)パスを実行してアシスト呼び出しのレイテンシ予算を食いつぶす gateway 向けの設定です。`true`(または `1`)にすると、サーバーはすべてのリクエストボディに `chat_template_kwargs: {"enable_thinking": false}` を付加します。このフィールドを転送する gateway(vLLM/sglang 系のデプロイや、GLM/Qwen 系の一部 LiteLLM ルート)は、thinking パスを省略します。標準の OpenAI endpoint は未知のボディフィールドを拒否するため、上流が受け付ける場合のみ有効にしてください。GPT-5.6 系モデルはフォローアップ質問のリクエストではサーバーが既に `reasoning_effort: none` を付けます。チャットの自動タイトル生成は推論フィールドを送信しません。本設定がそれに影響するのは、構成された上流が `chat_template_kwargs` を受け付ける場合だけです。指定できる値は `true`/`false` と `1`/`0`(大文字小文字を区別しない)で、それ以外は起動に失敗します。起動ログにはリトライポリシーと併せて有効な状態が記録されます。+このレイヤーを使う機能は 2 つあり、どちらも設定した endpoint にチャットの内容を送信します。- **会話タイトルの自動生成** — 新しいチャットセッションでユーザーが最初に送ったメッセージを、そのまま送信します。添付ファイルは含まれません。diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex a4ea346498..72eee39b0f 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -206,9 +206,12 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야| `MULTICA_LLM_BASE_URL` | 비어 있음 | OpenAI 호환 endpoint || `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | 요청에 모델이 지정되지 않았을 때 사용 || `MULTICA_LLM_MAX_RETRIES` | `2` | 호출당 재시도 상한. `0`은 재시도 비활성화, `1`–`5`는 최대 N회 |+| `MULTICA_LLM_DISABLE_THINKING` | `false` | 모든 요청에 `chat_template_kwargs: {"enable_thinking": false}`를 첨부. 해당 필드를 해석하는 gateway용 |`MULTICA_LLM_MAX_RETRIES`는 재시도 정책의 유일한 설정 소스입니다. 설정하지 않으면 기본값 2회, `0`이면 호출당 요청을 정확히 한 번만 보내고, 1–5면 재시도를 최대 그 횟수까지만 합니다. 할당량이 아니라 상한입니다. 재시도 대상 실패만 이를 소모하며, 성공하거나 호출자 자신의 데드라인에 걸리면 더 일찍 끝납니다. 그 밖의 값(음수, 숫자가 아닌 값, 5 초과)은 조용히 보정되지 않고 시작에 실패합니다. 상한은 지연 예산입니다. 백오프는 0.5초에서 시작해 8초 상한까지 두 배씩 늘어나므로, 더 큰 예산은 호출자 자신의 타임아웃을 넘겨 재시도 가능한 실패를 타임아웃으로 바꿉니다. 재시도는 연결 실패와 HTTP 408, 409, 429, 5xx를 대상으로 하며 그 외 4xx는 그대로 반환됩니다. 서버는 시작 시 유효한 정책을 `llm retry policy`로 기록하며 해당 줄에는 자격 증명이 포함되지 않습니다.+`MULTICA_LLM_DISABLE_THINKING`은 모델이 추론(thinking) 패스를 실행해 어시스트 호출의 지연 예산을 잠식하는 gateway를 위한 설정입니다. `true`(또는 `1`)로 설정하면 서버가 모든 요청 본문에 `chat_template_kwargs: {"enable_thinking": false}`를 첨부하며, 이 필드를 전달하는 gateway(vLLM/sglang 계열 배포, 일부 GLM/Qwen 계열 LiteLLM 라우트)는 thinking 패스를 건너뜁니다. 표준 OpenAI endpoint는 알 수 없는 본문 필드를 거부하므로, 업스트림이 이를 받아들이는 경우에만 활성화하세요. GPT-5.6 계열 모델은 후속 질문 요청에서 서버가 이미 `reasoning_effort: none`을 붙입니다. 채팅 자동 제목 생성은 추론 필드를 보내지 않습니다. 이 설정이 그것에 영향을 주는 것은 구성된 업스트림이 `chat_template_kwargs`를 받아들이는 경우뿐입니다. 허용되는 값은 `true`/`false`와 `1`/`0`(대소문자 구분 없음)이며, 그 외 값은 시작에 실패합니다. 시작 로그에 재시도 정책과 함께 유효 상태가 기록됩니다.+이 레이어를 사용하는 기능은 두 가지이며, 둘 다 설정한 endpoint로 채팅 내용을 전송합니다.- **대화 제목 자동 생성** — 새 채팅 세션에서 사용자가 보낸 첫 메시지를 그대로 전송합니다. 첨부 파일은 포함되지 않습니다.diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 6b8af5e1ee..63bcba7ee0 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -206,9 +206,12 @@ This group configures server-side assist generation, such as conversation titles| `MULTICA_LLM_BASE_URL` | empty | OpenAI-compatible endpoint || `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | Used when a request does not specify a model || `MULTICA_LLM_MAX_RETRIES` | `2` | Retry ceiling per call; `0` disables retries, `1`–`5` cap it at N |+| `MULTICA_LLM_DISABLE_THINKING` | `false` | Add `chat_template_kwargs: {"enable_thinking": false}` to every request, for gateways that honor the field |`MULTICA_LLM_MAX_RETRIES` is the single source for the retry policy. Leave it unset for the default of 2, set `0` to send exactly one request per call, or set 1–5 to cap retries at that many. It is a ceiling, not a quota: only retryable failures consume it, and a success or the caller's own deadline can end the call sooner. Any other value — negative, non-numeric, or above 5 — fails startup instead of being corrected silently. The ceiling is a latency budget: backoff starts at 0.5s and doubles to an 8s cap, so a larger budget would outlast the callers' own deadlines and turn a retryable failure into a timeout. Retries cover connection failures and HTTP 408, 409, 429 and 5xx; all other 4xx responses are returned as-is. The server logs the effective policy at startup as `llm retry policy`, with no credentials in the line.+`MULTICA_LLM_DISABLE_THINKING` is for gateways whose models spend a reasoning ("thinking") pass that dominates the latency budget of the assist calls. When set to `true` (or `1`), the server adds `chat_template_kwargs: {"enable_thinking": false}` to every request body; gateways that forward the field — vLLM/sglang-style deployments and some GLM/Qwen-style LiteLLM routes — then skip the thinking pass. Standard OpenAI endpoints reject unknown body fields, so only enable this when your upstream accepts it. GPT-5.6-family models already get `reasoning_effort: none` on the follow-up questions request. Chat auto-titling sends no reasoning field; this switch affects it only when the configured upstream accepts `chat_template_kwargs`. Accepted values are `true`/`false` and `1`/`0` (case-insensitive); anything else fails startup. The startup log reports the effective state alongside the retry policy.+Two features use this layer, and each one sends chat content to the endpoint you configure:- **Chat auto-titling** — the first user message of a new chat session, sent verbatim. Attachments are never included.diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex c9fc4e0b0d..ac9adc29e1 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -206,9 +206,12 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `MULTICA_LLM_BASE_URL` | 空 | OpenAI 兼容 endpoint || `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | 请求未指定模型时使用 || `MULTICA_LLM_MAX_RETRIES` | `2` | 单次调用的重试上限;`0` 表示禁用重试,`1`–`5` 表示最多重试 N 次 |+| `MULTICA_LLM_DISABLE_THINKING` | `false` | 在每个请求中附带 `chat_template_kwargs: {"enable_thinking": false}`,供支持该字段的网关关闭模型思考 |`MULTICA_LLM_MAX_RETRIES` 是重试策略的唯一配置源。不设置时使用默认的 2 次;设为 `0` 表示每次调用只发一个请求;设为 1–5 表示最多重试这么多次。它是上限而不是配额:只有可重试的失败才会消耗它,请求成功或调用方自身的超时都会让调用提前结束。其它取值(负数、非数字、大于 5)会让服务启动失败,而不是被静默纠正。上限是一个延迟预算:退避从 0.5s 开始翻倍,上限 8s,更大的预算会超出调用方自身的超时,把可重试的失败变成超时失败。重试覆盖连接失败以及 HTTP 408、409、429 和 5xx;其余 4xx 直接返回。服务启动时会以 `llm retry policy` 打印生效策略,其中不包含任何凭据。+`MULTICA_LLM_DISABLE_THINKING` 面向"模型会先跑一段推理(thinking)并吃掉辅助调用延迟预算"的网关。设为 `true`(或 `1`)时,服务端会在每个请求体中附带 `chat_template_kwargs: {"enable_thinking": false}`;支持透传该字段的网关(vLLM/sglang 类部署、部分 GLM/Qwen 系的 LiteLLM 路由)会因此跳过思考阶段。标准 OpenAI 端点会拒绝未知的请求体字段,所以仅在上游接受时启用。GPT-5.6 系模型在后续提问建议请求中已由服务端附带 `reasoning_effort: none`。会话自动命名不发送推理字段;只有当所配置的上游接受 `chat_template_kwargs` 时,此项才会影响它。可接受的取值为 `true`/`false` 和 `1`/`0`(不区分大小写);其它取值会让服务启动失败。启动日志会在重试策略旁打印生效状态。+有两个功能会使用这一层,它们都会把聊天内容发送到你配置的 endpoint:- **对话标题自动生成** —— 发送新对话中用户的第一条消息,原文发送。附件不会包含在内。diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 7673974817..c0b3db2880 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -156,10 +156,13 @@ services:# and callers fall back silently rather than failing. MULTICA_LLM_MAX_RETRIES# is the retry budget: unset = 2, 0 = disabled, 1-5 = an exact ceiling.# Anything else fails the boot instead of being silently corrected.+ # MULTICA_LLM_DISABLE_THINKING asks gateways that honor the field to+ # turn model reasoning off; see .env.example for the contract.MULTICA_LLM_API_KEY: ${MULTICA_LLM_API_KEY:-}MULTICA_LLM_BASE_URL: ${MULTICA_LLM_BASE_URL:-}MULTICA_LLM_DEFAULT_MODEL: ${MULTICA_LLM_DEFAULT_MODEL:-}MULTICA_LLM_MAX_RETRIES: ${MULTICA_LLM_MAX_RETRIES:-}+ MULTICA_LLM_DISABLE_THINKING: ${MULTICA_LLM_DISABLE_THINKING:-}# Lark / Feishu bot integration. MULTICA_LARK_SECRET_KEY is the# opt-in: unset = integration disabled. Mainland 飞书 and international# Lark are auto-detected per installation and served side by side, sodiff --git a/server/cmd/server/llm_retry_config_test.go b/server/cmd/server/llm_retry_config_test.goindex f70373677a..34d92acf1a 100644--- a/server/cmd/server/llm_retry_config_test.go+++ b/server/cmd/server/llm_retry_config_test.go@@ -97,4 +97,60 @@ func TestParsedLLMMaxRetriesReachesTheClient(t *testing.T) {}}+// TestParseLLMDisableThinking pins the MULTICA_LLM_DISABLE_THINKING states.+// Unset means the knob stays off — the state every existing deployment gets+// without the variable present — and anything that is not a deliberate+// true/false must stop the boot rather than be coerced (MUL-6364 contract).+func TestParseLLMDisableThinking(t *testing.T) {+ t.Run("accepted", func(t *testing.T) {+ for _, tc := range []struct {+ name string+ raw string+ want bool+ }{+ {name: "unset", raw: "", want: false},+ {name: "whitespace is unset", raw: " ", want: false},+ {name: "false", raw: "false", want: false},+ {name: "numeric false", raw: "0", want: false},+ {name: "true", raw: "true", want: true},+ {name: "numeric true", raw: "1", want: true},+ {name: "case-insensitive", raw: "TRUE", want: true},+ {name: "surrounding whitespace is tolerated", raw: " true ", want: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got, err := parseLLMDisableThinking(tc.raw)+ if err != nil {+ t.Fatalf("parseLLMDisableThinking(%q) failed: %v", tc.raw, err)+ }+ if got != tc.want {+ t.Fatalf("parseLLMDisableThinking(%q) = %v, want %v", tc.raw, got, tc.want)+ }+ })+ }+ })++ t.Run("rejected", func(t *testing.T) {+ for _, tc := range []struct {+ name string+ raw string+ }{+ {name: "typo", raw: "ture"},+ {name: "yes/no style", raw: "yes"},+ {name: "on/off style", raw: "on"},+ {name: "numeric non-boolean", raw: "2"},+ {name: "trailing garbage", raw: "true " + "x"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got, err := parseLLMDisableThinking(tc.raw)+ if err == nil {+ t.Fatalf("parseLLMDisableThinking(%q) accepted the value (= %v), want a validation error", tc.raw, got)+ }+ if !strings.Contains(err.Error(), strings.TrimSpace(tc.raw)) {+ t.Fatalf("parseLLMDisableThinking(%q) error = %q, want it to echo the offending value", tc.raw, err)+ }+ })+ }+ })+}+func ptr(n int) *int { return &n }diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex cf862d43f9..06164306ee 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -197,6 +197,25 @@ func parseLLMMaxRetries(raw string) (*llm.RetryOverride, error) {return override, nil}+// parseLLMDisableThinking turns the raw MULTICA_LLM_DISABLE_THINKING value+// into the bool llm.Config.DisableThinking expects. It follows the+// parseLLMMaxRetries contract: unset is a valid state (the knob stays off),+// and anything that does not read as a deliberate true/false stops the boot+// instead of being coerced — a typo'd "ture" that silently did nothing would+// leave an operator debugging latency the configuration claims to remove.+func parseLLMDisableThinking(raw string) (bool, error) {+ switch strings.ToLower(strings.TrimSpace(raw)) {+ case "":+ return false, nil+ case "1", "true":+ return true, nil+ case "0", "false":+ return false, nil+ default:+ return false, fmt.Errorf("must be a boolean (true/false or 1/0), got %q", raw)+ }+}+func envPositiveInt64(name string, def int64) int64 {raw := os.Getenv(name)if raw == "" {@@ -652,6 +671,14 @@ func main() {readRecorder = dbRoutingMetrics}+ // Same contract for the thinking-off hint: an unparseable value must stop+ // the boot rather than read as "disabled" and look configured.+ llmDisableThinking, err := parseLLMDisableThinking(os.Getenv("MULTICA_LLM_DISABLE_THINKING"))+ if err != nil {+ slog.Error("invalid MULTICA_LLM_DISABLE_THINKING", "error", err)+ os.Exit(1)+ }+r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{HTTPMetrics: httpMetrics,BusinessMetrics: businessMetrics,@@ -665,6 +692,7 @@ func main() {FeatureFlags: flags,HeartbeatScheduler: heartbeatScheduler,LLMMaxRetries: llmMaxRetries,+ LLMDisableThinking: llmDisableThinking,})var replicaQueries *db.Queriesif replicaPool != nil {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 1cb7b321d1..dc660efa19 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -254,6 +254,11 @@ type RouterOptions struct {// any test that happened to have the variable set. nil means unset, which// is what tests and NewRouter get.LLMMaxRetries *llm.RetryOverride+ // LLMDisableThinking carries the parsed MULTICA_LLM_DISABLE_THINKING+ // switch. It follows its LLMMaxRetries sibling in being injected rather+ // than read here, for the same fail-the-boot-in-main-only reason: the raw+ // value is validated by parseLLMDisableThinking before the router exists.+ LLMDisableThinking bool}func buildChannelSupervisor(@@ -436,6 +441,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusLLMBaseURL: strings.TrimSpace(os.Getenv("MULTICA_LLM_BASE_URL")),LLMDefaultModel: strings.TrimSpace(os.Getenv("MULTICA_LLM_DEFAULT_MODEL")),LLMMaxRetries: opts.LLMMaxRetries,+ LLMDisableThinking: opts.LLMDisableThinking,ServerVersion: normalizeServerVersion(version),}h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 4634b6acbe..25b478822f 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -135,6 +135,8 @@ type Config struct {// - LLMBaseURL -> MULTICA_LLM_BASE_URL (OpenAI or any compatible gateway)// - LLMDefaultModel -> MULTICA_LLM_DEFAULT_MODEL (used when a request omits `model`)// - LLMMaxRetries -> MULTICA_LLM_MAX_RETRIES (transport retry budget)+ // - LLMDisableThinking -> MULTICA_LLM_DISABLE_THINKING (gateway hint to+ // turn model reasoning off; see llm.Config.DisableThinking)LLMAPIKey stringLLMBaseURL stringLLMDefaultModel string@@ -144,6 +146,10 @@ type Config struct {// and cmd/server additionally fails the boot on an out-of-range value before// one reaches this struct. See llm.Config.MaxRetries for the full semantics.LLMMaxRetries *llm.RetryOverride+ // LLMDisableThinking is the parsed MULTICA_LLM_DISABLE_THINKING switch.+ // cmd/server validates the raw value before the boot continues, so a+ // non-boolean never reaches this struct.+ LLMDisableThinking bool// ServerVersion is the build version of the running API binary (the same// value main.go stamps via -X main.version and reports on /metrics).// Surfaced through /api/config so self-hosted operators can confirm which@@ -444,23 +450,27 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event}llmClient := llm.New(llm.Config{- APIKey: cfg.LLMAPIKey,- BaseURL: cfg.LLMBaseURL,- DefaultModel: cfg.LLMDefaultModel,- MaxRetries: cfg.LLMMaxRetries,+ APIKey: cfg.LLMAPIKey,+ BaseURL: cfg.LLMBaseURL,+ DefaultModel: cfg.LLMDefaultModel,+ MaxRetries: cfg.LLMMaxRetries,+ DisableThinking: cfg.LLMDisableThinking,})// Report the effective retry policy so an operator can confirm from the// boot log alone what a misbehaving upstream will cost, instead of inferring// it from an env var whose semantics used to be unguessable (MUL-6364).// Read off the client, not off cfg, so the line cannot drift from what the// SDK actually enforces. Counts and an enum only — never the key or the base- // URL, since a self-hosted gateway URL routinely embeds a token.+ // URL, since a self-hosted gateway URL routinely embeds a token. The+ // disable_thinking field rides along so the effective request shape is on+ // the same line.llmRetry := llmClient.RetryBudget()slog.Info("llm retry policy","max_retries", llmRetry.MaxRetries,"source", llmRetry.Source,"request_timeout", llmRetry.RequestTimeout,"enabled", llmClient.Enabled(),+ "disable_thinking", llmClient.DisableThinking(),)taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)diff --git a/server/pkg/llm/client.go b/server/pkg/llm/client.goindex ecffc0160d..c1c14f6fc7 100644--- a/server/pkg/llm/client.go+++ b/server/pkg/llm/client.go@@ -45,6 +45,14 @@// answered capped at 3000 runes (2000 head + 1000 tail) and each older// message at 800.//+// Request shape beyond the prompts is deployment-controlled and lives in+// Config: MaxRetries (transport budget) and DisableThinking, which appends+// `chat_template_kwargs: {"enable_thinking": false}` to every request body for+// gateways that honor it — some GLM/Qwen-style routes spend a thinking pass+// that dominates the assist calls' latency budget. Standard OpenAI endpoints+// reject unknown body fields, so the knob is opt-in per deployment and off by+// default.+//// Both consumers send private chat content, which is why an unconfigured// deployment making zero upstream requests is a contract rather than a side// effect: New with no API key and no base URL returns a disabled client whose@@ -145,6 +153,16 @@ type Config struct {// 6, so a budget larger than the caller's timeout only converts a// recoverable failure into a deadline-exceeded one.MaxRetries *RetryOverride+ // DisableThinking appends `chat_template_kwargs: {"enable_thinking": false}`+ // to every request body this client sends. Some OpenAI-compatible gateways+ // (vLLM/sglang-style deployments, and LiteLLM routes that forward the+ // field) honor it for GLM/Qwen-style models whose default thinking pass+ // would otherwise dominate the latency budget of the assist calls above.+ // Standard OpenAI endpoints reject unknown body fields, so this is opt-in+ // per deployment rather than automatic. It never touches reasoning_effort:+ // GPT-5.6-family models already get ReasoningEffortNone from GenerateJSON,+ // and this knob targets the gateways where that field is ignored instead.+ DisableThinking bool// HTTPClient, when set, replaces the SDK's default transport. Primarily a// test seam.HTTPClient option.HTTPClient@@ -215,10 +233,11 @@ type RetryBudget struct {// Client is a configured, reusable LLM caller. It is safe for concurrent use;// the underlying SDK client holds no per-request state.type Client struct {- sdk openai.Client- defaultModel string- enabled bool- retry RetryBudget+ sdk openai.Client+ defaultModel string+ enabled bool+ disableThinking bool+ retry RetryBudget}// New builds a Client from cfg. It never returns an error: an unconfigured@@ -248,6 +267,14 @@ func New(cfg Config) *Client {// Always set it explicitly, even for the default, so the budget the SDK// enforces and the one RetryBudget reports are the same number.opts = append(opts, option.WithMaxRetries(retry.MaxRetries))+ if cfg.DisableThinking {+ // Applied as a body mutation rather than a typed field:+ // chat_template_kwargs is not part of the Chat Completions schema, and+ // sjson merging cannot collide with any managed field (model, messages,+ // response_format, ...). The mutation runs after the typed body is+ // marshaled, so it survives every GenerateText/GenerateJSON shape.+ opts = append(opts, option.WithJSONSet("chat_template_kwargs", map[string]any{"enable_thinking": false}))+ }if cfg.HTTPClient != nil {opts = append(opts, option.WithHTTPClient(cfg.HTTPClient))}@@ -262,8 +289,9 @@ func New(cfg Config) *Client {defaultModel: defaultModel,// A deployment is "configured" if it gave us either a key or a base// URL. A bare base URL (no key) is valid for keyless local gateways.- enabled: strings.TrimSpace(cfg.APIKey) != "" || strings.TrimSpace(cfg.BaseURL) != "",- retry: retry,+ enabled: strings.TrimSpace(cfg.APIKey) != "" || strings.TrimSpace(cfg.BaseURL) != "",+ disableThinking: cfg.DisableThinking,+ retry: retry,}}@@ -280,6 +308,13 @@ func (c *Client) RetryBudget() RetryBudget {// Handlers use this to short-circuit with a 503 before doing any work.func (c *Client) Enabled() bool { return c != nil && c.enabled }+// DisableThinking reports whether the client appends the chat_template_kwargs+// thinking-off hint to every request it sends. It is read for the startup+// diagnostic line alongside RetryBudget so an operator can confirm the+// effective request shape from the boot log alone. Safe to log: it carries no+// credentials or URLs.+func (c *Client) DisableThinking() bool { return c != nil && c.disableThinking }+// DefaultModel returns the effective default model (never empty).func (c *Client) DefaultModel() string { return c.defaultModel }diff --git a/server/pkg/llm/client_test.go b/server/pkg/llm/client_test.goindex 5b68707321..3971eb296b 100644--- a/server/pkg/llm/client_test.go+++ b/server/pkg/llm/client_test.go@@ -178,6 +178,75 @@ func TestGenerateJSONUsesGPT56CompatibleParameters(t *testing.T) {}}+func TestDisableThinkingDefaultOmitsChatTemplateKwargs(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":"a title"},"finish_reason":"stop"}]}`)+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL})+ if c.DisableThinking() {+ t.Fatal("default config must report DisableThinking=false")+ }+ if _, err := c.GenerateText(context.Background(), "", "system", "hi"); err != nil {+ t.Fatalf("GenerateText failed: %v", err)+ }+ if _, ok := gotBody["chat_template_kwargs"]; ok {+ t.Fatalf("default config must not send chat_template_kwargs, got body %#v", gotBody)+ }+}++// TestDisableThinkingInjectsChatTemplateKwargs pins the request shape behind+// MULTICA_LLM_DISABLE_THINKING: the hint rides on every request the client+// makes — GenerateText (titles) and GenerateJSON (quick actions) alike — as a+// body mutation that must not disturb the fields the helpers manage+// themselves.+func TestDisableThinkingInjectsChatTemplateKwargs(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 {+ _, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"a title"},"finish_reason":"stop"}]}`)+ return+ }+ _, _ = io.WriteString(w, `{"id":"cmpl-2","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{\"actions\":[]}"},"finish_reason":"stop"}]}`)+ })++ c := New(Config{APIKey: "k", BaseURL: srv.URL, DefaultModel: "huya/glm-5.3-flash", DisableThinking: true})+ if !c.DisableThinking() {+ t.Fatal("expected DisableThinking to report true")+ }+ if _, err := c.GenerateText(context.Background(), "", "you are helpful", "make a title"); err != nil {+ t.Fatalf("GenerateText failed: %v", err)+ }+ // A non-GPT-5.6 model keeps the caller's temperature and gets no+ // reasoning_effort — the thinking-off hint must coexist with that shape.+ if _, err := c.GenerateJSON(context.Background(), "", "Return JSON.", "Generate actions.", 0.3, 2048); err != nil {+ t.Fatalf("GenerateJSON failed: %v", err)+ }+ if len(bodies) != 2 {+ t.Fatalf("expected two requests, got %d", len(bodies))+ }+ for i, body := range bodies {+ kwargs, ok := body["chat_template_kwargs"].(map[string]any)+ if !ok {+ t.Fatalf("request %d must carry chat_template_kwargs, got %#v", i+1, body)+ }+ if kwargs["enable_thinking"] != false {+ t.Fatalf("request %d must disable thinking, got %#v", i+1, kwargs)+ }+ }+ if bodies[1]["temperature"] != 0.3 {+ t.Fatalf("GenerateJSON must preserve temperature alongside the hint, got %#v", bodies[1])+ }+ if _, ok := bodies[1]["reasoning_effort"]; ok {+ t.Fatalf("non-GPT-5.6 models must not get reasoning_effort, got %#v", bodies[1])+ }+}+func TestGenerateJSONFallsBackToLegacyMaxTokens(t *testing.T) {var bodies []map[string]anysrv := stubUpstream(t, func(w http.ResponseWriter, body map[string]any) {