I've created three improved templates for your code generation use case, each with different levels of detail and structure. All are significant improvements over your original template.
- ❌ Your version:
{output_schema: '}(invalid syntax) - ✅ Improved:
{output_schema}(proper placeholder)
Your template was a single block of text. The improved versions use:
- Clear section headers (## TASK, ## REQUIREMENTS, etc.)
- Numbered/bulleted lists for requirements
- Explicit "DO/DON'T" instructions
- Visual separation between sections
Original issues:
- Vague: "Only write the code. No introduction or explanation"
- No guidance on type hints
- No guidance on edge case handling
- Unclear about markdown code blocks
Improved specificity:
- "Write ONLY the function definition (no imports in function body, no examples, no explanations)"
- "All parameters should have type hints where possible"
- "Handle edge cases appropriately (e.g., empty inputs, None values)"
- "Do NOT wrap the code in markdown code blocks"
- "The response must be valid Python that can be directly executed with
exec()"
Original: Just mentioned output schema should be followed
Improved: Explicit mapping of JSON types to Python types:
- JSON "string" → Python str
- JSON "number"/"integer" → Python int/float
- JSON "boolean" → Python bool
- JSON "array" → Python list
- JSON "object" → Python dict
Plus instructions on handling nested structures and required fields.
Original: "The variables of the function are indicated by braces-surrounded names"
Improved:
- "Parameters: Extract from the task description (indicated by {braces})"
- Example in structured template: "Scan the task description for {{variable_name}} patterns"
- Concrete example: "Add {{a}} and {{b}}" → parameters are
aandb
Added explicit checklist items:
- ✓ Single function definition only
- ✓ One-line docstring
- ✓ Type hints on parameters and return value
- ✓ Handle edge cases
- ✓ No debugging prints
- ✓ Valid Python syntax (must pass compile())
- ✓ PEP 8 compliant
Original: Unclear what to do if schema is empty
Improved:
- "If output_schema is null or empty, the function can return any appropriate value"
- "(If schema is null/empty, return type can be determined from task context)"
Best for: General use, good balance of detail and conciseness
Structure:
## TASK DESCRIPTION
## OUTPUT SCHEMA
## REQUIREMENTS
### Function Signature
### Code Quality
### Output Format
### Code Style
## CRITICAL INSTRUCTIONS
## EXAMPLE FORMAT
Strengths:
- Clear, scannable structure
- Comprehensive but not overwhelming
- Explicit about what NOT to include
- Provides format example (marked as reference only)
Best for: Complex tasks requiring more guidance
Structure:
## 1. TASK
## 2. SPECIFICATIONS
## 3. IMPLEMENTATION GUIDE
### Parameter Extraction
### Type Hints
### Output Schema Conformance
### Code Quality Standards
## 4. CRITICAL OUTPUT REQUIREMENTS
Strengths:
- Most detailed guidance
- Step-by-step implementation instructions
- Explicit examples for parameter extraction
- Detailed JSON→Python type mapping
- Visual checkboxes for quality standards
Best for: Simple tasks, faster responses
Structure:
Write a Python function that does: {task}
Requirements:
- [bullet list]
Strengths:
- Concise, gets to the point
- Lower token count = faster/cheaper
- Still covers essentials
{
"name": "generated_python_function",
"schema": {
"type": "object",
"properties": {
"code": {"type": "string", "description": "Complete Python function definition"}
},
"required": ["code"]
}
}Use when: You just need the code string
{
"name": "detailed_python_function",
"schema": {
"type": "object",
"properties": {
"code": {"type": "string"},
"function_name": {"type": "string"},
"parameters": {"type": "array", "items": {"type": "string"}},
"docstring": {"type": "string"}
},
"required": ["code", "function_name"]
}
}Use when: You want metadata about the generated function
Safely extracts a function from generated code string:
- Compiles code to catch syntax errors early
- Executes in isolated namespace
- Validates exactly one function is defined
- Returns the function object ready to use
Factory function to create a code generator:
- Takes template and schema as arguments
- Automatically imports
oa.prompt_json_functionif available - Returns configured code generator function
End-to-end convenience function:
- Takes task description, schema, and name
- Generates code using LLM
- Extracts and returns executable function
- One-liner to go from natural language to working code
from oa import prompt_json_function
code_writing_template = """...""" # Your template
code_definition_schema = {...}
write_code = prompt_json_function(
code_writing_template,
json_schema=code_definition_schema,
)
r = write_code(task='Add {a} and {b}', output_schema='...', name='add_numbers')
# Then manually exec and extract functionfrom oa import prompt_json_function
from code_generation_improved import (
CODE_WRITING_TEMPLATE,
CODE_DEFINITION_SCHEMA,
extract_function_from_code
)
# Create code generator (same as before)
write_code = prompt_json_function(
CODE_WRITING_TEMPLATE,
json_schema=CODE_DEFINITION_SCHEMA
)
# Generate code (cleaner output)
result = write_code(
task='Add {a} and {b}',
output_schema='{"type": "object", "properties": {"sum": {"type": "number"}}}',
name='add_numbers'
)
# Extract function (safe helper)
add_numbers = extract_function_from_code(result['code'])
print(add_numbers(2, 3)) # {'sum': 5}from code_generation_improved import task_to_function
# One call does everything
add_numbers = task_to_function(
task='Add {a} and {b}',
output_schema={"type": "object", "properties": {"sum": {"type": "number"}}},
name='add_numbers'
)
print(add_numbers(2, 3)) # {'sum': 5}Better instructions = fewer malformed outputs, less need for retries
extract_function_from_code() validates before executing, catches errors early
Explicit type hint guidance means generated code is more maintainable
Instructions explicitly mention edge case handling, reducing runtime errors
"No markdown blocks" instruction prevents common exec() failures from LLMs wrapping code in ```python blocks
The structured approach, error handling, and helpers make this suitable for real applications, not just demos
- Start with
CODE_WRITING_TEMPLATE- It's the sweet spot - Use
extract_function_from_code()- Don't manually exec without validation - For simple tasks: Switch to
MINIMAL_CODE_WRITING_TEMPLATEto save tokens - For complex tasks: Use
STRUCTURED_CODE_WRITING_TEMPLATEfor more guidance - Consider adding retries: If code generation fails, retry with error feedback
To integrate this into your self-adaptive function pattern:
- Use the code generator as the "code path" in your hybrid approach
- Compare generated code performance vs LLM function calls
- Track which tasks benefit most from code generation
- Build a feedback loop to improve the template based on failure patterns
- Consider fine-tuning: Save task→code pairs for future model training
The improved templates give you a much stronger foundation for building that self-adaptive system!