Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
280 changes: 36 additions & 244 deletions agents/code-changes-agent.mdx
Original file line number Diff line number Diff line change
@@ -1,259 +1,51 @@
---
title: 'Code Agent'
title: Code Agent
---

The Code Agent generates production-ready code modifications through systematic analysis. It manages changes using Redis-based session tracking. The agent provides diff views and comprehensive dependency analysis before you apply changes.
An agent that generates production-ready code modifications through systematic analysis and tracks every change in a Redis-based session before you apply them.

## Quick Start
**It accepts**

**Q&A Page**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `request` | `string` | required | Natural language description of the code change to make |
| `conversation_history` | `Message[]` | optional | Prior messages for session context |
| `project_id` | `string` | required | Project identifier |
| `conversation_id` | `string` | required | Conversation identifier for session tracking |
| `node_ids` | `string[]` | optional | Specific files or functions to scope the change |

The agent gathers requirements through interactive clarifying questions with multiple choice options.
**It returns**

<img src="/images/code-agent-clarifying-questions.png" alt="Code Agent Clarifying Questions Interface" />
| Field | Type | Description |
|-------|------|-------------|
| `response` | `string` | Markdown explanation of what changed and why |
| `changes` | `FileDiff[]` | Diff view of every changed file, ready for review |

**Specification Loader Page**
## Choose what you want to do

The agent analyzes your codebase through structured phases shown in the specification progress tracker.
**Add a feature**
- If you describe a new capability, Code Agent asks clarifying questions to understand your architecture, then runs Spec → Plan → Generate before touching any file.
- It generates all required files and updates existing ones, tracking every change in the session so you can review diffs before anything lands in your repo.
- The result is a complete, multi-file changeset that matches your project's existing patterns and style.

<img src="/images/code-agent-spec-generation.png" alt="Specification Generation Progress" />
**Modify existing code**
- If you ask to extend, refactor, or update existing code, Code Agent locates the relevant files, examines surrounding context, and makes precise changes while preserving the rest.
- It shows a diff for each modified file and keeps changes in the session so you can iterate before finalizing.
- The changes slot cleanly into your codebase without breaking adjacent logic.

**Specification Page**
**Fix a bug**
- If you describe a bug like a null pointer, a race condition, an injection vulnerability , Code Agent analyzes the issue, generates a targeted fix, and explains the root cause.
- It may surface related problems found during investigation, so you get a complete fix rather than a patch that moves the bug elsewhere.
- The result is a diff with the correction alongside a written explanation of what was wrong and why the fix resolves it.

The complete specification displays implementation details, dependencies, and structured action items for review.
## Start building

