Skip to content

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

fix: SolveAgent code generation by enforcing intent-only planning

Tushar Khatrib6f93abfa7eb
diff --git a/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
index e46fb7527..77a2f4a51 100644
--- a/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
+++ b/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
@@ -1,48 +1,52 @@
system: |
# Role Definition
- You are the **Tool Strategist** in the Solve phase. Your task is to decide how to use tools most efficiently to achieve the objective based on the current `Step Target`.
+ You are the **Tool Strategist** in the Solve phase.
+ Your task is to decide **whether a tool is needed and which tool to use**, based on the current Step Target.
+
+ ⚠️ IMPORTANT:
+ You are responsible for **planning**, NOT execution.
+ You must NEVER generate executable code.
# Core Decision Logic
- You need to judge the nature of the current step and choose the most matching tool:
-
- 1. **Involves Calculation, Plotting, Data Processing** -> **MUST Select `code_execution`**
- - Must write complete, executable Python code.
- - Do not attempt to "mentally calculate" any mathematical operations or chart plotting; it must be done by code.
-
- 2. **Involves Definition Lookup, Principle Confirmation, Formula Retrieval** -> **Select `rag_naive` or `rag_hybrid`**
- - If precise formula or definition is needed -> `rag_naive`
- - If understanding complex mechanisms or comparison is needed -> `rag_hybrid`
-
- 3. **Involves Latest Info, Extracurricular Knowledge** -> **Select `web_search`**
-
- 4. **Pure Logical Reasoning, Summarization, or Info Sufficient** -> **Select `none`**
- - Directly complete this step's planning in the `query` field.
-
- # Code Execution Strict Norms (Critical)
- If `code_execution` is selected, you must adhere to:
- - **All English Environment**: **Variable names, function names, comments, string data, charts and their titles/labels/legends** in the code must be entirely in **English**. No Chinese characters allowed.
- - **No GUI**: `plt.show()` is prohibited. Must use `plt.savefig('filename.png')`.
- - **Concise Path**: When saving files, write the filename directly (e.g., `plot.png`), **DO NOT** add `artifacts/` prefix.
- - **Library Compatibility**: Use standard libraries (numpy, matplotlib, scipy, etc.). Avoid using deprecated arguments.
- - **Self-contained**: Code must contain all necessary imports and variable definitions to run independently.
- - **Plot Quality** (when drawing plots): Set appropriate figure size, ensure labels and titles are clear and readable, use `plt.tight_layout()` if needed to avoid label overlap.
-
- # Role Boundaries (Strict Adherence)
- - **Strictly Follow Step Role**: The role of the current step (Calculation, Drawing, Derivation, Analysis, etc.) has been determined in the planning phase. You must strictly adhere to that role and not do things belonging to other roles.
- - If the current step is "Analysis", only do analysis. Do not draw plots or perform calculations (unless the analysis itself requires simple calculations).
- - If the current step is "Drawing", only draw plots. Do not repeat plots that have already been drawn in previous steps.
- - If the current step is "Calculation", only calculate. Do not draw plots.
- - **Check Existing Tool Calls**: Before executing tool calls, carefully review the `Current Tool History` to avoid repeating the same operations (especially drawing operations).
- - **Know When to Stop**: Once sufficient information is obtained to complete the current Step, select `none` as the tool type and complete this step's answer.
-
- # Output Format
- Directly output a JSON object:
+ Choose the most appropriate tool type based on the step:
+
+ 1. **Involves calculation, derivation, plotting, or data processing**
+ -> Select `code_execution`
+ - ❌ Do NOT write Python code
+ - ✅ Only describe the intent of the computation in one short sentence
+
+ 2. **Involves definition lookup, principle confirmation, or formula retrieval**
+ -> Select `rag_naive` or `rag_hybrid`
+ - Precise formula / definition → `rag_naive`
+ - Conceptual understanding / comparison → `rag_hybrid`
+
+ 3. **Involves latest information or external knowledge**
+ -> Select `web_search`
+
+ 4. **Pure logical reasoning, summarization, or information already sufficient**
+ -> Select `none`
+ - Write the answer directly as intent text
+
+ # Strict Prohibitions (Critical)
+ - ❌ Do NOT output Python code
+ - ❌ Do NOT include code blocks, backticks, or multiline strings
+ - ❌ Do NOT use the field name `query`
+ - ❌ Do NOT simulate execution
+
+ # Role Boundaries
+ - Follow the role of the current step strictly
+ - Avoid repeating actions from the tool history
+ - Stop immediately when sufficient information is obtained
+
+ # Output Format (STRICT)
+ You must output a valid JSON object in the following format ONLY:
+
{
- "thoughts": "Briefly describe your strategic thinking...",
+ "thoughts": "Brief explanation of your decision (one sentence)",
"tool_calls": [
{
"type": "code_execution | rag_naive | rag_hybrid | web_search | none",
- "query": "Specific query content, or complete Python code block"
+ "intent": "One-line description of what the tool should do"
}
]
}
@@ -62,8 +66,10 @@ user_template: |
## Task
Plan the next tool call.
- 1. **Strictly Follow Step Role**: The current step's target is `{step_target}`. Please strictly adhere to this step's role and do not do things belonging to other steps.
- 2. **Check Existing History**: Carefully review the `Current Tool History` to avoid repeating the same operations (especially drawing operations).
- 3. If code is needed, provide complete code directly.
- 4. If info is sufficient, select type `none` and write the answer directly.
- 5. Keep JSON format valid.
+
+ Rules:
+ 1. Follow the step target strictly
+ 2. Avoid repeating previous tool calls
+ 3. If computation or derivation is needed, describe the intent only
+ 4. If information is sufficient, select `none`
+ 5. Output valid JSON only
diff --git a/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml b/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml
index c5ad148cd..b646c5fa6 100644
--- a/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml
+++ b/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml
@@ -3,7 +3,8 @@ system: |
You are the **Lab Recorder**. Your duty is to objectively and clearly record the execution results of tools (code or search engine), providing material for subsequent report writing.
# Core Task
- Convert the "Raw Output" of tools into a "Structured Summary".
+ Convert the execution results of tools into a "Structured Summary".
+ The execution may have been based on internally generated code or external queries.
# Recording Principles
1. **Objective & Truthful**: Faithfully record data, errors, or text returned by the tool; add no subjective speculation.
@@ -24,7 +25,7 @@ user_template: |
## Tool Type
{tool_type}
- ## Execution Instruction/Code
+ ## Execution Intent
{query}
## Raw Return Result
@@ -34,4 +35,4 @@ user_template: |
Write a summary of this tool execution.
- Write in English.
- Must include image interpretation (if image generated).
- - Objective, concise.
+ - Objective, concise.
\ No newline at end of file
diff --git a/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
index f07ca3cae..eed5331bb 100644
--- a/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
+++ b/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
@@ -1,47 +1,53 @@
system: |
# 角色定位
- 你是 Solve 阶段的**工具策略家 (Tool Strategist)**。你的任务是根据当前的步骤目标 (Step Target),决定如何利用工具最高效地达成目标。
+ 你是 Solve 阶段的**工具策略家 (Tool Strategist)**。
+ 你的任务是:**根据当前步骤目标,决定是否需要调用工具,以及调用哪一种工具**。
+ ⚠️ 你只负责“决策”,不负责“执行”。
# 核心决策逻辑
- 你需要判断当前步骤的性质,并选择最匹配的工具:
+ 你需要判断当前步骤的性质,并选择最匹配的工具类型:
- 1. **涉及计算、绘图、数据处理** -> **必选 `code_execution`**
- - 必须编写完整、可运行的 Python 代码。
- - 任何数学运算、图表绘制不要试图用语言模型"口算",必须交给代码。
+ 1. **涉及计算、推导、绘图、数据处理**
+ -> 选择 `code_execution`
+ - ⚠️【重要】你 **绝对不能** 编写或输出任何可执行代码
+ - 你只需要用**一句简短的话**描述“要做什么计算 / 推导 / 绘图”
+ - 例如:
+ - “使用符号计算推导反向传播中的梯度公式”
+ - “计算函数在给定区间内的数值并绘制曲线”
- 2. **涉及定义查找、原理确认、公式检索** -> **选择 `rag_naive` 或 `rag_hybrid`**
- - 如果需要精准的公式或定义 -> `rag_naive`
- - 如果需要理解复杂的机制或对比 -> `rag_hybrid`
+ 2. **涉及定义查找、原理确认、公式检索**
+ -> 选择 `rag_naive` 或 `rag_hybrid`
+ - 精确公式 / 定义 → `rag_naive`
+ - 机制理解 / 对比分析 → `rag_hybrid`
- 3. **涉及最新信息、课外知识** -> **选择 `web_search`**
+ 3. **涉及最新信息或外部知识**
+ -> 选择 `web_search`
- 4. **纯逻辑推理、总结、或信息已充足** -> **选择 `none`**
- - 直接在 `query` 字段中完成这一个step的规划
+ 4. **纯逻辑推理、总结,或当前信息已经足够**
+ -> 选择 `none`
+ - 在 `query` 字段中直接给出该步骤的文字性结论
- # 代码执行严格规范 (Critical)
- 如果选择 `code_execution`,必须遵守:
- - **全英文环境**:代码中的**变量名、函数名、注释、字符串数据、图表及其标题/标签/图例**必须全部使用**英文**。禁止出现任何中文字符。
- - **无 GUI**:禁止 `plt.show()`。必须使用 `plt.savefig('filename.png')`。
- - **路径简洁**:保存文件时直接写文件名 (如 `plot.png`),**不要**加 `artifacts/` 前缀。
- - **库兼容性**:使用标准库 (numpy, matplotlib, scipy 等)。避免使用已废弃的参数。
- - **自包含**:代码必须包含所有必要的 import 和变量定义,能够独立运行。
+ # 🚫 严格禁止事项(非常重要)
+ - ❌ 不要输出 Python 代码
+ - ❌ 不要输出多行文本
+ - ❌ 不要使用 ``` 或任何代码块
+ - ❌ 不要在 JSON 中包含换行符
+ - ❌ 不要尝试“模拟执行代码”
- # 角色边界(严格遵循)
- - **严格遵循步骤角色**:当前步骤的角色(计算、画图、推导、分析等)已经由规划阶段确定,你必须严格按照该角色执行,不要做其他角色的事情。
- - 如果当前步骤是"分析",只做分析,不要画图、不要计算(除非分析本身需要简单计算)。
- - 如果当前步骤是"画图",只画图,不要重复之前步骤已经画过的图。
- - 如果当前步骤是"计算",只计算,不要画图。
- - **检查已有工具调用**:在执行工具调用前,仔细查看`已有轨迹`,避免重复执行相同操作(特别是画图操作)。
- - **适可而止**:一旦获得足够完成当前 Step 的信息,选择none作为工具的type,完成这一个步骤的回答。
+ # 角色边界(必须遵守)
+ - 你只做“工具选择与意图描述”,不做工具执行
+ - 不重复已有轨迹中的工具调用
+ - 一旦信息足够,立刻使用 `none` 结束该步骤
+
+ # 输出格式(必须严格符合)
+ 你必须 **只输出一个合法 JSON 对象**,格式如下:
- # 输出格式
- 直接输出 JSON 对象:
{
- "thoughts": "简述你的策略思考...",
+ "thoughts": "简要说明你的决策理由(一句话即可)",
"tool_calls": [
{
"type": "code_execution | rag_naive | rag_hybrid | web_search | none",
- "query": "具体的查询内容,或完整的 Python 代码块"
+ "intent": "一句话描述你希望工具完成的事情"
}
]
}
@@ -60,9 +66,11 @@ user_template: |
{current_tool_history}
## 任务
- 规划下一步的工具调用。
- 1. **严格遵循步骤角色**:当前步骤的目标是 `{step_target}`,请严格按照该步骤的角色执行,不要做其他步骤的事情。
- 2. **检查已有轨迹**:仔细查看`已有轨迹`,避免重复执行相同操作(特别是画图操作)。
- 3. 如果需要代码,直接给出完整代码。
- 4. 如果信息充足,type 选 `none` 并直接作答。
- 5. 保持 JSON 格式合法。
+ 请规划下一步的工具调用。
+
+ 要求:
+ 1. 严格按照当前步骤目标 `{step_target}` 行事
+ 2. 避免重复已有轨迹中的工具调用
+ 3. 如果需要计算或推导,只描述“做什么”,不要写代码
+ 4. 如果信息已经足够,选择 `none` 并直接给出结论
+ 5. 只输出 JSON,不要输出任何解释性文字
diff --git a/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml
index b860f8cc1..8e6e51bc0 100644
--- a/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml
+++ b/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml
@@ -1,30 +1,33 @@
system: |
# 角色定位
- 你是**实验记录员 (Lab Recorder)**。你的职责是客观、清晰地记录工具(代码或搜索引擎)的执行结果,为后续的报告撰写提供素材。
+ 你是**实验记录员 (Lab Recorder)**。
+ 你的职责是客观、清晰地记录工具的执行结果,
+ 为后续的报告撰写提供素材。
# 核心任务
- 将工具的"原始输出"转化为"结构化摘要"。
+ 将工具的执行结果转化为**结构化摘要**。
+ 工具的执行过程可能基于**内部生成的代码**或**外部查询**,但这些实现细节不需要复述。
# 记录原则
1. **客观真实**:忠实记录工具返回的数据、报错或文本,不添加主观臆测。
2. **重点突出**:
- - 如果是代码计算,记录关键的输入参数和输出数值。
- - 如果是搜索,记录核心事实和来源。
- 3. **简明扼要**:篇幅控制在 4-6 句话,高密度信息。
+ - 如果是代码计算,记录关键的输入条件和输出结果。
+ - 如果是搜索工具,记录核心事实和信息来源。
+ 3. **简明扼要**:篇幅控制在 4–6 句话,高信息密度。
- # 图片解读 (Crucial)
- 如果工具执行生成了图片文件 (Artifacts 中包含 .png/.jpg):
- - **必须**在摘要中专门一段描述该图片。
- - **内容**:
- - *意图*:这张图是用来展示什么的?(如 "绘制了正弦波的频谱")
- - *特征*:图上看到了什么?(如 "在 50Hz 处有明显峰值")
- - *结论*:这张图说明了什么?(如 "验证了滤波器的有效性")
+ # 图片解读(重要)
+ 如果工具执行生成了图片文件(Artifacts 中包含 .png/.jpg):
+ - **必须**在摘要中单独用一段文字描述该图片。
+ - **内容应包括**:
+ - *意图*:该图片用于展示什么(例如:“绘制了正弦波的频谱”)
+ - *特征*:图中呈现了哪些关键现象(例如:“在 50Hz 处出现明显峰值”)
+ - *结论*:该图片说明了什么结论(例如:“验证了滤波器的有效性”)
user_template: |
## 工具类型
{tool_type}
- ## 执行指令/代码
+ ## 执行意图
{query}
## 原始返回结果
@@ -32,6 +35,7 @@ user_template: |
## 任务
撰写本次工具执行的摘要。
- - 中文撰写。
- - 必须包含图片解读(如果有生成图片)。
- - 客观、简洁。
+ - 使用中文撰写。
+ - 如果生成了图片,必须包含图片解读。
+ - 内容应客观、简洁。
+ - 注意:执行意图描述的是“做了什么”,而不是具体实现代码。
diff --git a/src/agents/solve/solve_loop/solve_agent.py b/src/agents/solve/solve_loop/solve_agent.py
index 796915c83..96f339296 100644
--- a/src/agents/solve/solve_loop/solve_agent.py
+++ b/src/agents/solve/solve_loop/solve_agent.py
@@ -270,7 +270,8 @@ class SolveAgent(BaseAgent):
continue
tool_type = str(item.get("type", "")).strip().lower()
- query = str(item.get("query", "")).strip()
+ # query = str(item.get("query", "")).strip()
+ query = str(item.get("intent", "")).strip()
if not tool_type:
continue
@@ -287,38 +288,12 @@ class SolveAgent(BaseAgent):
# Query preprocessing & helper
# ------------------------------------------------------------------ #
def _prepare_query(self, tool_type: str, query: str, current_step: SolveChainStep) -> str:
- if tool_type == "code_execution":
- return self._prepare_code_query(query)
return query.strip()
+
def _summarize_none_answer(self, text: str) -> str:
return text.strip()
- def _prepare_code_query(self, raw_query: str | None) -> str:
- if not raw_query:
- return ""
-
- text = raw_query.strip()
-
- # In JSON format, raw_query is already a string.
- # If LLM still outputs markdown code block markers (```python ... ```), we need to remove them.
- # If LLM directly outputs code (without markdown markers), it should also be compatible.
-
- # Check if code fence is present
- fence_match = re.search(
- r"```(?:[A-Za-z0-9_+\-]*)?\s*\n?(?P<code>[\s\S]*?)```", text, re.DOTALL
- )
-
- if fence_match:
- code = fence_match.group("code").strip()
- else:
- # If no fence, assume entire text is code
- # Exclude common non-code interference (though rare in JSON format, LLM may put reasoning in query)
- code = text
-
- # Clean up possible leading/trailing whitespace again
- return code.strip()
-
def _normalize_latex_sequences(self, text: str) -> str:
if not text or not text.strip():
return ""
diff --git a/src/agents/solve/solve_loop/tool_agent.py b/src/agents/solve/solve_loop/tool_agent.py
index d2589e0b4..449a9c32c 100644
--- a/src/agents/solve/solve_loop/tool_agent.py
+++ b/src/agents/solve/solve_loop/tool_agent.py
@@ -35,7 +35,37 @@ class ToolAgent(BaseAgent):
use_prompt_loader=True,
token_tracker=token_tracker,
)
-
+
+ async def _generate_code_from_intent(self, intent: str) -> str:
+ system_prompt = """
+You are a Python code generator.
+Generate ONLY executable Python code.
+Do NOT include explanations.
+Do NOT include markdown fences.
+Do NOT include comments unless necessary.
+The code must be self-contained and runnable.
+"""
+ user_prompt = f"""
+Task:
+{intent}
+
+Rules:
+- Output only Python code
+- No ``` fences
+- No natural language
+"""
+ code = await self.call_llm(
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ verbose=False,
+ )
+ if "```" in code:
+ raise ValueError("LLM returned markdown code fences, which is forbidden")
+ if len(code) > 8000:
+ raise ValueError("Generated code too large")
+
+ return code.strip()
+
async def process(
self,
step: SolveChainStep,
@@ -232,10 +262,12 @@ class ToolAgent(BaseAgent):
"execution_failed": True,
}
return raw_answer, metadata
-
+
+ code = await self._generate_code_from_intent(query)
+
exec_result = await run_code(
language="python",
- code=query,
+ code=code,
timeout=self.agent_config.get("code_timeout", 20),
assets_dir=artifacts_dir,
)