본문으로 건너뛰기
Skillpedia
일반 코딩7.8k · #12847

code-execution-fallback

하는 일

이 스킬은 코드를 실행하기 전에 작업 폴더를 확인하고, 필요할 때 셸 실행으로 대체하는 방법을 다룹니다. AI가 작성한 스크립트를 실행하는데 파일이 잘못된 위치에 저장되는 사람을 위한 것입니다.

사용하는 경우

  • ✓AI 작업 중 파일이 계속 잘못된 폴더에 나타날 때.
  • ✓샌드박스가 반복해서 실패하고 코드를 더 단순하게 만들어도 해결되지 않는 경우.
  • ✓코드를 인라인으로 작성해 셸에서 Python을 실행하고 싶을 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/code-execution-fallback/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“AI가 계속 파일을 잘못된 곳에 저장하고 샌드박스도 계속 실패합니다. 폴더를 고치고 셸에서 스크립트를 실행해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

AI는 먼저 작업 폴더를 확인하고, 더 단순한 코드를 시도한 다음, 코드를 인라인으로 넣은 셸 실행으로 옮깁니다. 출력을 확인해 실행이 성공했는지 확인합니다.

기술 내용 (원본 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
자주 묻는 질문

인라인 셸 실행이란 무엇인가요?

샌드박스를 쓰지 않고, 셸 명령 하나에 여러 줄의 Python을 담아 실행하는 것입니다.

왜 작업 폴더를 먼저 확인하나요?

AI가 도구를 바꿀 때 파일이 예상치 못한 곳에 쓰이지 않도록 하기 위해서입니다.

셸 전환 전에는 무엇을 하나요?

안내서는 더 단순한 코드를 먼저 시도하고, 그래도 실패하면 셸 실행으로 전환하라고 제안합니다.

상세 정보

작성자의 원본 설명

Handle code execution failures with fallback strategies and anchored workspace paths

repo: HKUDS/AgentPilot

인기도

GitHub 스타
7.8k
순위
#12847
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