YouTip LogoYouTip

Codex Examples

This section demonstrates various use cases of Codex CLI through practical examples to help you quickly master its application in real-world development.

\\n\\n
\\n\\n

Code Writing

\\n\\n

Example 1: Creating New Features

\\n\\n

Have Codex create a complete feature module for you:

\\n\\n

Task

\\n\\n

Create a Python function that accepts a list of strings and returns the longest string and its index position

\\n\\n

Codex will generate code similar to the following:

\\n\\n

Generated Code

\\n\\n
def find_longest_string(strings):\\n    """\\n    Find the longest string in a List of strings and its Index position.\\n    \\n    Args:\\n        strings: List of strings\\n    \\n    Returns:\\n        tuple: (Longest string, Indexposition)\\n               If the list is empty, return (None, -1)\\n    """\\n    if not strings:\\n        return None, -1\\n    \\n    longest = max(strings, key=len)\\n    index = strings.index(longest)\\n    \\n    return longest, index\\n\\n# TestExample\\nif __name__ == "__main__":\\n    test_list = ["apple", "banana", "cherry", "dragonfruit"]\\n    result, idx = find_longest_string(test_list)\\n    print(f"Longest string: {result}, Index: {idx}")\\n    # Output: Longest string: dragonfruit, Index: 3\\n
\\n\\n
\\n

Codex-generated code includes detailed documentation comments and test examples, ready for immediate use.

\\n
\\n\\n

Example 2: Refactoring Code

\\n\\n

Request Codex to refactor existing code:

\\n\\n

Task

\\n\\n

Refactor this function to use a generator:

\\n\\n
def get_squares(n):\\n    result = []\\n    for i in range(n):\\n        result.append(i * i)\\n    return result\\n
\\n\\n

Codex will provide the refactored code:

\\n\\n

Refactored Code

\\n\\n
def get_squares(n):\\n    """\\n    Generate from 0 to n-1 square numbers of。\\n    \\n    Args:\\n        n: Count of generated square numbers\\n    \\n    Yields:\\n        int: 0 to n-1 square numbers of\\n    """\\n    for i in range(n):\\n        yield i * i\\n\\n# Usage example\\nfor square in get_squares(5):\\n    print(square)\\n# Output: 0, 1, 4, 9, 16\\n
\\n\\n
\\n\\n

Code Review

\\n\\n

Example 1: Reviewing Code Issues

\\n\\n

Request Codex to review code and provide improvement suggestions:

\\n\\n

Task

\\n\\n

Review the issues in the following code:

\\n\\n
def process_data(data):\\n    result = []\\n    for item in data:\\n        if item['type'] == 'a':\\n            result.append(item['value'] * 2)\\n        elif item['type'] == 'b':\\n            result.append(item['value'] + 10)\\n        elif item['type'] == 'c':\\n            result.append(item['value'])\\n    return result\\n
\\n\\n

Codex will analyze and provide a review report:

\\n\\n

Code Review Report

\\n\\n

Issues

\\n\\n
    \\n
  1. Missing error handling: No check whether item contains required keys
  2. \\n
  3. Inconsistent types: 'c' type returns the original value directly, while other types are processed
  4. \\n
  5. Hard-coded values: Multipliers and addends should be parameters or configurations
  6. \\n
\\n\\n

Improvement Suggestions

\\n\\n
    \\n
  1. Add default dictionary or try-except handling
  2. \\n
  3. Unify processing logic
  4. \\n
  5. Extract magic numbers as constants
  6. \\n
\\n\\n

Example 2: Using the /review Command

\\n\\n

Use the built-in review command in Codex:

\\n\\n

Task

\\n\\n
/review src/\\n
\\n\\n

Codex will scan the entire src/ directory and generate a comprehensive code review report.

\\n\\n
\\n\\n

Debugging and Troubleshooting

\\n\\n

Example 1: Analyzing Error Messages

\\n\\n

Give error messages to Codex for analysis:

\\n\\n

Task

\\n\\n

Help me analyze this error:

\\n\\n
Traceback (most recent call last):\\n  File "app.py", line 42, in <module>\\n    main()\\n  File "app.py", line 38, in fetch_data()\\n  File "app.py", line 25, in fetch_data\\n    response = requests.get(url)\\n  File "/usr/lib/python3.10/site-packages/requests/api.py", line 88, in in get\\n    return session.request(method='GET', url=url, **kwargs)\\nrequests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded\\n
\\n\\n

Codex will provide analysis and solutions:

\\n\\n

Error Analysis

\\n\\n

Cause

\\n\\n

Network connection issue - unable to connect to api.example.com

\\n\\n

Possible Reasons

\\n\\n
    \\n
  1. Network is unreachable
  2. \\n
  3. Domain name resolution failure
  4. \\n
  5. Server is unavailable
  6. \\n
  7. Firewall blocking
  8. \\n
\\n\\n

Suggested Troubleshooting Steps

\\n\\n
    \\n
  1. Check network connection: ping api.example.com
  2. \\n
  3. Verify domain resolution: nslookup api.example.com
  4. \\n
  5. Check if port is open: telnet api.example.com 443
  6. \\n
  7. If local development, check proxy settings
  8. \\n
\\n\\n

Example 2: Adding Debug Logs

\\n\\n

Request Codex to add debug code:

\\n\\n

Task

\\n\\n

Add debug logs to this function:

\\n\\n
def calculate(a, b):\\n    return a + b * (a - b)\\n
\\n\\n

Codex will generate a version with debug logs:

\\n\\n

Adding Debug Logs

