Skip to content

Code Generation Guide

Learn how to effectively use DeepSeek's code generation capabilities to create high-quality code across multiple programming languages and frameworks.

Overview

DeepSeek's code generation models can help you:

  • Generate complete functions: Create entire functions from descriptions
  • Write boilerplate code: Generate repetitive code structures
  • Create unit tests: Automatically generate test cases
  • Debug and fix code: Identify and resolve issues
  • Refactor code: Improve code quality and structure
  • Generate documentation: Create comprehensive code documentation

Getting Started

Basic Code Generation

python
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.deepseek.com/v1"
)

response = client.chat.completions.create(
    model="deepseek-coder",
    messages=[
        {
            "role": "user",
            "content": "Write a Python function to calculate the factorial of a number"
        }
    ],
    max_tokens=300,
    temperature=0.2
)

print(response.choices[0].message.content)

Language-Specific Generation

python
def generate_code(description: str, language: str, framework: str = None):
    """Generate code for specific language and framework"""
    
    prompt = f"Write {language} code to {description}"
    if framework:
        prompt += f" using {framework}"
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "system",
                "content": f"You are an expert {language} developer. Write clean, efficient, and well-documented code."
            },
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=500,
        temperature=0.1
    )
    
    return response.choices[0].message.content

# Examples
python_code = generate_code("create a REST API endpoint", "Python", "Flask")
js_code = generate_code("implement a binary search algorithm", "JavaScript")
java_code = generate_code("create a singleton pattern", "Java")

Advanced Code Generation

Function Generation with Specifications

python
def generate_function_with_specs(name: str, description: str, 
                                parameters: list, return_type: str, 
                                language: str = "Python"):
    """Generate function with detailed specifications"""
    
    param_str = ", ".join([f"{p['name']}: {p['type']}" for p in parameters])
    
    prompt = f"""
Create a {language} function with these specifications:
- Function name: {name}
- Description: {description}
- Parameters: {param_str}
- Return type: {return_type}
- Include docstring and type hints
- Add error handling
- Include example usage
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=600,
        temperature=0.1
    )
    
    return response.choices[0].message.content

# Example usage
function_spec = {
    "name": "calculate_compound_interest",
    "description": "Calculate compound interest for an investment",
    "parameters": [
        {"name": "principal", "type": "float"},
        {"name": "rate", "type": "float"},
        {"name": "time", "type": "int"},
        {"name": "compound_frequency", "type": "int"}
    ],
    "return_type": "float"
}

code = generate_function_with_specs(**function_spec)
print(code)

Class Generation

python
def generate_class(class_name: str, description: str, 
                  attributes: list, methods: list, language: str = "Python"):
    """Generate complete class with attributes and methods"""
    
    attr_str = "\n".join([f"- {attr['name']}: {attr['type']} - {attr['description']}" 
                         for attr in attributes])
    method_str = "\n".join([f"- {method['name']}: {method['description']}" 
                           for method in methods])
    
    prompt = f"""
Create a {language} class with these specifications:

Class Name: {class_name}
Description: {description}

Attributes:
{attr_str}

Methods:
{method_str}

Requirements:
- Include constructor/initializer
- Add proper documentation
- Include type hints (if applicable)
- Add error handling where appropriate
- Follow best practices for the language
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=800,
        temperature=0.1
    )
    
    return response.choices[0].message.content

# Example
class_spec = {
    "class_name": "BankAccount",
    "description": "A simple bank account class for managing deposits and withdrawals",
    "attributes": [
        {"name": "account_number", "type": "str", "description": "Unique account identifier"},
        {"name": "balance", "type": "float", "description": "Current account balance"},
        {"name": "owner", "type": "str", "description": "Account owner name"}
    ],
    "methods": [
        {"name": "deposit", "description": "Add money to the account"},
        {"name": "withdraw", "description": "Remove money from the account"},
        {"name": "get_balance", "description": "Return current balance"},
        {"name": "transfer", "description": "Transfer money to another account"}
    ]
}

bank_account_class = generate_class(**class_spec)
print(bank_account_class)

Framework-Specific Generation

Web Development

React Components

