Code Generation Agent Prompt

About Prompt

  • Prompt Type – Dynamic
  • Prompt Platform – ChatGPT, Grok, Deepseek, Gemini, Copilot, Midjourney, Meta AI and more
  • Niche – Development
  • Language – English
  • Category – Programming
  • Prompt Title – Code Generation Agent Prompt

Prompt Details

Of course. Here is an optimized, dynamic AI prompt for a Code Generation Agent, designed for all AI platforms and adhering to modern prompt engineering best practices. It is followed by a practical example.

### **Optimized Dynamic AI Prompt for Code Generation**

**Prompt Title:** The Expert Co-Pilot: A Dynamic Code Generation Template

**Prompt Goal:** To generate high-quality, production-ready, and context-aware code by providing the AI with a comprehensive and structured set of requirements. This template is designed to be filled in by a developer to minimize ambiguity and maximize the accuracy of the generated output.

### **Prompt Template**

“`
# AI Code Generation Request

## 1. ROLE & GOAL

You are to act as a **[Specify a detailed persona, e.g., “Expert Senior Python Developer specializing in secure and scalable REST APIs using the FastAPI framework”]**. Your primary goal is to generate clean, efficient, and well-documented code that perfectly aligns with the detailed specifications provided below. Think critically about security, performance, and maintainability.

## 2. PROJECT CONTEXT & ENVIRONMENT

This code will be part of a larger project. Understanding its context is crucial for generating integrated and consistent code.

* **Project Description:** `[Briefly describe the project, e.g., “A customer relationship management (CRM) platform for small businesses.”]`
* **Technology Stack:**
* **Language & Version:** `[e.g., Python 3.11]`
* **Framework(s) & Version(s):** `[e.g., FastAPI 0.104, Pydantic V2]`
* **Database & ORM/Library:** `[e.g., PostgreSQL 15, SQLAlchemy 2.0 with asyncpg driver]`
* **Key Libraries:** `[e.g., bcrypt for password hashing, httpx for testing, alembic for migrations]`
* **Coding Standards & Style Guide:** `[e.g., “Strictly adhere to PEP 8 for Python. Use Black for formatting and isort for imports.”]`
* **File Structure & Location (if relevant):** `[e.g., “This code should be placed in `app/api/v1/endpoints/users.py`. It needs to import the database session from `app/db/session.py` and Pydantic models from `app/schemas/user.py`.”]`

## 3. PRIMARY TASK DEFINITION

Your main task is to: **[Describe the main task clearly and concisely, e.g., “Generate a complete FastAPI endpoint function to handle new user registration.”]`**

## 4. DETAILED SPECIFICATIONS

Follow these technical requirements precisely.

* **Function/Class Signature:**
* **Name:** `[e.g., create_user]`
* **Parameters & Type Hints:** `[e.g., `user_in: schemas.UserCreate`, `db: AsyncSession = Depends(get_db)`]`
* **Return Value & Type Hint:** `[e.g., `-> schemas.UserRead`]`
* **Decorator(s):** `[e.g., `@router.post(“/”, response_model=schemas.UserRead, status_code=201)`]`

* **Core Logic (Step-by-Step):**
1. `[Describe the first logical step, e.g., “Check if a user with the provided email already exists in the database.”]`
2. `[Describe the second logical step, e.g., “If the user exists, raise an `HTTPException` with a 409 Conflict status code and a clear error message.”]`
3. `[Describe the third logical step, e.g., “If the user does not exist, hash the user’s plain-text password using the `bcrypt` library.”]`
4. `[Continue with all necessary steps, e.g., “Create a new `models.User` SQLAlchemy instance, populating it with the validated data from the Pydantic model and the newly hashed password.”]`
5. `[e.g., “Add the new user instance to the database session, commit the transaction, and refresh the instance to get the database-generated values (like the ID).”]`
6. `[e.g., “Return the newly created user object, which will be automatically serialized by FastAPI using the `UserRead` response model.”]`

* **Input Data Structure & Validation:**
* **Description:** `[Describe the input data, e.g., “The input will be a JSON object matching the `UserCreate` Pydantic schema.”]`
* **Example (if complex):**
“`json
{
“email”: “test@example.com”,
“password”: “a_strong_password_123”,
“full_name”: “John Doe”
}
“`

* **Output Data Structure:**
* **Description:** `[Describe the successful output, e.g., “A JSON object of the created user, matching the `UserRead` Pydantic schema, which excludes the password.”]`
* **Example:**
“`json
{
“id”: 1,
“email”: “test@example.com”,
“full_name”: “John Doe”,
“is_active”: true
}
“`

* **Error Handling & Edge Cases:**
* `[Specify an error case, e.g., “If the input email already exists in the database, return an HTTP 409 Conflict error.”]`
* `[Specify another error case, e.g., “Pydantic should automatically handle validation errors, returning an HTTP 422 Unprocessable Entity error.”]`
* `[Specify an edge case, e.g., “Ensure database connection errors are handled gracefully (FastAPI’s dependency injection and middleware may handle this, but be mindful of transaction rollbacks).”]`

## 5. QUALITY ATTRIBUTES

In addition to the core logic, the final code must exhibit the following qualities:

* **Documentation:** Generate a comprehensive docstring for the function/class using **[e.g., Google Style or reStructuredText format]**. Explain the purpose, arguments, return value, and any exceptions it might raise. Add concise inline comments for any complex or non-obvious lines of code.
* **Security:** The code must follow security best practices. **[e.g., “Do NOT store passwords in plain text. Use a strong, one-way hashing algorithm like bcrypt. Prevent SQL injection by using the ORM correctly.”]`**
* **Performance:** The code should be efficient. **[e.g., “Make database queries asynchronous and specific. Only select the columns you need if the query were more complex.”]`**
* **Testing:** After generating the function, create a corresponding unit/integration test file using the **[e.g., `pytest` framework and `httpx` for making requests to the test client]**. The tests should cover:
1. The “happy path” (successful user creation).
2. The error case (attempting to create a user with a duplicate email).
3. A validation error case (e.g., providing an invalid email format).

