Codex Prompt Best Practices
Master prompt techniques to help Codex understand your intent more accurately and complete tasks efficiently.
Basic prompt structure
A good prompt includes the following elements:
Basic Elements
| Elements | Description | Example |
|---|---|---|
| Task Description | What you want to do | "Implement user login functionality" |
| Context | Related background information | "Use the existing auth module" |
| Constraints | Limitations and Requirements | "Must be compatible with existing APIs" |
| Expected result | Specific Output | "Return JWT token" |
Structured prompt
Complete prompt example
Implement a user login API endpoint
# Context
- The project uses the FastAPI framework
- The existing auth module handles authentication logic
- The database uses PostgreSQL
# Constraints
- Use the existing JWT utility to generate the token
- Passwords are verified using bcrypt
- Need to add request logging
# Expected Result
- Path: POST /api/auth/login
- Request body: {"email": "...", "password": "..."}
- Success response: {"token": "...", "user": {...}}
- Failure response: {"error": "..."}
Task decomposition principle
Complex tasks should be broken down into small steps and completed step by step.
Decomposition Principles
- Each step has a clear objective
- Dependencies between steps are clear
- Verify results after each step
- Can roll back when problems are encountered
Decomposition Example
Task Decomposition
"Implement a complete user authentication system"
# Decompose into Small Tasks
Steps1:"Design the data structure of the authentication system, including the user table and the token table"
Steps2:"Implement user registration functionality, including password encryption and verification"
Steps3:"Implement user login functionality and generate JWT token"
Steps4:"Implement token verification middleware"
Steps5:"Implement user logout functionality"
Steps6:"Write tests for the authentication system"
Steps7:"Update API documentation"
Using /plan mode can help Codex automatically break down complex tasks.
Provide context information
Sufficient context helps Codex understand the project state more accurately.
Key Context
| Type | Description | When to Provide |
|---|---|---|
| Tech Stack | Framework, language, library versions | First-time tasks or new modules |
| Project Structure | Module location, naming conventions | Involves multi-file modifications |
| Existing Code | Related functions, classes, modules | Requires compatibility or extension |
| Constraints | Compatibility, performance requirements | Has Special Constraints |
Ways to provide context
Provide Context
"The project uses Django 4.2 and the database is PostgreSQL 15"
# Reference Existing Code
Refer to the validation logic in src/utils/validator.py
# Specify file
Modify src/api/users.py, keeping the style consistent with other APIs
# AGENTS.md automatically provided
Create AGENTS.md file, Codex will automatically read the project guidelines
Error message handling
Codex can quickly locate issues based on error messages.
Provide complete error information
Error Handling
An error occurred while running tests:
AssertionError: Expected status 200 but got 500
at test_login.py:45
in test_successful_login
Full traceback:
...
Analyze the cause and fix it
# Screenshot assistance
Attach error screenshots, Codex can view them directly
Error message elements
- Error types and messages
- Full stack trace
- Trigger conditions (what operation was performed)
- Expected result vs actual result
Image input
Codex supports image input, suitable for conveying visual information.
Applicable scenarios
| Scenarios | Description |
|---|---|
| Error screenshot | Screenshots showing the error interface or logs |
| Design mockup | Convert UI design mockups to code |
| Architecture diagram | Explain the architecture diagram and implement it |
| Data chart | Analyze chart data |
Image input method
Use images
codex -i screenshot.png
codex --image design.png Implement the page based on the design mockup
# App/IDE
Directly paste or drag images into the conversation area
# Multiple images
codex -i img1.png -i img2.png Compare the differences between these two design mockups
Iterative optimization
Gradually optimize code quality through iteration.
Iteration process
- Codex completes the initial implementation
- Check results, propose improvements
- Codex adjusts based on feedback
- Verify improvement effect
- Repeat until satisfied
Iterative optimization
Implement user list API with pagination support
# Review and suggest improvements
Add sorting functionality to support sorting by creation time
# Continue optimizing
Add search functionality to support searching by username
# Performance optimization
Optimize query performance and add indexes
Avoid ambiguity
Clear prompts reduce misunderstanding and rework.
Examples of ambiguity
Avoid ambiguity
Modify that function
# Clear prompt (good)
Modify the format_date function in src/utils/helper.py
# Vague prompt (bad)
Make it faster
# Clear prompt (good)
Optimize the query_users function to reduce query time from 500ms to under 100ms
# Vague prompt (bad)
Add a feature
# Clear prompt (good)
Add a batch delete feature to the user API that accepts a list of user IDs
Use reference examples
Provide reference code or documentation to help Codex understand the expected style.
Provide reference
Refer to the style of src/api/products.py to implement the user API
# Reference documentation
Implement according to the OpenAPI specification document docs/api-spec.yaml
# Reference example
Return the response in this format:
{
'success': true,
'data': {...},
'message': '...'
}"
Common prompt templates
Feature development template
Feature development
Requirements:
- Use [technology/library]
- Be compatible with [existing system]
- Include [edge case handling]
- Return [response format]
Reference: [existing similar feature path]
Bug fix template
Bug Fix
Trigger conditions: [the circumstances in which it occurs]
Error message:
[Full error stack]
Expected behavior: [what the correct result should be]
Please analyze the cause and fix it, without affecting other functions.
Code review template
Code Review
# Example
/review src/auth/ for security issues
/review HEAD~5..HEAD for performance regressions
Best practices summary
Core Principles
- Be specific and clear, avoid vague descriptions
- Provide sufficient context
- Break down complex tasks for execution
- Iterative optimization, gradual improvement
- Verify results to ensure correctness
Efficiency Tips
- Use AGENTS.md to reduce repeated explanations.
- Use Skills to encapsulate common prompts.
- Use images to convey visual information
- Provide complete error information
FAQ
Q: What if Codex misunderstands?
Provide a clearer description, add context, or use reference examples.
Q: How can I make Codex follow project conventions?
Create an AGENTS.md file to define conventions, and Codex will automatically follow them.
Q: How to handle complex tasks?
Use /plan mode to make a plan, execute step by step, and verify.
Q: What are the limitations of image input?
Supports PNG, JPG, WebP formats; a moderate resolution is recommended (not too small or too large).
other extensions