Try this tool today
Accelerate your vibe coding workflow with our partner link.
Claude Code / Sonnet is a family of large language models from Anthropic, designed specifically for code generation, comprehension, and refinement. Use it when writing, reviewing, or refactoring code, especially when you need a deep understanding of a codebase or want to generate high-quality, idiomatic code across multiple languages. It excels at tasks like generating function bodies from docstrings, writing unit tests from signatures, suggesting improvements to existing code, and summarizing complex modules.
Writing Code from Specification
To generate code from a natural language prompt, send a structured message to the model using the /v1/chat/completions endpoint with a messages array. The most common pattern involves a system message that sets the role and a user message with the specification.
{
"model": "claude-3-sonnet-20240229",
"messages": [
{
"role": "system",
"content": "You are an expert software engineer. Write clean, idiomatic code in the target language. Use standard libraries and best practices. Include docstrings and error handling."
},
{
"role": "user",
"content": "Write a Python function that takes a list of integers and returns the median. Handle edge cases: empty list, odd-length list, even-length list. Use the statistics module if possible."
}
],
"max_tokens": 512,
"temperature": 0.3,
"top_p": 0.8
}
The temperature parameter controls creativity: lower values (0.1–0.5) yield more deterministic, focused code; higher values (0.7–1.0) produce more varied or exploratory solutions. Use top_p to sample from a dynamic vocabulary, balancing diversity and coherence.
The model returns a content field in the choices array, often including full code blocks with syntax highlighting:
def median(numbers: list[int]) -> float:
"""Calculate the median of a list of integers.
Args:
numbers: A list of integers. May be empty.
Returns:
The median value as a float. For even-length lists, returns the average
of the two middle elements.
Raises:
ValueError: If the input list is empty.
"""
if not numbers:
raise ValueError("Cannot compute median of empty list")
sorted_nums = sorted(numbers)
n = len(sorted_nums)
if n % 2 == 1:
return float(sorted_nums[n // 2])
else:
mid1 = sorted_nums[n // 2 - 1]
mid2 = sorted_nums[n // 2]
return (mid1 + mid2) / 2
When generating code for a larger project, include context by preceding the user prompt with previously defined code:
{
"role": "user",
"content": "Implement a `UserRepository` class that stores users in a JSON file. Use the `User` class defined below.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass User:\n id: int\n name: str\n email: str\n```\n\nThe repository should support:\n- `save(user: User)`\n- `find_by_id(id: int) -> User | None`\n- `all() -> list[User]`\n\nUse the `json` module and handle file I/O exceptions."
}
The model reads the context and generates code that integrates well with the existing structure, often using the same conventions and types.
Refactoring and Code Review
To suggest improvements to an existing codebase, use the model in a code review role. Send a system message that defines the reviewer’s persona and a user message with the code and a set of review questions.
{
"model": "claude-3-sonnet-20240229",
"messages": [
{
"role": "system",
"content": "You are a senior engineer reviewing code. Focus on clarity, correctness, performance, and idiomatic style. Suggest improvements with concrete examples. Use a bullet list for each suggestion."
},
{
"role": "user",
"content": "Review the following Python module. Identify issues and suggest improvements.\n\n```python\nimport json\n\ndef process_orders(order_list):\n total = 0\n for order in order_list:\n total += order['price']\n return total\n\n# Save orders to file\ndef save_orders(filename, orders):\n with open(filename, 'w') as f:\n json.dump(orders, f)\n```\n\nSuggest improvements for: naming, error handling, type hints, and performance."
}
],
"max_tokens": 1024,
"temperature": 0.4
}
The model returns a response with structured suggestions:
- Naming: Consider renaming
process_orderstocalculate_total_revenuefor clarity. - Error Handling: Add validation for
order_listand handleKeyErrorwhen accessingorder['price']. - Type Hints: Add type hints to parameters and return values.
- Performance: Precompute
len(order_list)if the list is large.
It may also return revised code with the improvements applied:
from typing import List, Dict, Any, Optional
def calculate_total_revenue(orders: List[Dict[str, Any]]) -> float:
"""Calculate the total revenue from a list of order dictionaries.
Args:
orders: List of orders, each with a 'price' key.
Returns:
Total revenue as a float.
Raises:
ValueError: If any order is missing the 'price' key.
"""
total: float = 0.0
for order in orders:
try:
total += order['price']
except KeyError as e:
raise ValueError(f"Order missing 'price' field: {order}") from e
return total
def save_orders(filename: str, orders: List[Dict[str, Any]]) -> None:
"""Save a list of orders to a JSON file.
Args:
filename: Path to the output file.
orders: List of order dictionaries.
"""
try:
with open(filename, 'w', encoding='utf-8') as f:
json.dump(orders, f, indent=2)
except (IOError, OSError) as e:
raise RuntimeError(f"Failed to save orders to {filename}") from e
Generating and Writing Unit Tests
To generate unit tests from function signatures or existing code, use a system prompt that emphasizes test quality and coverage.
{
"model": "claude-3-sonnet-20240229",
"messages": [
{
"role": "system",
"content": "Generate comprehensive unit tests for the following code. Use pytest. Include edge cases, error conditions, and test documentation. Use mock objects where appropriate."
},
{
"role": "user",
"content": "```python\nfrom datetime import datetime\n\ndef format_date(date: datetime) -> str:\n return date.strftime('%Y-%m-%d')\n```\n\nWrite tests for this function."
}
],
"max_tokens": 1024,
"temperature": 0.6
}
The model outputs a full test file, including setup, test cases, and assertions:
import pytest
from datetime import datetime
from mymodule import format_date
def test_format_date_returns_string():
"""Given a datetime, format_date returns a string."""
dt = datetime(2023, 12, 25)
result = format_date(dt)
assert isinstance(result, str)
assert result == "2023-12-25"
def test_format_date_handles_different_dates():
"""format_date returns correct YYYY-MM-DD format."""
cases = [
(datetime(1999, 1, 1), "1999-01-01"),
(datetime(2000, 2, 29), "2000-02-29"),
(datetime(2024, 10, 3), "2024-10-03")
]
for dt, expected in cases:
assert format_date(dt) == expected
def test_format_date_handles_none_input():
"""format_date raises TypeError when input is not a datetime."""
with pytest.raises(TypeError):
format_date("not a datetime")
def test_format_date_handles_timezone_aware_datetime():
"""format_date works with timezone-aware datetimes."""
dt = datetime(2023, 12, 25, 15, 30, tzinfo=timezone.utc)
result = format_date(dt)
assert result == "2023-12-25"
Handling Large Codebases
For codebases with multiple files, use the model to summarize or extract information. Send a prompt that includes the contents of multiple files and ask for a high-level overview.
{
"model": "claude-3-sonnet-20240229",
"messages": [
{
"role": "system",
"content": "Summarize the architecture of the following codebase. Identify the main components, their responsibilities, and how they interact. Highlight key design decisions and potential areas for improvement."
},
{
"role": "user",
"content": "```python\n# app/models.py\nfrom dataclasses import dataclass\n\n@dataclass\nclass User:\n id: int\n name: str\n email: str\n```\n\n```python\n# app/services.py\nfrom app.models import User\n\nclass UserService:\n def create_user(self, name: str, email: str) -> User:\n user = User(id=1, name=name, email=email)\n return user\n```\n\n```python\n# app/api.py\nfrom fastapi import FastAPI\nfrom app.services import UserService\n\napp = FastAPI()\nuser_service = UserService()\n\[email protected](\"/users\")\ndef create_user(name: str, email: str):\n user = user_service.create_user(name, email)\n return user\n```\n\nAnalyze this structure and summarize the project."
}
],
"max_tokens": 2048,
"temperature": 0.5
}
The model produces a narrative summary that can be used for onboarding, documentation, or design reviews.
Failure Modes and Sharp Edges
- Silent Token Limit Capping: If the input exceeds the model’s context window (typically 2048 tokens for Sonnet), the model truncates without warning. The first 1024 tokens are always processed, but longer inputs lose early context. Use
max_tokensto guide the output, but expect partial results when input is large.
- Confused Temperature and Top_p:
temperaturecontrols randomness across all tokens, whiletop_psamples from a dynamic set of likely tokens. Using both together is powerful, but confusing: hightemperaturewith lowtop_pyields very diverse but focused outputs; lowtemperaturewith hightop_pproduces stable, coherent results. A common mistake is settingtemperaturetoo high and expecting more variation, but getting only minor rewording.
- Missing or Misused System Prompts: The model often underperforms when the
systemmessage is too generic. “Write code” is weaker than “You are an expert Python engineer who writes production-ready, well-documented code.” Use specific roles and constraints.
- Inconsistent Output Formatting: The model sometimes returns code blocks with incorrect language tags, or mixes code and prose without clear separation. When generating code, always verify that the output is properly formatted and that the model includes the correct file extensions or module structure.
- Over-Refactoring: The model suggests many improvements, but often over-refactors. It may split a simple function into multiple smaller ones, add dependency injection, or introduce a new abstraction layer where it’s not needed. Review the output carefully, especially for small or ad-hoc code.
- Handling of Missing or Ambiguous Input: When input code is incomplete or uses non-standard names, the model makes assumptions that may not match the developer’s intent. For example, it might assume
order['price']is always present, but the actual data includesorder['cost']andorder['price']is optional. Always validate the model’s interpretation of the data structure.
Configuration and Optimization
Use the max_tokens, temperature, top_p, and stop parameters to fine-tune outputs:
max_tokens: Set to 512 for function generation, 1024 for module-level code, and 2048 for summaries or architecture reviews.temperature: 0.3–0.5 for production code, 0.6–0.8 for exploratory or experimental code.top_p: 0.7–0.9 for diverse, natural-sounding output.stop: Use["\n\n", "###", "##"]to control paragraph and section boundaries.
When calling the API from a script, cache common prompts and use model to switch between claude-3-sonnet-20240229 and claude-3-haiku-20240307 based on performance needs.
Use response_format for structured output:
{
"response_format": {
"type": "json_object"
}
}
This ensures the model returns a JSON object with predictable keys, ideal for integration with other tools.
Common Workflow Pattern
- Write a specification in natural language.
- Send it to the model with a system prompt that defines the expected style.
- Review the generated code.
- Refine the prompt based on the output.
- Generate unit tests.
- Apply improvements to the codebase.
- Summarize the codebase for documentation or onboarding.
The model is most effective when used iteratively: each output becomes the input for the next round of refinement.
This page was rewritten on 11 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.