Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(visualize): unblock Gemini 2.5+, harden Visualize pipeline

Sam6c2615df39e6
diff --git a/deeptutor/agents/visualize/agents/code_generator_agent.py b/deeptutor/agents/visualize/agents/code_generator_agent.py
index 9110e4089..6f6aaf892 100644
--- a/deeptutor/agents/visualize/agents/code_generator_agent.py
+++ b/deeptutor/agents/visualize/agents/code_generator_agent.py
@@ -84,4 +84,25 @@ class CodeGeneratorAgent(BaseAgent):
if lowered.startswith("<!doctype") or lowered.startswith("<html"):
return stripped
+ # The renderers expect their payload to start cleanly with the right
+ # root tag. Models often wrap output with prose ("Here you go: <svg>…")
+ # or emit a code fence on the same line as the closing tag, which
+ # `extract_code_block`'s regex (requiring a leading \n before ```) does
+ # not strip. Trim to the outermost root tags as a defensive net.
+ if extracted:
+ if analysis.render_type == "svg":
+ lower = extracted.lower()
+ start = lower.find("<svg")
+ end = lower.rfind("</svg>")
+ if start != -1 and end != -1 and end > start:
+ extracted = extracted[start : end + len("</svg>")]
+ elif analysis.render_type == "html":
+ lower = extracted.lower()
+ start = lower.find("<!doctype")
+ if start == -1:
+ start = lower.find("<html")
+ end = lower.rfind("</html>")
+ if start != -1 and end != -1 and end > start:
+ extracted = extracted[start : end + len("</html>")]
+
return extracted
diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.py
index 845b56f52..151e737b2 100644
--- a/deeptutor/capabilities/visualize.py
+++ b/deeptutor/capabilities/visualize.py
@@ -8,6 +8,7 @@ Produces SVG or Chart.js code from user requests and conversation context.
from __future__ import annotations
+import logging
from typing import Any
from deeptutor.capabilities.request_contracts import get_capability_request_schema
@@ -16,6 +17,8 @@ from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import merge_trace_metadata
+logger = logging.getLogger(__name__)
+
class VisualizeCapability(BaseCapability):
manifest = CapabilityManifest(
@@ -135,24 +138,47 @@ class VisualizeCapability(BaseCapability):
source=self.name,
stage="reviewing",
)
- review = await pipeline.run_review(
- user_input=context.user_message,
- analysis=analysis,
- code=code,
- )
- final_code = review.optimized_code
- if review.changed:
- await stream.progress(
- message=f"Code optimized: {review.review_notes}",
- source=self.name,
- stage="reviewing",
+ from deeptutor.agents.visualize.models import ReviewResult
+
+ try:
+ review = await pipeline.run_review(
+ user_input=context.user_message,
+ analysis=analysis,
+ code=code,
)
- else:
+ except Exception as exc:
+ # Review wraps generated code inside a JSON string field;
+ # large/complex SVGs trip JSON-mode escaping and crash the
+ # whole turn. Fall back to the unreviewed draft so the user
+ # still gets a rendered result.
+ logger.warning(
+ "Visualize review failed (%s); using unreviewed draft.", exc
+ )
+ review = ReviewResult(
+ optimized_code=code,
+ changed=False,
+ review_notes=f"Review skipped due to error: {exc}",
+ )
+ final_code = code
await stream.progress(
- message="Code looks good — no changes needed.",
+ message="Review skipped — using draft as-is.",
source=self.name,
stage="reviewing",
)
+ else:
+ final_code = review.optimized_code
+ if review.changed:
+ await stream.progress(
+ message=f"Code optimized: {review.review_notes}",
+ source=self.name,
+ stage="reviewing",
+ )
+ else:
+ await stream.progress(
+ message="Code looks good — no changes needed.",
+ source=self.name,
+ stage="reviewing",
+ )
# Emit final content as a fenced code block for the chat area
if analysis.render_type == "svg":
diff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.py
index 2e9170103..e66e33988 100644
--- a/deeptutor/services/config/loader.py
+++ b/deeptutor/services/config/loader.py
@@ -231,6 +231,7 @@ def get_agent_params(module_name: str) -> dict:
"research": ("capabilities", "research"),
"question": ("capabilities", "question"),
"co_writer": ("capabilities", "co_writer"),
+ "visualize": ("capabilities", "visualize"),
"brainstorm": ("tools", "brainstorm"),
"vision_solver": ("plugins", "vision_solver"),
"math_animator": ("plugins", "math_animator"),
diff --git a/deeptutor/services/llm/cloud_provider.py b/deeptutor/services/llm/cloud_provider.py
index d98fbe865..a846f4578 100644
--- a/deeptutor/services/llm/cloud_provider.py
+++ b/deeptutor/services/llm/cloud_provider.py
@@ -349,6 +349,14 @@ async def _openai_complete(
effort.lower() == "minimal" and binding.lower() in _BINDINGS_WITH_EXTRA_BODY_THINKING
):
data["reasoning_effort"] = effort
+ elif (binding or "").lower() == "gemini" and any(
+ (model or "").lower().startswith(p) for p in ("gemini-2.5", "gemini-3")
+ ):
+ # Gemini 2.5+ models burn most of `max_tokens` on internal thinking by
+ # default, leaving too little headroom for the actual response and
+ # truncating with finish_reason=length. Disable thinking unless the
+ # caller explicitly asked for it.
+ data["reasoning_effort"] = "none"
timeout = aiohttp.ClientTimeout(total=120)
connector = _get_aiohttp_connector()
@@ -518,6 +526,14 @@ async def _openai_stream(
effort.lower() == "minimal" and binding.lower() in _BINDINGS_WITH_EXTRA_BODY_THINKING
):
data["reasoning_effort"] = effort
+ elif (binding or "").lower() == "gemini" and any(
+ (model or "").lower().startswith(p) for p in ("gemini-2.5", "gemini-3")
+ ):
+ # Gemini 2.5+ models burn most of `max_tokens` on internal thinking by
+ # default, leaving too little headroom for the actual response and
+ # truncating with finish_reason=length. Disable thinking unless the
+ # caller explicitly asked for it.
+ data["reasoning_effort"] = "none"
timeout = aiohttp.ClientTimeout(total=300)
connector = _get_aiohttp_connector()
diff --git a/deeptutor/services/llm/executors.py b/deeptutor/services/llm/executors.py
index a93fb6c2b..062ca9a95 100644
--- a/deeptutor/services/llm/executors.py
+++ b/deeptutor/services/llm/executors.py
@@ -178,6 +178,14 @@ async def sdk_complete(
if reasoning_effort:
payload["reasoning_effort"] = reasoning_effort
+ elif (provider_name or "").lower() == "gemini" and any(
+ (resolved_model or "").lower().startswith(p) for p in ("gemini-2.5", "gemini-3")
+ ):
+ # Gemini 2.5+ models burn most of `max_tokens` on internal "thinking"
+ # by default, often leaving zero room for the actual response and
+ # truncating with finish_reason=length. Disable thinking unless the
+ # caller explicitly opted in.
+ payload["reasoning_effort"] = "none"
payload.update(kwargs)
response = await _create_with_format_fallback(
@@ -246,6 +254,14 @@ async def sdk_stream(
if reasoning_effort:
payload["reasoning_effort"] = reasoning_effort
+ elif (provider_name or "").lower() == "gemini" and any(
+ (resolved_model or "").lower().startswith(p) for p in ("gemini-2.5", "gemini-3")
+ ):
+ # Gemini 2.5+ models burn most of `max_tokens` on internal "thinking"
+ # by default, often leaving zero room for the actual response and
+ # truncating with finish_reason=length. Disable thinking unless the
+ # caller explicitly opted in.
+ payload["reasoning_effort"] = "none"
payload.update(kwargs)
stream_response = await _create_with_format_fallback(
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index e188068c3..eafa99b84 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -313,6 +313,15 @@ class OpenAICompatProvider(LLMProvider):
if any(p.lower() in model_lower for p in spec.reasoning_model_patterns):
reasoning_effort = "high"
+ # Gemini 2.5+ models burn most of `max_tokens` on internal "thinking"
+ # by default, often leaving zero room for the actual response and
+ # truncating with finish_reason=length. Disable thinking unless the
+ # caller explicitly opted in.
+ if reasoning_effort is None and spec and spec.name == "gemini":
+ model_lower = model_name.lower()
+ if any(model_lower.startswith(p) for p in ("gemini-2.5", "gemini-3")):
+ reasoning_effort = "none"
+
semantic_effort: str | None = None
if isinstance(reasoning_effort, str):
semantic_effort = reasoning_effort.lower()
diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.py
index e38838422..efe4a0f0b 100644
--- a/deeptutor/services/setup/init.py
+++ b/deeptutor/services/setup/init.py
@@ -83,6 +83,7 @@ DEFAULT_AGENTS_SETTINGS = {
"research": {"temperature": 0.5, "max_tokens": 12000},
"question": {"temperature": 0.7, "max_tokens": 4096},
"co_writer": {"temperature": 0.7, "max_tokens": 4096},
+ "visualize": {"temperature": 0.4, "max_tokens": 16384},
"chat": {
"temperature": 0.2,
"responding": {"max_tokens": 8000},