python
def generate_react_component(component_name: str, description: str, 
                           props: list = None, hooks: list = None):
    """Generate React functional component"""
    
    props_str = ", ".join([f"{prop['name']}: {prop['type']}" for prop in (props or [])])
    hooks_str = ", ".join(hooks or [])
    
    prompt = f"""
Create a React functional component with these specifications:
- Component name: {component_name}
- Description: {description}
- Props: {props_str}
- Hooks to use: {hooks_str}
- Include TypeScript types
- Add proper JSX structure
- Include basic styling with CSS modules
- Add PropTypes or TypeScript interfaces
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=600,
        temperature=0.1
    )
    
    return response.choices[0].message.content

# Example
component = generate_react_component(
    "UserProfile",
    "Display user profile information with edit functionality",
    props=[
        {"name": "user", "type": "User"},
        {"name": "onEdit", "type": "() => void"}
    ],
    hooks=["useState", "useEffect"]
)

Express.js Routes

python
def generate_express_route(endpoint: str, method: str, description: str,
                          middleware: list = None, validation: bool = True):
    """Generate Express.js route handler"""
    
    middleware_str = ", ".join(middleware or [])
    
    prompt = f"""
Create an Express.js route handler:
- Endpoint: {endpoint}
- HTTP Method: {method}
- Description: {description}
- Middleware: {middleware_str}
- Include input validation: {validation}
- Add error handling
- Include proper HTTP status codes
- Add JSDoc comments
- Use async/await pattern
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=500,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Database Operations

SQL Query Generation

python
def generate_sql_query(description: str, tables: list, 
                      query_type: str = "SELECT"):
    """Generate SQL queries based on description"""
    
    tables_str = ", ".join(tables)
    
    prompt = f"""
Generate a {query_type} SQL query:
- Description: {description}
- Tables involved: {tables_str}
- Include proper JOINs if needed
- Add WHERE clauses for filtering
- Include comments explaining the logic
- Optimize for performance
- Follow SQL best practices
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=400,
        temperature=0.1
    )
    
    return response.choices[0].message.content

# Example
sql_query = generate_sql_query(
    "Get all orders with customer details for orders placed in the last 30 days",
    ["orders", "customers", "order_items"],
    "SELECT"
)

ORM Model Generation

python
def generate_orm_model(model_name: str, fields: list, 
                      orm: str = "SQLAlchemy", relationships: list = None):
    """Generate ORM model definitions"""
    
    fields_str = "\n".join([f"- {field['name']}: {field['type']} ({field.get('constraints', '')})" 
                           for field in fields])
    rel_str = "\n".join([f"- {rel['name']}: {rel['type']} to {rel['target']}" 
                        for rel in (relationships or [])])
    
    prompt = f"""
Create a {orm} model:
- Model name: {model_name}
- Fields:
{fields_str}
- Relationships:
{rel_str}
- Include proper constraints
- Add indexes where appropriate
- Include model methods if needed
- Add validation
- Follow {orm} best practices
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=600,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Testing and Quality Assurance

Unit Test Generation

python
def generate_unit_tests(function_code: str, test_framework: str = "pytest"):
    """Generate comprehensive unit tests for a function"""
    
    prompt = f"""
Generate comprehensive unit tests for this function using {test_framework}:

{function_code}

Requirements:
- Test normal cases
- Test edge cases
- Test error conditions
- Include setup and teardown if needed
- Add descriptive test names
- Include docstrings for test methods
- Use appropriate assertions
- Mock external dependencies if needed
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=800,
        temperature=0.1
    )
    
    return response.choices[0].message.content

# Example
function_to_test = """
def divide_numbers(a: float, b: float) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
"""

tests = generate_unit_tests(function_to_test)
print(tests)

Integration Test Generation

python
def generate_integration_tests(api_endpoint: str, description: str,
                             test_framework: str = "pytest"):
    """Generate integration tests for API endpoints"""
    
    prompt = f"""
Generate integration tests for this API endpoint using {test_framework}:
- Endpoint: {api_endpoint}
- Description: {description}

Include tests for:
- Successful requests with valid data
- Invalid input data
- Authentication/authorization
- Error responses
- Response format validation
- Performance considerations
- Use proper test fixtures
- Include setup and cleanup
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=700,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Code Optimization and Refactoring

