Code Generation Assistants
Code generation is one of the most impactful applications of Generative AI. This topic covers building tools that write, review, debug, and explain code.
How LLMs Generate Code
LLMs trained on code repositories understand programming patterns, APIs, and best practices. They can:
- Write functions from natural language descriptions
- Complete partial code (autocomplete)
- Translate between programming languages
- Generate tests for existing code
- Debug and fix errors
- Explain complex code
Building a Code Generator
Basic Code Generation
python
from openai import OpenAI
client = OpenAI()
def generate_code(description, language="python"):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"""You are an expert {language} developer.
Generate clean, well-structured code with:
- Type hints (if applicable)
- Error handling
- Brief inline comments for complex logic
Return ONLY the code, no explanations."""
},
{
"role": "user",
"content": description
}
],
temperature=0.2, # Low for code accuracy
max_tokens=2000
)
return response.choices[0].message.content
# Usage
code = generate_code(
"Create a REST API endpoint using FastAPI that accepts a POST "
"request with a JSON body containing 'email' and 'password', "
"validates them, and returns a JWT token."
)
print(code)Code with Tests
python
def generate_code_with_tests(description, language="python"):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"""You are an expert {language} developer.
For every function you write, also generate unit tests.
Format your response as:
## Implementation
```{language}
[code here]
```
## Tests
```{language}
[test code here]
```"""
},
{
"role": "user",
"content": description
}
],
temperature=0.2
)
return response.choices[0].message.contentBuilding a Code Review Assistant
python
def review_code(code, focus_areas=None):
focus = ""
if focus_areas:
focus = f"\nFocus especially on: {', '.join(focus_areas)}"
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"""You are a senior code reviewer.
Review code for:
1. Bugs and logical errors
2. Security vulnerabilities
3. Performance issues
4. Code style and readability
5. Best practice violations
{focus}
For each issue:
- Quote the problematic line
- Explain the issue
- Provide the fixed code
- Rate severity: Critical / High / Medium / Low"""
},
{
"role": "user",
"content": f"Review this code:\n```\n{code}\n```"
}
],
temperature=0.2
)
return response.choices[0].message.contentBuilding a Debugging Assistant
python
def debug_code(code, error_message, language="python"):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": """You are an expert debugger. When given code
and an error message:
1. Identify the root cause
2. Explain WHY the error occurs
3. Provide the corrected code
4. Suggest how to prevent similar issues"""
},
{
"role": "user",
"content": f"""This {language} code produces an error:
```{language}
{code}Error message:
{error_message}Find and fix the bug.""" } ], temperature=0.1 ) return response.choices[0].message.content
## Code Translation
```python
def translate_code(code, source_lang, target_lang):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"""Translate code from {source_lang} to {target_lang}.
Preserve:
- Logic and algorithms
- Error handling
- Comments (translate if needed)
Use idiomatic {target_lang} patterns and conventions."""
},
{
"role": "user",
"content": f"```{source_lang}\n{code}\n```"
}
],
temperature=0.2
)
return response.choices[0].message.content
# Usage
js_code = """
const users = data.filter(u => u.active).map(u => ({
name: u.firstName + ' ' + u.lastName,
email: u.email
}));
"""
python_code = translate_code(js_code, "javascript", "python")Code Explanation
python
def explain_code(code, detail_level="intermediate"):
levels = {
"beginner": "Explain like I'm new to programming. Define all technical terms.",
"intermediate": "Explain the logic and patterns used. Assume basic programming knowledge.",
"expert": "Focus on design decisions, trade-offs, and potential issues."
}
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"You are a code explainer. {levels[detail_level]}"
},
{
"role": "user",
"content": f"Explain this code line by line:\n```\n{code}\n```"
}
],
temperature=0.3
)
return response.choices[0].message.contentPrompt Tips for Better Code Generation
1. Specify the Tech Stack
❌ "Create a web server"
✅ "Create an Express.js web server with TypeScript, using Zod for
request validation and Prisma for database access"2. Provide Context
"I have an existing User model with fields: id, name, email, role.
Write a middleware that checks if the user has admin role."3. Include Constraints
"Write a sorting function that:
- Works in-place (O(1) extra space)
- Is stable (preserves order of equal elements)
- Handles arrays up to 1 million elements"4. Give Examples of Input/Output
"Write a function that converts camelCase to snake_case.
Examples:
'getUserName' → 'get_user_name'
'HTMLParser' → 'html_parser'
'simpleTest' → 'simple_test'"Safety Considerations
When building code generation tools for production:
- Never execute generated code automatically — Always have human review
- Sandbox execution — If you must run generated code, use containers
- Validate outputs — Check for common vulnerabilities (SQL injection, etc.)
- Rate limit — Prevent abuse of your code generation API
- Log everything — Track what code is generated for auditing
Key Takeaways
- Low temperature (0.1–0.3) works best for code generation
- Be specific about language, framework, and constraints
- Always review generated code — LLMs can produce subtle bugs
- Test generated code — Generate tests alongside implementation
- Use the right model — GPT-4o or Claude Sonnet for complex code tasks
Next, we'll explore multimodal AI applications that work with images, audio, and more.