Fallback pattern for PDF/document generation when execute_code_sandbox fails with opaque errors
Apply this pattern when execute_code_sandbox returns opaque or unhelpful errors during PDF, DOCX, or other document generation tasks. This fallback uses run_shell with direct python -c execution for more reliable document generation.
If execute_code_sandbox fails during document generation with errors like:
Proceed to the fallback approach.
Before generating documents, verify the required Python libraries are available in the shell environment:
python -c "import reportlab; print('OK')" 2>&1 || echo "reportlab missing"
python -c "import fpdf; print('OK')" 2>&1 || echo "fpdf missing"
python -c "import pypdf; print('OK')" 2>&1 || echo "pypdf missing"
python -c "import docx; print('OK')" 2>&1 || echo "python-docx missing"
If a library is missing, install it via pip:
pip install reportlab fpdf2 pypdf python-docx
Use run_shell with python -c and multi-line strings for document generation:
python -c "
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
c = canvas.Canvas('output.pdf', pagesize=letter)
c.drawString(100, 750, 'Document Title')
c.drawString(100, 700, 'Content here')
c.save()
print('SUCCESS: PDF created')
"
For DOCX files:
python -c "
from docx import Document
doc = Document()
doc.add_heading('Document Title', 0)
doc.add_paragraph('Content here')
doc.save('output.docx')
print('SUCCESS: DOCX created')
"
Always wrap generation code with try/except for clear error reporting:
python -c "