## 6. OUTPUT FORMAT

Please provide your response in the following structure:

1. **Brief Explanation:** A short paragraph explaining your approach and any important decisions made.
2. **Main Code:** The complete, production-ready code for the requested feature, inside a single, well-formatted markdown code block with the appropriate language identifier (e.g., ` “`python `).
3. **Test Code:** The complete test code in a separate markdown code block.
“`

### **Example of the Filled-Out Prompt in Practice**

Here is the above template filled out for a specific, real-world task.

“`
# AI Code Generation Request

## 1. ROLE & GOAL

You are to act as an **Expert Senior Python Developer specializing in secure and scalable REST APIs using the FastAPI framework**. Your primary goal is to generate clean, efficient, and well-documented code that perfectly aligns with the detailed specifications provided below. Think critically about security, performance, and maintainability.

## 2. PROJECT CONTEXT & ENVIRONMENT

This code will be part of a larger project. Understanding its context is crucial for generating integrated and consistent code.

* **Project Description:** **A customer relationship management (CRM) platform for small businesses.**
* **Technology Stack:**
* **Language & Version:** **Python 3.11**
* **Framework(s) & Version(s):** **FastAPI 0.104, Pydantic V2**
* **Database & ORM/Library:** **PostgreSQL 15, SQLAlchemy 2.0 with asyncpg driver**
* **Key Libraries:** **bcrypt for password hashing, httpx for testing, alembic for migrations**
* **Coding Standards & Style Guide:** **Strictly adhere to PEP 8 for Python. Use Black for formatting and isort for imports.**
* **File Structure & Location (if relevant):** **This code should be placed in `app/api/v1/endpoints/users.py`. It needs to import the database session from `app/db/session.py`, Pydantic schemas from `app/schemas/`, and the User model from `app/models/user.py`.**

## 3. PRIMARY TASK DEFINITION

Your main task is to: **Generate a complete FastAPI endpoint function to handle new user registration.**

## 4. DETAILED SPECIFICATIONS

Follow these technical requirements precisely.

* **Function/Class Signature:**
* **Name:** `create_user`
* **Parameters & Type Hints:** `user_in: schemas.UserCreate`, `db: AsyncSession = Depends(get_db)`
* **Return Value & Type Hint:** `-> models.User` (FastAPI will handle serialization via `response_model`)
* **Decorator(s):** `@router.post(“/”, response_model=schemas.UserRead, status_code=status.HTTP_201_CREATED)`

* **Core Logic (Step-by-Step):**
1. **Query the database to check if a user with the `user_in.email` already exists.**
2. **If the user exists, raise an `HTTPException` with status code `409 Conflict` and the detail message “Email already registered”.**
3. **If the user does not exist, hash the `user_in.password` using `bcrypt.hashpw` with a generated salt.**
4. **Create a new `models.User` SQLAlchemy instance. Pass all attributes from `user_in` except the password. Set the `hashed_password` attribute with the result from the previous step.**
5. **Add the new user object to the async database session, commit the transaction, and refresh the instance to load the database-generated ID.**
6. **Return the newly created `models.User` object.**

* **Input Data Structure & Validation:**
* **Description:** **The input is a JSON object matching the `schemas.UserCreate` Pydantic schema, which requires an email, a password, and a full_name.**
* **Example (if complex):**
“`json
{
“email”: “new.user@example.com”,
“password”: “VerySecurePassword!123”,
“full_name”: “Jane Doe”
}
“`

* **Output Data Structure:**
* **Description:** **A JSON object of the created user, matching the `schemas.UserRead` Pydantic schema, which excludes the password and includes the `id`.**
* **Example:**
“`json
{
“id”: 5,
“email”: “new.user@example.com”,
“full_name”: “Jane Doe”,
“is_active”: true
}
“`

* **Error Handling & Edge Cases:**
* **If the email from the payload already exists in the `users` table, the API must return an HTTP 409 Conflict error.**
* **If the input JSON fails Pydantic validation (e.g., invalid email format, missing fields), FastAPI’s default 422 Unprocessable Entity response is acceptable.**

## 5. QUALITY ATTRIBUTES

In addition to the core logic, the final code must exhibit the following qualities:

* **Documentation:** Generate a comprehensive docstring for the function using **Google Style format**. It should detail the function’s purpose, arguments (user_in, db), return value, and the `HTTPException` it can raise.
* **Security:** The code must follow security best practices. **Do NOT store passwords in plain text. Use bcrypt for hashing. Rely on SQLAlchemy’s parameterization to prevent SQL injection.**
* **Performance:** **The database query to check for an existing user must be asynchronous (`await db.execute(…)`).**
* **Testing:** After generating the function, create a corresponding unit test file `tests/api/v1/test_users.py` using the **`pytest` framework and `httpx.AsyncClient`**. The tests should cover:
1. Successful user creation (expect a 201 status code and correct data).
2. Attempting to create a user with a duplicate email (expect a 409 status code).
3. Attempting to create a user with an invalid email (expect a 422 status code).

## 6. OUTPUT FORMAT

Please provide your response in the following structure:

1. **Brief Explanation:** A short paragraph explaining your approach.
2. **Main Code:** The complete Python code for the FastAPI endpoint, inside a ` “`python ` markdown block.
3. **Test Code:** The complete `pytest` code in a separate ` “`python ` markdown block.
“`