Performance Optimization

python
def optimize_code(original_code: str, language: str, 
                 optimization_goals: list = None):
    """Generate optimized version of existing code"""
    
    goals_str = ", ".join(optimization_goals or ["performance", "readability"])
    
    prompt = f"""
Optimize this {language} code for {goals_str}:

{original_code}

Optimization requirements:
- Improve time complexity if possible
- Reduce memory usage
- Enhance readability
- Add performance comments
- Maintain functionality
- Follow best practices
- Explain optimizations made
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=800,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Code Refactoring

python
def refactor_code(original_code: str, refactoring_type: str, language: str):
    """Refactor code according to specific patterns"""
    
    refactoring_prompts = {
        "extract_method": "Extract repeated code into separate methods",
        "remove_duplication": "Remove code duplication using appropriate patterns",
        "improve_naming": "Improve variable and function naming for clarity",
        "add_error_handling": "Add comprehensive error handling",
        "apply_solid": "Apply SOLID principles to improve design",
        "add_documentation": "Add comprehensive documentation and comments"
    }
    
    refactoring_goal = refactoring_prompts.get(refactoring_type, refactoring_type)
    
    prompt = f"""
Refactor this {language} code to {refactoring_goal}:

{original_code}

Requirements:
- Maintain original functionality
- Improve code structure
- Add appropriate comments
- Follow language conventions
- Explain changes made
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=800,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Documentation Generation

API Documentation

python
def generate_api_docs(endpoint_code: str, format_type: str = "OpenAPI"):
    """Generate API documentation from code"""
    
    prompt = f"""
Generate {format_type} documentation for this API endpoint:

{endpoint_code}

Include:
- Endpoint description
- Request/response schemas
- Parameter descriptions
- Example requests and responses
- Error codes and descriptions
- Authentication requirements
- Rate limiting information
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=600,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Code Comments and Docstrings

python
def add_documentation(code: str, language: str, doc_style: str = "google"):
    """Add comprehensive documentation to existing code"""
    
    prompt = f"""
Add comprehensive documentation to this {language} code using {doc_style} style:

{code}

Include:
- Function/class docstrings
- Parameter descriptions
- Return value descriptions
- Usage examples
- Inline comments for complex logic
- Type hints (if applicable)
- Exception documentation
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=700,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Best Practices

Prompt Engineering for Code Generation

python
def create_effective_code_prompt(task: str, language: str, 
                               requirements: list = None, 
                               constraints: list = None):
    """Create well-structured prompts for code generation"""
    
    prompt_parts = [
        f"Task: {task}",
        f"Language: {language}",
    ]
    
    if requirements:
        prompt_parts.append("Requirements:")
        prompt_parts.extend([f"- {req}" for req in requirements])
    
    if constraints:
        prompt_parts.append("Constraints:")
        prompt_parts.extend([f"- {constraint}" for constraint in constraints])
    
    prompt_parts.extend([
        "Additional guidelines:",
        "- Write clean, readable code",
        "- Include error handling",
        "- Add appropriate comments",
        "- Follow language best practices",
        "- Include example usage if applicable"
    ])
    
    return "\n".join(prompt_parts)

# Example usage
prompt = create_effective_code_prompt(
    "Create a caching decorator",
    "Python",
    requirements=[
        "Support TTL (time-to-live)",
        "Thread-safe implementation",
        "Configurable cache size"
    ],
    constraints=[
        "No external dependencies",
        "Memory efficient",
        "Python 3.8+ compatible"
    ]
)

Code Quality Validation

