跳到正文
Skillpedia
通用编程7.8k · #12847

code-execution-fallback

它能做什么

这项技能涵盖在运行代码前检查工作文件夹,并在需要时退回到 shell 执行。它适合运行 AI 编写的脚本、并发现文件保存位置错误的人。

适用场景

  • ✓当 AI 任务执行期间,文件总是出现在错误的文件夹中的时候。
  • ✓当沙箱反复失败,而代码的简化版本也无法解决问题的时候。
  • ✓当我希望 AI 通过 shell 运行 Python,并且代码以内联方式编写的时候。

技能链接

https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/code-execution-fallback/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/code-execution-fallback/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“我的 AI 总是把文件保存在错误的位置,而且沙箱一直失败。请修正文件夹,并通过 shell 运行脚本。”

每周 5 个新技能,1 分钟读完。

工作原理

AI 会先检查它的工作文件夹,尝试更简单的代码,然后改用 shell 运行,代码以内联方式编写。它会检查输出,以确认运行成功。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

Code Execution Fallback & Workspace Anchoring

This skill provides a robust pattern for executing code when the primary method fails, combined with proper workspace path management to prevent file location errors.

Core Techniques

1. Workspace Path Anchoring

Always establish and verify your working directory at the start of any task:

# At the beginning of any code execution
import os
workspace_path = os.getcwd()
print(f"Working directory: {workspace_path}")
# In shell scripts
pwd
echo "Current directory: $(pwd)"

Why: Prevents files from being written to unexpected locations when agents switch between tools.

2. Execution Fallback Ladder

When execute_code_sandbox fails, follow this escalation pattern:

Level 1: Retry with Simpler Code

  • Simplify the code structure
  • Remove complex dependencies
  • Add explicit error handling

Level 2: Use run_shell with Heredoc

When sandbox execution repeatedly fails, switch to shell execution:

python3 << 'EOF'
import os
import pandas as pd

# Your code here
data = {"col1": [1, 2, 3], "col2": ["a", "b", "c"]}
df = pd.DataFrame(data)
df.to_csv("output.csv", index=False)
print("File written successfully")
EOF

Key points:

  • Use << 'EOF' (quoted) to prevent variable expansion
  • Include all imports and dependencies inline
  • Add explicit success/failure messages

Level 3: Delegate to shell_agent

For complex multi-step tasks with error recovery needs:

Task: Create a data processing pipeline that reads CSV, transforms data, and outputs Excel
Requirements:
- Handle missing values
- Apply transformations
- Write to ./output/ directory
- Retry on transient errors

3. Explicit Path Management

Always use absolute or explicitly relative paths:

# BAD - relies on implicit working directory
df.to_csv("output/data.csv")

# GOOD - explicit path anchoring
import os
base_path = os.getcwd()
output_dir = os.path.join(base_path, "output")
os.makedirs(output_dir, exist_ok=True)
df.to_csv(os.path.join(output_dir, "data.csv"))
# BAD
cd some_dir && python script.py

# GOOD
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
python script.py

Decision Tree

execute_code_sandbox fails?
├── Yes, with syntax/import errors → Fix code, retry Level 1
├── Yes, with timeout/resource errors → Use Level 2 (run_shell heredoc)
├── Yes, with unknown/unclear errors → Use Level 3 (shell_agent)
└── No, success → Verify output file exists at expected path

Common Failure Scenarios & Solutions

Error Type Likely Cause Recommended Fallback
ModuleNotFoundError Missing packages run_shell with pip install first
Timeout Long-running operation shell_agent with progress tracking
PermissionError Wrong directory Verify workspace path, use explicit paths
Unknown error Sandbox limitations run_shell or shell_agent

Example: Robust File Generation

# Step 1: Anchor workspace
import os
workspace = os.getcwd()
print(f"Workspace: {workspace}")

# Step 2: Create output directory explicitly
output_path = os.path.join(workspace, "deliverables")
os.makedirs(output_path, exist_ok=True)

# Step 3: Generate content with error handling
try:
    # Your generation logic here
    with open(os.path.join(output_path, "report.txt"), "w") as f:
        f.write("Content here")
    print(f"Success: File written to {output_path}")
except Exception as e:
    print(f"Error: {e}")
    # Signal to escalate to run_shell or shell_agent
    raise

Anti-Patterns to Avoid

  • ❌ Assuming current directory without verification
  • ❌ Using relative paths like ../output/file.txt without context
  • ❌ Repeatedly retrying failed execute_code_sandbox without changing approach
  • ❌ Not checking if output files exist after generation
  • ❌ Mixing implicit and explicit path styles in same task

Verification Checklist

After any code execution:

  • Confirm working directory was verified at start
  • Confirm output files exist at expected paths
  • Confirm file contents are non-empty and valid
  • If execution failed, escalate to next fallback level within 2 retries
常见问题

什么是内联 shell 运行?

指在一个代码块中,把几行 Python 作为一条 shell 命令传入,而不是使用沙箱。

为什么要先检查工作文件夹?

当 AI 切换工具时,这可以防止文件被写入意外的位置。

切换到 shell 之前要做什么?

指南建议先尝试更简单的代码,如果仍然失败,再切换到 shell 执行。

详情

作者的原始描述

Handle code execution failures with fallback strategies and anchored workspace paths

repo: HKUDS/AgentPilot

热度

GitHub 星标
7.8k
排名
#12847
许可证
MIT
更新时间
2026/11/1

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能