miau commited on
Commit
93b07ca
·
1 Parent(s): 39ac4ad

Optimize conversational turns on ZeroGPU

Browse files
Files changed (4) hide show
  1. README.md +4 -0
  2. app.py +58 -0
  3. openai_compat.py +21 -2
  4. test_openai_compat.py +19 -1
README.md CHANGED
@@ -55,3 +55,7 @@ a slow ZeroGPU generation does not block health checks or web-search requests.
55
  The aliases `gpt-5.6-luna-max`, `gpt-5.6-luna`, and `qwen-coder` all route to
56
  the same Qwen backend. Use the first alias for the Luna Max profile; use
57
  `qwen-coder` when a client requires the historical model name.
 
 
 
 
 
55
  The aliases `gpt-5.6-luna-max`, `gpt-5.6-luna`, and `qwen-coder` all route to
56
  the same Qwen backend. Use the first alias for the Luna Max profile; use
57
  `qwen-coder` when a client requires the historical model name.
58
+
59
+ Simple greetings such as `ola`/`olá` use a deterministic fast path and do not
60
+ queue a full 30B inference. Tool catalogs are also omitted from ordinary
61
+ conversation turns and retained when the request actually needs a tool.
app.py CHANGED
@@ -46,6 +46,7 @@ from generation import (
46
  from openai_compat import (
47
  analyze_tool_flow,
48
  indexed_tool_calls,
 
49
  normalize_tools,
50
  resolve_tool_choice,
51
  select_tools,
@@ -68,6 +69,14 @@ from web_search import SearchUnavailable, search_web
68
 
69
  logger = logging.getLogger("qwen-coder-api")
70
 
 
 
 
 
 
 
 
 
71
 
72
  # Qwen3-Coder 30B is trained for long-horizon agentic coding and native tool
73
  # use. Its official fine-grained FP8 checkpoint leaves enough runtime margin on
@@ -129,6 +138,12 @@ MAX_TOOL_CALL_TOKENS = int(os.getenv("MAX_TOOL_CALL_TOKENS", "2048"))
129
  MAX_TEMPERATURE = float(os.getenv("MAX_TEMPERATURE", "0.2"))
130
  PRESERVED_PREFIX_TOKENS = int(os.getenv("PRESERVED_PREFIX_TOKENS", "4096"))
131
  DEVICE = os.getenv("DEVICE", "cuda").strip() or "cuda"
 
 
 
 
 
 
132
 
133
  tokenizer = AutoTokenizer.from_pretrained(MODEL)
134
 
@@ -313,6 +328,7 @@ def gerar(
313
  "max_new_tokens": output_tokens,
314
  "do_sample": float(temperature) > 0,
315
  "pad_token_id": tokenizer.pad_token_id or tokenizer.eos_token_id,
 
316
  }
317
  if eos_token_ids is not None:
318
  generation_kwargs["eos_token_id"] = eos_token_ids
@@ -353,6 +369,48 @@ def _completion_payload(request: ChatCompletionRequest) -> dict[str, Any]:
353
  if request.model.casefold() not in _MODEL_ALIASES_CASEFOLDED:
354
  raise HTTPException(status_code=404, detail=f"Model not available: {request.model}")
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  already_adapted = has_tool_protocol(request.messages)
357
  flow_state = analyze_tool_flow(request.messages, request.tools or [])
358
  state_controls_choice = request.tool_choice is None or (
 
46
  from openai_compat import (
47
  analyze_tool_flow,
48
  indexed_tool_calls,
49
+ is_simple_greeting,
50
  normalize_tools,
51
  resolve_tool_choice,
52
  select_tools,
 
69
 
70
  logger = logging.getLogger("qwen-coder-api")
71
 
72
+ # Prefer the fastest safe CUDA kernels for the mixed-precision checkpoint.
73
+ # These flags do not change the FP8 weights or the public API contract.
74
+ torch.set_float32_matmul_precision("high")
75
+ if hasattr(torch.backends, "cuda"):
76
+ torch.backends.cuda.matmul.allow_tf32 = True
77
+ if hasattr(torch.backends, "cudnn"):
78
+ torch.backends.cudnn.allow_tf32 = True
79
+
80
 
81
  # Qwen3-Coder 30B is trained for long-horizon agentic coding and native tool
82
  # use. Its official fine-grained FP8 checkpoint leaves enough runtime margin on
 
138
  MAX_TEMPERATURE = float(os.getenv("MAX_TEMPERATURE", "0.2"))
139
  PRESERVED_PREFIX_TOKENS = int(os.getenv("PRESERVED_PREFIX_TOKENS", "4096"))
140
  DEVICE = os.getenv("DEVICE", "cuda").strip() or "cuda"
141
+ ENABLE_FAST_GREETING = os.getenv("ENABLE_FAST_GREETING", "1").casefold() not in {
142
+ "0",
143
+ "false",
144
+ "no",
145
+ "off",
146
+ }
147
 
148
  tokenizer = AutoTokenizer.from_pretrained(MODEL)
149
 
 
328
  "max_new_tokens": output_tokens,
329
  "do_sample": float(temperature) > 0,
330
  "pad_token_id": tokenizer.pad_token_id or tokenizer.eos_token_id,
331
+ "use_cache": True,
332
  }
333
  if eos_token_ids is not None:
334
  generation_kwargs["eos_token_id"] = eos_token_ids
 
369
  if request.model.casefold() not in _MODEL_ALIASES_CASEFOLDED:
370
  raise HTTPException(status_code=404, detail=f"Model not available: {request.model}")
371
 
372
+ # Avoid a full 30B inference for a greeting. OpenClaude includes its
373
+ # complete tool catalog in these turns, but there is no useful tool work.
374
+ # Keep this opt-out available for clients that want every turn model-backed.
375
+ explicit_tool_choice = request.tool_choice
376
+ has_tool_history = any(
377
+ isinstance(message, dict)
378
+ and (
379
+ message.get("role") == "tool"
380
+ or bool(message.get("tool_calls"))
381
+ )
382
+ for message in request.messages
383
+ )
384
+ if (
385
+ ENABLE_FAST_GREETING
386
+ and is_simple_greeting(request.messages)
387
+ and not has_tool_history
388
+ and (
389
+ explicit_tool_choice is None
390
+ or (
391
+ isinstance(explicit_tool_choice, str)
392
+ and explicit_tool_choice.casefold() == "auto"
393
+ )
394
+ )
395
+ ):
396
+ return {
397
+ "id": f"chatcmpl-{uuid.uuid4().hex}",
398
+ "object": "chat.completion",
399
+ "created": int(time.time()),
400
+ "model": request.model,
401
+ "choices": [
402
+ {
403
+ "index": 0,
404
+ "message": {
405
+ "role": "assistant",
406
+ "content": "Olá! Como posso ajudar você hoje?",
407
+ },
408
+ "finish_reason": "stop",
409
+ }
410
+ ],
411
+ "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
412
+ }
413
+
414
  already_adapted = has_tool_protocol(request.messages)
415
  flow_state = analyze_tool_flow(request.messages, request.tools or [])
416
  state_controls_choice = request.tool_choice is None or (
openai_compat.py CHANGED
@@ -119,6 +119,10 @@ NO_TOOLS_RE = re.compile(
119
  r"without"
120
  r")\s+(?:as?\s+)?(?:ferramentas?|tools?)\b"
121
  )
 
 
 
 
122
  OPENCLAUDE_METADATA_BLOCK_RE = re.compile(
123
  r"<(?P<tag>available-deferred-tools|system-reminder)\b[^>]*>.*?</(?P=tag)>",
124
  re.DOTALL | re.IGNORECASE,
@@ -338,6 +342,16 @@ def _latest_user_request(messages: object) -> str:
338
  return latest
339
 
340
 
 
 
 
 
 
 
 
 
 
 
341
  def _explicitly_disables_tools(messages: object) -> bool:
342
  if not isinstance(messages, list):
343
  return False
@@ -632,8 +646,13 @@ def resolve_tool_choice(
632
  """Override only auto/default choices; explicit client choices win."""
633
  if (
634
  state.reason == "no concrete tool action was requested"
635
- and isinstance(requested_choice, str)
636
- and requested_choice.casefold() == "required"
 
 
 
 
 
637
  ):
638
  return "none"
639
  is_auto = requested_choice is None or (
 
119
  r"without"
120
  r")\s+(?:as?\s+)?(?:ferramentas?|tools?)\b"
121
  )
122
+ SIMPLE_GREETING_RE = re.compile(
123
+ r"(?i)^\s*(?:oi|ol[aá]|hello|hi|hey|bom\s+dia|boa\s+tarde|boa\s+noite)"
124
+ r"[\s!,.?]*$"
125
+ )
126
  OPENCLAUDE_METADATA_BLOCK_RE = re.compile(
127
  r"<(?P<tag>available-deferred-tools|system-reminder)\b[^>]*>.*?</(?P=tag)>",
128
  re.DOTALL | re.IGNORECASE,
 
342
  return latest
343
 
344
 
345
+ def is_simple_greeting(messages: object) -> bool:
346
+ """Identify a greeting that does not need a model or tool prompt.
347
+
348
+ OpenClaude sends its complete tool catalog even for ``ola``. Calling a
349
+ 30B model for that turn adds tens of seconds on ZeroGPU without adding
350
+ useful work, so the API can answer it deterministically before inference.
351
+ """
352
+ return bool(SIMPLE_GREETING_RE.fullmatch(_latest_user_request(messages)))
353
+
354
+
355
  def _explicitly_disables_tools(messages: object) -> bool:
356
  if not isinstance(messages, list):
357
  return False
 
646
  """Override only auto/default choices; explicit client choices win."""
647
  if (
648
  state.reason == "no concrete tool action was requested"
649
+ and (
650
+ requested_choice is None
651
+ or (
652
+ isinstance(requested_choice, str)
653
+ and requested_choice.casefold() in {"auto", "required"}
654
+ )
655
+ )
656
  ):
657
  return "none"
658
  is_auto = requested_choice is None or (
test_openai_compat.py CHANGED
@@ -8,6 +8,7 @@ from openai_compat import (
8
  _tool_result_events,
9
  analyze_tool_flow,
10
  indexed_tool_calls,
 
11
  normalize_messages,
12
  normalize_tools,
13
  resolve_tool_choice,
@@ -144,8 +145,25 @@ class OpenAICompatibilityTests(unittest.TestCase):
144
  TOOLS,
145
  )
146
  self.assertFalse(state.active)
 
 
147
  self.assertEqual(resolve_tool_choice("required", state), "none")
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  def test_openclaude_metadata_does_not_become_user_intent(self) -> None:
150
  state = analyze_tool_flow(
151
  [
@@ -921,7 +939,7 @@ class OpenAICompatibilityTests(unittest.TestCase):
921
  [*TOOLS, EDIT_TOOL, *WEB_TOOLS],
922
  )
923
  self.assertFalse(state.active)
924
- self.assertIsNone(resolve_tool_choice(None, state))
925
 
926
 
927
  if __name__ == "__main__":
 
8
  _tool_result_events,
9
  analyze_tool_flow,
10
  indexed_tool_calls,
11
+ is_simple_greeting,
12
  normalize_messages,
13
  normalize_tools,
14
  resolve_tool_choice,
 
145
  TOOLS,
146
  )
147
  self.assertFalse(state.active)
148
+ self.assertEqual(resolve_tool_choice(None, state), "none")
149
+ self.assertEqual(resolve_tool_choice("auto", state), "none")
150
  self.assertEqual(resolve_tool_choice("required", state), "none")
151
 
152
+ def test_openclaude_greeting_metadata_is_fast_path_safe(self) -> None:
153
+ messages = [
154
+ {
155
+ "role": "user",
156
+ "content": (
157
+ "<available-deferred-tools>\nBash\n"
158
+ "</available-deferred-tools>\n"
159
+ "<system-reminder>Create code and run tests.</system-reminder>\n"
160
+ "ola\n<system-reminder>snip_id=x</system-reminder>"
161
+ ),
162
+ }
163
+ ]
164
+ self.assertTrue(is_simple_greeting(messages))
165
+ self.assertFalse(is_simple_greeting([{"role": "user", "content": "ola, leia app.py"}]))
166
+
167
  def test_openclaude_metadata_does_not_become_user_intent(self) -> None:
168
  state = analyze_tool_flow(
169
  [
 
939
  [*TOOLS, EDIT_TOOL, *WEB_TOOLS],
940
  )
941
  self.assertFalse(state.active)
942
+ self.assertEqual(resolve_tool_choice(None, state), "none")
943
 
944
 
945
  if __name__ == "__main__":