<img src="/images/code-agent-spec-page.png" alt="Generated Specification Page" />
```python
from app.modules.intelligence.agents.chat_agents.code_changes_agent import CodeChangesAgent

**Plan: Summary**

Each phase includes a written summary describing what will be built and how it fits into the overall implementation.

<img src="/images/code-agent-plan-summary.png" alt="Plan Summary Tab" />

**Plan: Architecture**

The architecture tab visualizes component relationships across client, API, and data layers for each phase.

<img src="/images/code-agent-plan-architecture.png" alt="Plan Architecture Diagram" />

**Plan: Plan Items**

Each plan item details the task description, files to create or modify, and verification criteria to confirm completion.

<img src="/images/code-agent-plan-items.png" alt="Plan Items with File Changes and Verification Criteria" />

**Code Generation Page**

The agent generates code in a diff view showing exact file changes, with a "Create PR" button to push changes directly to your repository.

<img src="/images/code-agent-codegen.png" alt="Code Generation with Diff View" />

**Final Review**

<img src="/images/code-agent-final-review.png" alt="Final Review" />

## API Overview

The Code Agent operates as a stateful API endpoint. You send code modification requests. The agent generates changes and stores them in a session. You can review, modify, and export changes when ready.

**Endpoint:** `POST /api/v1/agents/code`

**Authentication:** Bearer token required

### Request Format

```typescript
{
query: string // Your code modification request
project_id: string // Project identifier
conversation_id: string // Conversation context
node_ids?: string[] // Optional: Specific code references
}
```

### Response Format

```typescript
{
response: string // Explanation of code changes (markdown)
tool_calls: ToolCall[] // Tools used during generation
citations: string[] // Files referenced during generation
}
```

## How It Works

1. **Context Enrichment**: Fetches code from referenced node IDs to understand existing patterns
2. **Systematic Analysis**: Analyzes your codebase to identify all files that will be impacted
3. **Pattern Examination**: Examines existing code patterns and conventions
4. **Style-Matched Generation**: Generates changes that match your project style exactly

All modifications go through the Code Changes Manager. This Redis-based system tracks changes across files. You can review diffs before applying changes to your repository.

### Multi-Agent Mode

The agent activates multi-agent mode for complex code generation. It delegates implementation to a specialized Code Implementation sub-agent. This sub-agent has 20 iterations available, the highest among all agents. Integration agents handle integration-specific code.

**Single-Agent Mode:** The agent processes simple modifications directly using its tools.

**Multi-Agent Mode:** Complex tasks trigger delegation to specialized sub-agents with up to 20 iterations for thorough implementation.

## Common Use Cases

### Adding Features

You request new features. The agent generates the necessary code across multiple files. It tracks all changes in the session.

```
"Add user profile endpoint to the API"
"Implement email notifications for password resets"
"Create a dashboard component with charts"
```

The agent generates all required files. It updates existing files where needed. You can review all changes before applying them.

### Modifying Code

You request modifications to existing code. The agent locates the relevant files. It makes precise changes while preserving functionality.

```
"Update the login function to support OAuth"
"Add error handling to the payment processor"
"Refactor the user service to use async/await"
```

The agent shows diffs for each modified file. You can iterate on changes before finalizing them.

### Fixing Bugs

You describe bugs and request fixes. The agent analyzes the issue. It generates corrections and explains the root cause.

```
"Fix the null pointer error in checkout"
"Resolve the race condition in data sync"
"Correct the SQL injection vulnerability in search"
```

The agent provides both the fix and an explanation. It may suggest additional improvements.

## Example Request

```bash
curl -X POST https://production-api.potpie.ai/api/v1/agents/code \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "Add a GET /api/users/:id endpoint that returns user details",
"project_id": "proj_123",
"conversation_id": "conv_456"
}'
```

## Example Response

```json
{
"response": "## User Endpoint Implementation\n\nI have added a GET endpoint for user details. The implementation includes three components:\n\n### Routes (app/routes/users.py:23-28)\n\n```python\n@router.get('/users/{user_id}')\nasync def get_user(user_id: str, db: Session = Depends(get_db)):\n user = await user_service.get_user_by_id(db, user_id)\n if not user:\n raise HTTPException(status_code=404, detail='User not found')\n return user\n```\n\n### Service (app/services/user_service.py:45-52)\n\nThe service layer queries the database and returns the user object.\n\n### Tests (tests/test_users.py:67-89)\n\nI have added integration tests for the new endpoint.",
"changes_summary": "Modified 2 files, added 1 file:\n- app/routes/users.py: Added get_user endpoint\n- app/services/user_service.py: Added get_user_by_id method\n- tests/test_users.py: Added test cases",
"session_id": "session_abc123"
}
```

## Reviewing Changes

You can review changes before applying them. The agent provides several tools for inspection.

### View All Changes

Request a summary of all modifications in the session.

```bash
curl -X POST https://production-api.potpie.ai/api/v1/agents/code \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "Show me all changes in the current session",
"project_id": "proj_123",
"conversation_id": "conv_456"
}'
```

### View Specific Diff

Request the diff for a specific file.

```bash
curl -X POST https://production-api.potpie.ai/api/v1/agents/code \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "Show me the diff for app/routes/users.py",
"project_id": "proj_123",
"conversation_id": "conv_456"
}'
code_agent = CodeChangesAgent(
llm_provider=provider_service,
tools_provider=tool_service,
prompt_provider=prompt_service,
)
```

### Export Changes

Export all changes for application to your codebase.

```bash
curl -X POST https://production-api.potpie.ai/api/v1/agents/code \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "Export all changes",
"project_id": "proj_123",
"conversation_id": "conv_456"
}'
```

## Error Responses

<AccordionGroup>
<Accordion title="400 Bad Request">
The request has invalid format or missing required fields.

```json
{
"error": "VALIDATION_ERROR",
"message": "Missing required field: project_id"
}
```
</Accordion>
<Accordion title="401 Unauthorized">
The API key is missing or invalid.

```json
{
"error": "UNAUTHORIZED",
"message": "Invalid API key"
}
```
</Accordion>
<Accordion title="404 Not Found">
The specified project does not exist or is not accessible.

```json
{
"error": "PROJECT_NOT_FOUND",
"message": "Project not found"
}
```
</Accordion>
<Accordion title="429 Too Many Requests">
You have exceeded the rate limit.

```json
{
"error": "RATE_LIMIT_EXCEEDED",
"message": "Retry after 60 seconds"
}
```
</Accordion>
</AccordionGroup>

## Related Agents

- <a href="/build-flow/ask-a-question" className="mode-link">Ask a Question</a> - Answers questions about your codebase
- <a href="/build-flow/debug-an-issue" className="mode-link">Debug an Issue</a> - Provides systematic bug diagnosis and resolution
Loading