\\n\\n
import logging\\n\\n# Configure logging\\nlogging.basicConfig(level=logging.DEBUG)\\nlogger = logging.getLogger(__name__)\\n\\ndef calculate(a, b):\\n    """Calculation function with debug logs"""\\n    logger.debug(f"calculate called with a={a}, b={b}")\\n    \\n    result = a + b * (a - b)\\n    \\n    logger.debug(f"a + b = {a} + {b} = {a + b}")\\n    logger.debug(f"a - b = {a} - {b} = {a - b}")\\n    logger.debug(f"b * (a - b) = {b} * {a - b} = {b * (a - b)}")\\n    logger.debug(f"final result: {result}")\\n    \\n    return result\\n
\\n\\n
\\n\\n

File Operations

\\n\\n

Example 1: Batch Renaming Files

\\n\\n

Task

\\n\\n

Rename all files like image_001.jpg in the current directory to image-001.jpg (replace underscores with hyphens)

\\n\\n

Example 2: Creating Project Structure

\\n\\n

Task

\\n\\n

Create a standard directory structure for a Flask project, including:

\\n\\n
    \\n
  • app.py main file
  • \\n
  • config.py configuration file
  • \\n
  • requirements.txt
  • \\n
  • tests/ directory
  • \\n
  • static/ and templates/ directories
  • \\n
\\n\\n

Codex will create the complete project structure and generate all necessary files.

\\n\\n
\\n

Codex will first list the files to be created and execute after confirmation.

\\n
\\n\\n
\\n\\n

Command Execution

\\n\\n

Example 1: Running Tests

\\n\\n

Task

\\n\\n

Run the project's unit tests

\\n\\n

Codex will automatically detect the project type and run the corresponding test commands:

\\n\\n
    \\n
  • Python projects: pytest or unittest
  • \\n
  • Node.js projects: npm test or yarn test
  • \\n
  • Rust projects: cargo test
  • \\n
\\n\\n

Example 2: Git Operations

\\n\\n

Task

\\n\\n

Create a Git commit with all changes and an appropriate commit message

\\n\\n

Codex will analyze all uncommitted changes, then execute:

\\n\\n
    \\n
  1. git status - view changes
  2. \\n
  3. git diff - review specific modifications
  4. \\n
  5. git add -A - add all files
  6. \\n
  7. git commit -m "..." - create commit
  8. \\n
\\n\\n
\\n

For Git operations, Codex will first display the changes and execute after confirmation.

\\n
\\n\\n
\\n\\n

Project Analysis

\\n\\n

Example 1: Understanding Project Structure

\\n\\n

Task

\\n\\n

Analyze this project's architecture and technology stack

\\n\\n

Codex will check the project's:

\\n\\n
    \\n
  • Configuration files (package.json, Cargo.toml, requirements.txt, etc.)
  • \\n
  • Directory structure
  • \\n
  • Main source files
  • \\n
\\n\\n

Then provide a detailed analysis report.

\\n\\n

Example 2: Finding Dependencies

\\n\\n

Task

\\n\\n

Find which files reference auth.py

\\n\\n
\\n\\n

Plan Mode

\\n\\n

Use the /plan command for planning complex tasks:

\\n\\n

Task

\\n\\n
/plan Add user authentication to this React project, including login, registration, and JWT verification\\n
\\n\\n

Codex will first display a detailed implementation plan:

\\n\\n

Implementation Plan: User Authentication Feature

\\n\\n

Step 1: Preparation

\\n\\n
    \\n
  • Create user model
  • \\n
  • Install authentication dependencies (jsonwebtoken, bcryptjs)
  • \\n
\\n\\n

Step 2: Backend Implementation

\\n\\n
    \\n
  • Create /api/auth/register endpoint
  • \\n
  • Create /api/auth/login endpoint
  • \\n
  • Implement JWT generation and verification middleware
  • \\n
\\n\\n

Step 3: Frontend Implementation

\\n\\n
    \\n
  • Create login form component
  • \\n
  • Create registration form component
  • \\n
  • Add authentication state management
  • \\n
\\n\\n

Step 4: Testing

\\n\\n
    \\n
  • Write backend unit tests
  • \\n
  • Test frontend form interactions
  • \\n
\\n\\n

Confirm execution of this plan?
\\n Confirm Cancel Modify

\\n\\n
\\n

Plan mode lets you understand Codex's complete thought process before execution, avoiding unnecessary rework.

\\n
\\n\\n
\\n\\n

Comprehensive Example

\\n\\n

A complete workflow example:

\\n\\n

Complete Workflow

\\n\\n
# 1. Start new session\\n/new\\n\\n# 2. Understand the project\\nWhat framework does this project use? What are its main features?\\n\\n# 3. Add new feature\\nAdd a verification code sending feature to the users module, considering:\\n- Verification code generation (6 digits)\\n- 60 Cannot be resent within seconds\\n- Verification code valid for 10 minutes\\n\\n# 4. Test\\nRun relevant Tests to ensure proper functionality.\\n\\n# 5. Code review\\n/review\\n
\\n\\n

This example demonstrates a typical development workflow: understand project β†’ implement feature β†’ test β†’ review.

\\n\\n
\\n\\n

Quick Operations Summary

\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
ScenarioCommand to Use
Write a functionDescribe requirements directly
Review code/review or "help me review..."
Debug issuesPaste error message and request analysis
Execute commandsStart with !
Complex task planning/plan + task description
Understand code"What does this function do?"
\\n\\n
\\n

Practice makes perfect. The more you use Codex, the more proficient you'll become, and your coding efficiency will improve significantly.

\\n
← Codex SubagentsCodex Cli Skills β†’