Merge pull request #1025 from evan188199-tech/codex/fix/code-execution-file-artifacts

This commit is contained in:
Bingxi Zhao
2026-08-29 11:50:04 +08:00
committed by GitHub
16 changed files with 180 additions and 41 deletions
@@ -70,17 +70,19 @@ loop:
That tool-less reply is shown to the user as the answer and ends the
loop, so write it for the reader: use concise Markdown and clear teaching
language, do not mention these internal mechanics or repeat your working
notes verbatim, and include any artifact URLs (e.g. from exec) you
collected. Build the answer on the conversation above — the gathered
notes verbatim, and refer to generated artifacts exactly as the tool result
lists them. Build the answer on the conversation above — the gathered
evidence, memory, persona, and attached sources.
If a skill listed in the Skills block matches the task, call read_skill
before attempting that workflow, then follow the skill instructions.
When a skill or request involves scripts or downloadable files (PDFs,
images, spreadsheets, archives), save them in the turn workspace and run
commands with exec; the exec result lists Generated artifacts with URLs —
cite those URLs in the final answer. If an extended tool is listed but
not loaded, call load_tools first with the exact tool name.
When a skill or request involves Python scripts or downloadable files
(PDFs, images, spreadsheets, archives), pass complete source to
code_execution and save outputs in the turn workspace. Use exec only for
genuinely shell-only commands; never embed Python source in `python -c`
or a heredoc. The tool result lists generated artifacts explicitly —
without that list, do not claim a file was created. If an extended tool is
listed but not loaded, call load_tools first with the exact tool name.
Tool names, parameter names, source ids, knowledge-base names, notebook
ids, and skill names must be copied verbatim from the prompt blocks or
@@ -50,12 +50,14 @@ loop:
当材料已经足够——或这个请求根本不需要工具时——就停止调用工具,直接写出面向用户的最终回答。
这条不带工具调用的回复会作为正式答案呈现给用户并结束循环,所以要为读者而写:用简洁 Markdown
和清晰的教学语言,不要提及这些内部机制、也不要逐字复述你的工作笔记,并带上你收集到的 artifact URL
(如 exec 生成的文件)。基于上面的对话——已收集的证据、记忆、persona 和附件来源——作答。
和清晰的教学语言,不要提及这些内部机制、也不要逐字复述你的工作笔记,并按工具结果原样引用生成文件。
基于上面的对话——已收集的证据、记忆、persona 和附件来源——作答。
如果 Skills 区域里有匹配任务的 skill,先调用 read_skill 再执行该工作流,并遵循 skill 的指示。
当 skill 或请求涉及脚本或可下载文件(PDF、图片、表格、压缩包)时,把文件保存在本轮工作区并用 exec 运行命令;
exec 结果会列出带 URL 的 Generated artifacts——在最终回答里引用这些 URL。
当 skill 或请求涉及 Python 脚本或可下载文件(PDF、图片、表格、压缩包)时,把完整源码传给
code_execution,并把输出保存到本轮工作区。exec 只用于真正必须使用 shell 的命令;
绝不要把 Python 源码嵌进 `python -c` 或 heredoc。工具结果会明确列出生成文件;
没有这个清单就不要宣称已创建文件。
如果 Extended Tools 里列出的工具尚未加载,先用精确工具名调用 load_tools。
工具名、参数名、source id、知识库名、笔记本 id 和 skill 名必须从提示词块或工具 schema 中逐字复制,
@@ -4,7 +4,7 @@ You are solving a problem end to end. Be rigorous: plan, work each step with the
FIRST, before doing anything else, call `solve_plan` with a short analysis and an ordered list of steps (2-6 for most problems; a single step is fine for a trivial one). Never start solving before you have called `solve_plan`.
Then work the plan one step at a time:
- Do the step's actual work with the available tools — `code_execution` for calculation / plotting / numeric checks, `rag` / `read_source` when materials are attached, `web_search` / `web_fetch` for facts you don't know, `reason` for a hard sub-derivation, `exec` to produce a file (a worked-solution PDF, a chart, a spreadsheet).
- Do the step's actual work with the available tools — `code_execution` for calculation / plotting / numeric checks and Python-generated files (a worked-solution PDF, a chart, a spreadsheet), `rag` / `read_source` when materials are attached, `web_search` / `web_fetch` for facts you don't know, `reason` for a hard sub-derivation, and `exec` only for genuinely shell-only commands.
- For a problem with a diagram, or a geometry problem where a figure helps, call `geogebra_analysis` to reconstruct the figure as a GeoGebra applet, then solve using it.
- After finishing a step, call `solve_finish_step` with its id and a short summary of what it established. This records the result and frees up context. Do not skip steps; do not mark a step done before its work is actually complete.
@@ -4,7 +4,7 @@
**第一件事**:在做任何事之前,先调用 `solve_plan`,给出简短分析和一个有序的步骤列表(多数题目 2-6 步;很简单的题一步也行)。在调用 `solve_plan` 之前,绝不开始求解。
然后按计划逐步推进,一次一步:
- 用合适的工具真正完成这一步的工作——`code_execution` 做计算/作图/数值验算,`rag` / `read_source` 在挂了材料时检索,`web_search` / `web_fetch` 查你不确定的事实,`reason` 做一段困难的子推导,`exec` 生成文件(解题 PDF、图表、表格)。
- 用合适的工具真正完成这一步的工作——`code_execution` 做计算/作图/数值验算以及用 Python 生成文件(解题 PDF、图表、表格),`rag` / `read_source` 在挂了材料时检索,`web_search` / `web_fetch` 查你不确定的事实,`reason` 做一段困难的子推导,`exec` 只用于真正必须使用 shell 的命令。
- 带配图的题、或画个图有助于理解的几何题,调用 `geogebra_analysis` 把图形还原成 GeoGebra 图形,再据此求解。
- 完成一步后,调用 `solve_finish_step`,传入步骤 id 和这一步结论的简短总结。这会记录结果并释放上下文。不要跳步;不要在工作真正完成前就把步骤标记为完成。
+1 -1
View File
@@ -83,7 +83,7 @@ def render_artifacts_for_tool(artifacts: list[SandboxArtifact]) -> str:
"""
if not artifacts:
return ""
return "No generated artifacts were found in the workspace."
lines = [
"Generated artifacts (now saved — shown to the user as download cards):",
*[
+1 -1
View File
@@ -20,7 +20,7 @@ A `.docx` is a ZIP of XML parts. Body text lives in `word/document.xml`. Two tie
- **Advanced — raw OOXML via `zipfile`**: only for what python-docx cannot express — tracked changes (redlines), comments, and exact-fidelity edits that must preserve every untouched byte. See [Raw OOXML](#raw-ooxml-advanced).
Work in the current directory (uploaded files land here). Write output to a new filename; don't overwrite the source.
After `exec` completes, use the Generated artifacts URL from the tool result in the final answer so the user can download the document.
Run Python through `code_execution`, save output in the current directory, and refer to the document exactly as the Generated artifacts list names it. Use `exec` only for a genuinely shell-only command; never put this source in `python -c` or a heredoc.
## Read / extract
+2 -2
View File
@@ -19,8 +19,8 @@ Work PDFs in the sandbox with preinstalled Python libs. Pick the library by task
- **Fill forms** → `pypdf` (fillable AcroForm fields) or annotation overlay (flat forms).
- **Create from scratch** → `reportlab`.
Write a short Python snippet and run it via `exec`. Save outputs to the workspace dir.
After `exec` completes, use the Generated artifacts URL from the tool result in the final answer so the user can download the PDF.
Write complete Python source and run it via `code_execution`. Save outputs to the workspace dir.
After execution, refer to the PDF exactly as the Generated artifacts list names it. Use `exec` only for a genuinely shell-only command; never put this source in `python -c` or a heredoc.
## Extract text and tables (pdfplumber)
+4 -4
View File
@@ -17,10 +17,10 @@ Work with PowerPoint `.pptx` files using **python-pptx** (preinstalled). A `.ppt
is a ZIP of XML parts; python-pptx handles the structure so you rarely touch XML.
Drop to raw OOXML only for the few things the library can't express (see Advanced).
All work happens in the sandbox `exec` shell, in the current workspace dir where
uploaded files land. Write a short Python heredoc or temp `.py` and run it.
After `exec` completes, use the Generated artifacts URL from the tool result in
the final answer so the user can download the deck.
Run complete Python source with `code_execution` in the current workspace dir
where uploaded files land. Refer to the deck exactly as the Generated artifacts
list names it. Use `exec` only for a genuinely shell-only command; never put
this source in `python -c` or a heredoc.
## Mental model
- A presentation has **slides**; each slide is built from a **layout**; layouts
+5 -4
View File
@@ -14,10 +14,11 @@ requires:
# Excel (.xlsx) workbooks
Work in the workspace dir (where uploads land) by writing short Python run via
`exec`. Two libraries, both preinstalled — pick by task:
After `exec` completes, use the Generated artifacts URL from the tool result in
the final answer so the user can download the workbook.
Work in the workspace dir (where uploads land) by running complete Python
source via `code_execution`. Two libraries, both preinstalled — pick by task:
Refer to the workbook exactly as the Generated artifacts list names it. Use
`exec` only for a genuinely shell-only command; never put this source in
`python -c` or a heredoc.
- **pandas** — bulk tabular read/write/analysis. Use for "load this sheet,
compute, dump a table". Drops all formatting and formulas.
+5 -4
View File
@@ -340,10 +340,11 @@ class CodeExecutionTool(_PromptHintsMixin, BaseTool):
name="code_execution",
description=(
"Run a code snippet in an isolated sandbox and return its "
"stdout/stderr. Pass complete, ready-to-run source in `code` "
"and pick `language` (python, c, or cpp). Use for calculation, "
"algorithm checking, and numerical verification — print results "
"to stdout. Not a substitute for explaining your reasoning."
"stdout/stderr plus any files generated in the workspace. Pass "
"complete, ready-to-run source in `code` and pick `language` "
"(python, c, or cpp). Use it for calculation, data processing, "
"and code-generated deliverables instead of embedding source in "
"an exec command. Print concise results to stdout."
),
parameters=[
ToolParameter(
@@ -1,12 +1,12 @@
short_description: "Run a code snippet (python/c/cpp) in an isolated sandbox; returns stdout/stderr."
when_to_use: "Use when computation, algorithm checking, or numerical verification is more reliable than mental calculation."
short_description: "Run a code snippet (python/c/cpp) in an isolated sandbox; returns stdout/stderr and generated files."
when_to_use: "Use for computation, verification, data processing, or creating a file with Python instead of embedding source in a shell command."
input_format: "`language` (python, c, or cpp) + `code` — the complete, ready-to-run source. Optional `stdin` and `timeout` (seconds, default 30)."
guideline: "Write complete source yourself and print results to stdout. Use code execution for objective verification, not as a substitute for explaining reasoning."
guideline: "Write complete source yourself, save output files to the working directory, and print a concise completion message. Never run this source through exec with `python -c` or a heredoc; use exec only for a command that is genuinely shell-only."
note: "Runs in this turn's workspace under the same OS-isolated sandbox as `exec`; unavailable when no sandbox backend is configured. Save generated files to the working directory to surface them as artifacts."
phase: "verification"
aliases:
- name: run_code
description: "Run a code snippet (python/c/cpp) for calculation, verification, or visualization."
description: "Run a code snippet (python/c/cpp) for calculation, verification, visualization, or file generation."
input_format: "`language` + `code`; optional `stdin`, `timeout`."
when_to_use: "Use for objective checks, quick calculations, or small experiments."
when_to_use: "Use for objective checks, quick calculations, small experiments, or Python-generated files."
phase: "verification"
+1 -1
View File
@@ -1,6 +1,6 @@
short_description: "Run a shell command inside an isolated sandbox; returns stdout/stderr + exit code."
when_to_use: "For data processing, running a skill's bundled scripts, or invoking CLI tools the task needs. Not for destructive or system-management commands."
input_format: "`command` — the shell command. Optional `timeout` — seconds (default 30, max 300). Runs in this turn's workspace directory."
guideline: "Prefer non-interactive flags (e.g. `-y`). Keep output small; pipe through `head`/`grep` when a command is chatty. Read a skill's SKILL.md before running its scripts. If the user asks you to create/export a file, run the command, save the file in the workspace, then include any Generated artifacts URL from the tool result in your final answer."
guideline: "Prefer non-interactive flags (e.g. `-y`). Keep output small; pipe through `head`/`grep` when a command is chatty. Read a skill's SKILL.md before running its scripts. For Python work or file generation, pass complete source to code_execution instead of `python -c` or a heredoc; use exec only for genuinely shell-only commands. Refer to generated artifacts exactly as the tool result lists them."
note: "Destructive patterns (rm -rf, mkfs, shutdown, …) are blocked. The sandbox confines filesystem and network access; commands that need the open internet may fail."
phase: "expansion"
@@ -1,12 +1,12 @@
short_description: "在隔离沙箱中运行一段代码(python/c/cpp),返回 stdout/stderr。"
when_to_use: "当计算、算法校验或数值验证比纯手算更可靠时使用。"
short_description: "在隔离沙箱中运行一段代码(python/c/cpp),返回 stdout/stderr 和生成文件。"
when_to_use: "用于计算、校验、数据处理,或用 Python 生成文件,而不是把源码嵌进 shell 命令。"
input_format: "`language`(python、c 或 cpp)+ `code`——完整、可直接运行的源码。可选 `stdin` 与 `timeout`(秒,默认 30)。"
guideline: "自行写出完整源码并把结果打印到 stdout;代码执行适合做客观验证,不应替代文字解释。"
guideline: "自行写出完整源码,把输出文件保存到当前工作目录,并打印简短完成信息。绝不要通过 exec 的 `python -c` 或 heredoc 运行这段源码;exec 只用于真正必须使用 shell 的命令。"
note: "在本回合 workspace 内运行,与 `exec` 共用同一套 OS 级隔离沙箱;未配置沙箱后端时不可用。把生成文件保存到工作目录即可作为产物输出。"
phase: "verification"
aliases:
- name: run_code
description: "运行一段代码(python/c/cpp),用于计算、验证或可视化。"
description: "运行一段代码(python/c/cpp),用于计算、验证、可视化或生成文件。"
input_format: "`language` + `code`;可选 `stdin`、`timeout`。"
when_to_use: "适合做客观校验、快速计算或小规模实验。"
when_to_use: "适合做客观校验、快速计算、小规模实验或用 Python 生成文件。"
phase: "verification"
+1 -1
View File
@@ -1,6 +1,6 @@
short_description: "在隔离沙箱中执行 shell 命令,返回 stdout/stderr 与退出码。"
when_to_use: "用于数据处理、运行技能自带脚本、调用任务所需的 CLI 工具。不要用于破坏性或系统管理类命令。"
input_format: "`command` — shell 命令。可选 `timeout` — 秒(默认 30,上限 300)。命令运行在本回合的工作目录中。"
guideline: "优先使用非交互参数(如 `-y`)。控制输出体量,命令过于啰嗦时用 `head`/`grep` 过滤。运行技能脚本前先读其 SKILL.md。若用户要求创建/导出文件,执行命令并把文件保存到工作目录,然后在最终回答中给出工具结果里的 Generated artifacts 下载链接。"
guideline: "优先使用非交互参数(如 `-y`)。控制输出体量,命令过于啰嗦时用 `head`/`grep` 过滤。运行技能脚本前先读其 SKILL.md。Python 工作或文件生成应把完整源码传给 code_execution,不要用 `python -c` 或 heredoc;exec 只用于真正必须使用 shell 的命令。最终回答按工具结果原样引用生成文件。"
note: "破坏性命令(rm -rf、mkfs、shutdown 等)会被拦截。沙箱限制文件与网络访问,需要公网的命令可能失败。"
phase: "expansion"
+59
View File
@@ -104,6 +104,35 @@ async def test_exec_tool_reports_generated_public_artifacts(
assert result.sources[0]["url"].endswith("/report.pdf")
@pytest.mark.asyncio
async def test_exec_tool_reports_missing_artifacts_after_success(
tmp_path, monkeypatch: pytest.MonkeyPatch
) -> None:
path_service = PathService(workspace_root=tmp_path / "data")
workdir = path_service.get_task_workspace("chat", "turn_1") / "exec"
workdir.mkdir(parents=True, exist_ok=True)
class FakeSandboxService:
async def run(self, request, *, user_id: str):
return ExecResult(stdout="done\n", exit_code=0)
import deeptutor.services.sandbox as sandbox_pkg
import deeptutor.services.sandbox.artifacts as sandbox_artifacts
monkeypatch.setattr(sandbox_pkg, "get_sandbox_service", lambda: FakeSandboxService())
monkeypatch.setattr(sandbox_artifacts, "get_path_service", lambda: path_service)
result = await ExecTool().execute(
command="python build_pdf.py",
_sandbox_user_id="user-1",
_sandbox_workdir=str(workdir),
)
assert result.success is True
assert "No generated artifacts were found in the workspace." in result.content
assert result.metadata["artifacts"] == []
@pytest.mark.asyncio
async def test_brainstorm_tool_passes_llm_arguments(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, Any] = {}
@@ -269,6 +298,36 @@ async def test_code_execution_tool_runs_python_via_sandbox(
assert "main.py" not in artifact_names
@pytest.mark.asyncio
async def test_code_execution_tool_warns_when_no_artifacts_are_generated(
tmp_path, monkeypatch: pytest.MonkeyPatch
) -> None:
path_service = PathService(workspace_root=tmp_path / "data")
workdir = path_service.get_task_workspace("chat", "turn_1") / "code_runs"
class FakeSandboxService:
async def run(self, request, *, user_id: str):
return ExecResult(stdout="PDF created\n", exit_code=0)
import deeptutor.services.sandbox as sandbox_pkg
import deeptutor.services.sandbox.artifacts as sandbox_artifacts
monkeypatch.setattr(sandbox_pkg, "get_sandbox_service", lambda: FakeSandboxService())
monkeypatch.setattr(sandbox_artifacts, "get_path_service", lambda: path_service)
result = await CodeExecutionTool().execute(
language="python",
code="print('PDF created')",
_sandbox_user_id="user-1",
_sandbox_workdir=str(workdir),
)
assert result.success is True
assert "No generated artifacts were found in the workspace." in result.content
assert result.metadata["artifacts"] == []
assert result.sources == []
@pytest.mark.asyncio
async def test_code_execution_tool_compiles_cpp(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
from pathlib import Path
@@ -0,0 +1,74 @@
from __future__ import annotations
from pathlib import Path
import yaml
from deeptutor.tools.builtin import CodeExecutionTool
from deeptutor.tools.prompting import load_prompt_hints
def test_code_execution_schema_and_hints_cover_file_generation() -> None:
definition = CodeExecutionTool().get_definition()
hint = load_prompt_hints("code_execution", language="en")
exec_hint = load_prompt_hints("exec", language="en")
assert "files generated" in definition.description
assert "code-generated deliverables" in definition.description
assert "creating a file" in hint.when_to_use
assert "python -c" in hint.guideline
assert "heredoc" in hint.guideline
assert "code_execution" in exec_hint.guideline
def test_code_execution_guidance_is_bilingual() -> None:
for language in ("en", "zh"):
hint = load_prompt_hints("code_execution", language=language)
exec_hint = load_prompt_hints("exec", language=language)
assert "Python" in hint.when_to_use
assert "python -c" in hint.guideline
assert "heredoc" in hint.guideline
assert "code_execution" in exec_hint.guideline
assert "python -c" in exec_hint.guideline
assert "heredoc" in exec_hint.guideline
def test_chat_prompts_prefer_code_execution_for_python_files() -> None:
root = Path(__file__).parents[2] / "deeptutor" / "agents" / "chat" / "prompts"
missing_artifact_warnings = {
"en": "without that list, do not claim a file was created",
"zh": "没有这个清单就不要宣称已创建文件",
}
for language in ("en", "zh"):
data = yaml.safe_load((root / language / "agentic_chat.yaml").read_text())
prompt = data["loop"]["system"]
assert "code_execution" in prompt
assert "python -c" in prompt
assert "heredoc" in prompt
assert missing_artifact_warnings[language] in prompt
def test_solve_prompts_route_python_files_to_code_execution() -> None:
root = Path(__file__).parents[2] / "deeptutor" / "capabilities" / "solve" / "prompts"
shell_only_guidance = {
"en": "`exec` only for genuinely shell-only commands",
"zh": "`exec` 只用于真正必须使用 shell 的命令",
}
for language in ("en", "zh"):
prompt = (root / language / "system.md").read_text()
assert "code_execution" in prompt
assert "Python-generated files" in prompt or "用 Python 生成文件" in prompt
assert shell_only_guidance[language] in prompt
def test_office_skills_use_code_execution_for_python_deliverables() -> None:
root = Path(__file__).parents[2] / "deeptutor" / "skills" / "builtin"
for skill in ("docx", "pdf", "pptx", "xlsx"):
document = (root / skill / "SKILL.md").read_text()
assert "code_execution" in document
assert "python -c" in document
assert "heredoc" in document