python
def validate_generated_code(code: str, language: str):
    """Validate generated code quality"""
    
    prompt = f"""
Review this {language} code for quality and suggest improvements:

{code}

Check for:
- Syntax errors
- Logic errors
- Security vulnerabilities
- Performance issues
- Code style violations
- Missing error handling
- Incomplete functionality

Provide specific feedback and suggestions.
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        max_tokens=500,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Iterative Code Improvement

python
class CodeGenerator:
    """Iterative code generation and improvement"""
    
    def __init__(self, client):
        self.client = client
        self.conversation_history = []
    
    def generate_initial_code(self, description: str, language: str):
        """Generate initial code version"""
        prompt = f"Write {language} code to {description}"
        
        response = self.client.chat.completions.create(
            model="deepseek-coder",
            messages=[
                {"role": "user", "content": prompt}
            ],
            max_tokens=500,
            temperature=0.1
        )
        
        code = response.choices[0].message.content
        self.conversation_history = [
            {"role": "user", "content": prompt},
            {"role": "assistant", "content": code}
        ]
        
        return code
    
    def improve_code(self, feedback: str):
        """Improve code based on feedback"""
        self.conversation_history.append({
            "role": "user",
            "content": f"Improve the code based on this feedback: {feedback}"
        })
        
        response = self.client.chat.completions.create(
            model="deepseek-coder",
            messages=self.conversation_history,
            max_tokens=600,
            temperature=0.1
        )
        
        improved_code = response.choices[0].message.content
        self.conversation_history.append({
            "role": "assistant",
            "content": improved_code
        })
        
        return improved_code
    
    def add_feature(self, feature_description: str):
        """Add new feature to existing code"""
        self.conversation_history.append({
            "role": "user",
            "content": f"Add this feature to the code: {feature_description}"
        })
        
        response = self.client.chat.completions.create(
            model="deepseek-coder",
            messages=self.conversation_history,
            max_tokens=700,
            temperature=0.1
        )
        
        enhanced_code = response.choices[0].message.content
        self.conversation_history.append({
            "role": "assistant",
            "content": enhanced_code
        })
        
        return enhanced_code

# Example usage
generator = CodeGenerator(client)

# Generate initial code
initial_code = generator.generate_initial_code(
    "create a simple calculator class", 
    "Python"
)

# Improve based on feedback
improved_code = generator.improve_code(
    "Add input validation and better error messages"
)

# Add new feature
final_code = generator.add_feature(
    "Add support for scientific operations like sin, cos, log"
)

Language-Specific Examples

Python Examples

python
# Data science code generation
def generate_data_analysis_code(dataset_description: str, analysis_type: str):
    prompt = f"""
Create Python code for {analysis_type} analysis of {dataset_description}:
- Use pandas for data manipulation
- Include data visualization with matplotlib/seaborn
- Add statistical analysis
- Include data cleaning steps
- Add comments explaining each step
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=800,
        temperature=0.1
    )
    
    return response.choices[0].message.content

JavaScript Examples

python
# Frontend component generation
def generate_vue_component(component_name: str, functionality: str):
    prompt = f"""
Create a Vue.js component named {component_name} that {functionality}:
- Use Composition API
- Include TypeScript types
- Add proper props validation
- Include CSS with scoped styles
- Add unit tests with Vue Test Utils
- Include JSDoc comments
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=700,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Java Examples

python
# Spring Boot service generation
def generate_spring_service(service_name: str, functionality: str):
    prompt = f"""
Create a Spring Boot service class {service_name} that {functionality}:
- Use proper Spring annotations
- Include dependency injection
- Add exception handling
- Include logging with SLF4J
- Add validation
- Include unit tests with JUnit 5
- Follow Spring best practices
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=800,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Troubleshooting

Common Issues

  1. Incomplete code generation: Increase max_tokens
  2. Syntax errors: Use lower temperature (0.1-0.2)
  3. Inconsistent style: Specify coding standards in prompt
  4. Missing imports: Request complete, runnable code
  5. Poor performance: Ask for optimized solutions

Debugging Generated Code

python
def debug_generated_code(code: str, language: str, error_message: str = None):
    """Debug and fix generated code"""
    
    prompt = f"""
Debug this {language} code and fix any issues:

{code}

"""
    
    if error_message:
        prompt += f"Error message: {error_message}\n"
    
    prompt += """
Please:
- Identify and fix syntax errors
- Resolve logic errors
- Improve error handling
- Optimize performance if needed
- Explain what was fixed
"""
    
    response = client.chat.completions.create(
        model="deepseek-coder",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=600,
        temperature=0.1
    )
    
    return response.choices[0].message.content

Next Steps

基于 DeepSeek AI 大模型技术