Codex Prompt Best Practices
Master prompting techniques to help Codex understand your intent more accurately and complete tasks efficiently.
Basic prompt structure
A good prompt contains the following elements:
Basic elements
| Element | Description | Example |
|---|---|---|
| Task description | What you want to do | "Implement user login functionality" |
| Context | Relevant background information | "Use the existing auth module" |
| Constraints | Constraints and requirements | "Must be compatible with existing APIs" |
| Expected result | Specific output | "Return a JWT token" |
Structured prompts
Complete prompt example
Task description
Implement a user login API endpoint
Context
The project uses the FastAPI framework
An existing auth module handles authentication logic
The database uses PostgreSQL
Constraints
Use existing JWT utilities to generate tokens
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":
{
...
}
}
Error response:
{
"error": "..."
}
Task decomposition principles
Complex tasks should be broken down into small steps and completed gradually.
Decomposition principles
- Each step has a clear goal
- Dependencies between steps are clear
- Verify results after each step
- Can roll back when problems arise
Decomposition example
Task decomposition
Large task
"Implement a complete user authentication system"
Break down into small tasks
Step
1
:
"Design the data structures for the authentication system, including user and token tables"
Step
2
:
"Implement user registration, including password encryption and verification"
Step
3
:
"Implement user login, generating a JWT token"
Step
4
:
"Implement token verification middleware"
Step
5
:
"Implement user logout"
Step
6
:
"Write tests for the authentication system"
Step
7
:
"Update the 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 | Frameworks, languages, library versions | First task or a new module |
| Project Structure | Module locations, naming conventions | Involves multi-file changes |
| Existing code | Related functions, classes, modules | Need compatibility or extension |
| Constraints | Compatibility and performance requirements | Have special constraints |
Ways to provide context
Provide context
Describe directly
"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 files
"Modify src/api/users.py, keeping a style consistent with other APIs"
AGENTS.md provided automatically
Create an AGENTS.md file, and Codex will automatically read the project conventions
Error message handling
Codex can quickly locate problems based on error messages.
Provide complete error messages
Error handling
Provide the complete error
"An error occurred when 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 an error screenshot, and Codex can view it directly
Error message elements
- Error type and message
- Complete stack trace
- Trigger conditions (what operation was performed)
- Expected result vs. actual result
Image input
Codex supports image input, ideal for conveying visual information.
Applicable scenarios
| Scenario | Description |
|---|---|
| Error screenshot | Screenshot showing the error screen or logs |
| Design mockup | Convert UI design mockups to code |
| Architecture diagram | Explain the architecture diagram and implement it |
| Data charts | Analyze chart data |
Image input methods
Use an image
CLI
codex
-i
screenshot.png
codex
--image
design.png
"Implement the page based on the design mockup"
App/IDE
Paste or drag an image directly into the conversation area
Multiple images
codex
-i
img1.png
-i
img2.png
"Compare the differences between these two design mockups"
Iterative Optimization
Gradually improve code quality through iteration.
Iteration process
- Codex completes the initial implementation
- Review the results and propose improvements
- Codex adjusts based on feedback
- Verify the improvements
- Repeat until satisfied
Iterative Optimization
Initial implementation
"Implement a user list API with pagination"
Propose improvements after review
"Add sorting, supporting sorting by creation time"
Continue optimizing
"Add search, supporting search by username"
Performance optimization
"Optimize query performance by adding indexes"
Avoid ambiguity
Clear prompts reduce misunderstandings and rework.
Ambiguity examples
Avoid ambiguity
Vague prompts (bad)
"Modify that function"
Clear prompts (good)
"Modify the format_date function in src/utils/helper.py"
Vague prompts (bad)
"Make it faster"
Clear prompts (good)
"Optimize the query_users function, reducing query time from 500ms to under 100ms"
Vague prompts (bad)
"Add a feature"
Clear prompts (good)
"Add batch deletion to the user API, accepting a list of user IDs"
Use reference examples
Provide reference code or documentation to help Codex understand the desired style.
Provide references
Reference existing code style
"Following the style of src/api/products.py, implement the user API"
Reference Documentation
"Implement according to the OpenAPI specification document docs/api-spec.yaml"
Reference examples
"Return the response in this format:
{
'success': true,
'data': {...},
'message': '...'
}"
Common prompt templates
Feature development template
Feature development
in
[
Module path
]
add
[
Feature name
]
Function
Requirements:
Use
[
Technology/library
]
Compatible
[
Existing system
]
Contains
[
Edge case handling
]
Return
[
Response format
]
Reference:
[
Paths of existing similar features
]
Bug fix template
Bug fixes
Problem description:
[
Bug symptoms
]
Trigger conditions:
[
Under what circumstances it occurs
]
Error message:
[
Complete error stack
]
Expected behavior:
[
What the correct result should be
]
Please analyze the cause and fix it without affecting other features.
Code review template
Code review
/
review
[
Range
]
for
[
Focus
]
Example
/
review src
/
auth
/
for
security issues
/
review HEAD~
5
..HEAD
for
performance regressions
Summary of best practices
Core principles
- Be clear and specific, avoid vague expressions
- Provide sufficient context
- Break down and execute complex tasks
- Iterate and refine gradually
- Verify results to ensure correctness
Efficiency tips
- Use AGENTS.md to reduce repetitive explanations
- Use Skills to encapsulate common prompts
- Use images to convey visual information
- Be complete when providing error information
Common questions
Q: What if Codex misunderstands?
Provide a clearer description, supplement the context, or use reference examples.
Q: How to make Codex follow project conventions?
Create an AGENTS.md file defining the conventions, and Codex will follow them automatically.
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?
PNG, JPG, and WebP formats are supported; a moderate resolution is recommended (not too small or too large).