> ## Documentation Index
> Fetch the complete documentation index at: https://amd-gaia.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Agent

> AI-powered full-stack Next.js application generation with TypeScript, Prisma, and Tailwind

<Info>
  **Source Code:** [`hub/agents/python/code/gaia_agent_code/agent.py`](https://github.com/amd/gaia/blob/main/hub/agents/python/code/gaia_agent_code/agent.py) · [`hub/agents/python/code/gaia_agent_code/tools/`](https://github.com/amd/gaia/tree/main/hub/agents/python/code/gaia_agent_code/tools)
</Info>

<Badge text="development" color="orange" />

<Note>
  The Code Agent is optimized for full-stack TypeScript web apps (Next.js + Prisma + Tailwind), but Python code generation remains fully supported (and is the default for non-TypeScript requests).
</Note>

<Info>
  **First time here?** Complete the [Setup](/docs/setup) guide first to install GAIA and its dependencies.
</Info>

The GAIA Code Agent turns a natural-language prompt into a working Next.js application. It designs the data model, builds Prisma schemas, generates REST API routes with Zod validation, creates React pages, applies Tailwind styling, validates TypeScript, and iterates until the app builds successfully.

<Note>
  End-to-end generation and auto-debugging for a full-stack app usually takes 10–20 minutes. Timing depends on how much context is created and how many debugging loops are needed. We prioritize output quality while continuously improving speed, and contributions that enhance either are welcome in the [GAIA repository](https://github.com/amd/gaia).
</Note>

## Key Features

<CardGroup cols={2}>
  <Card title="Full-Stack Generation" icon="robot">
    Next.js apps with API routes, React pages, and Tailwind styling
  </Card>

  <Card title="Prisma Data Modeling" icon="database">
    SQLite schemas with autogenerated IDs and timestamps
  </Card>

  <Card title="Validated APIs" icon="shield-check">
    REST endpoints with Zod validation and clear error responses
  </Card>

  <Card title="Type-Safe UI" icon="desktop">
    React components for list, create, and detail flows with TypeScript types
  </Card>

  <Card title="Iterative Fixes" icon="wrench">
    TypeScript checks, Next.js builds, and auto-fix loops until green
  </Card>

  <Card title="CLI Control" icon="list-check">
    Step-through, traces, and background process management for long runs
  </Card>
</CardGroup>

## Quick Start

**Prerequisite:** Install Node.js v20.19.x

* Download from [nodejs.org](https://nodejs.org/en/download) (Windows Installer for v20.19.x LTS)
* Verify installation: `node --version` (should show v20.19.x)
* Node.js is required to build and run the web application that the GAIA Code Agent generates.

<Steps>
  <Step title="Clone the repository">
    ```bash theme={null}
    git clone https://github.com/amd/gaia.git
    cd gaia
    ```
  </Step>

  <Step title="Install development dependencies">
    ```bash theme={null}
    curl -LsSf https://astral.sh/uv/install.sh | sh
    uv venv .venv --python 3.12
    source .venv/bin/activate
    uv pip install -e ".[dev]"
    ```
  </Step>

  <Step title="Start Lemonade server (local LLM)">
    ```bash theme={null}
    lemonade-server serve --ctx-size 32768
    ```
  </Step>

  <Step title="Generate an app">
    ```bash theme={null}
    gaia-code "Build me a movie tracking app in nextjs where I can track the movie title, genre, date watched, and a score out of 10" --path movie-web-app
    ```
  </Step>

  <Step title="Run the generated app">
    ```bash theme={null}
    cd movie-web-app
    npm run dev
    ```

    The app serves at [http://localhost:3000](http://localhost:3000)
  </Step>
</Steps>

### Basic Examples

<Tabs>
  <Tab title="Workout Tracker">
    ```bash theme={null}
    gaia-code "Build me a workout tracking app in nextjs where I can track workout, duration, date, and goal"
    ```
  </Tab>

  <Tab title="Restaurant Reviews">
    ```bash theme={null}
    gaia-code "Build me a restaurant rating application in nextjs. I want to be able to put the location of the restaurant, the food that I ate, and my review"
    ```
  </Tab>

  <Tab title="AI Tool Leaderboard">
    ```bash theme={null}
    gaia-code "Build me an AI tool rater in nextjs where I can give the name of the AI programming tool, give it a score out of 10 for speed and quality in a text box, as well as provide a description. Show a little leaderboard that will show the highest performing to lowest performing tools by averaging those scores."
    ```
  </Tab>

  <Tab title="Simple Todos">
    ```bash theme={null}
    gaia-code "Build me a todo tracking app using typescript"
    ```
  </Tab>

  <Tab title="Interactive Mode">
    ```bash theme={null}
    gaia-code --interactive
    # then type your prompt when prompted
    ```
  </Tab>
</Tabs>

## Next.js Full-Stack App Generation

The Code Agent outputs a complete Next.js project with Prisma, Zod, and Tailwind baked in.

```
your-app/
├── prisma/
│   └── schema.prisma          # SQLite models with IDs and timestamps
├── src/
│   ├── app/
│   │   ├── api/
│   │   │   └── [resource]/
│   │   │       ├── route.ts        # GET, POST
│   │   │       └── [id]/route.ts   # GET, PUT, DELETE
│   │   ├── [resource]/
│   │   │   ├── page.tsx        # List view
│   │   │   ├── new/page.tsx    # Create form
│   │   │   └── [id]/page.tsx   # Detail view
│   │   ├── layout.tsx          # Root layout
│   │   ├── page.tsx            # Landing page with navigation
│   │   └── globals.css         # Tailwind styles
│   └── lib/
│       └── prisma.ts           # Prisma client bootstrap
├── package.json
├── tsconfig.json
├── tailwind.config.ts
└── next.config.js
```

**Stack defaults:**

* Next.js with the App Router
* TypeScript + strict typing
* Prisma ORM with SQLite
* REST API routes validated with Zod
* Tailwind CSS styling for layouts, forms, and states

## Debug and Trace Options

<CardGroup cols={2}>
  <Card title="Debug Logging" icon="bug">
    ```bash theme={null}
    gaia-code "Create a todo tracking app in nextjs" --debug
    ```

    See internal decision logs
  </Card>

  <Card title="JSON Trace" icon="file-code">
    ```bash theme={null}
    gaia-code "Create a todo tracking app in nextjs" --trace
    ```

    Save detailed execution trace
  </Card>

  <Card title="Full Debug" icon="magnifying-glass-chart">
    ```bash theme={null}
    gaia-code "Create a todo tracking app in nextjs" --debug --trace
    ```

    Maximum debugging information
  </Card>
</CardGroup>

### JSON Output Structure

The `--trace` flag saves a complete trace with detailed information:

```json title="trace_output.json" theme={null}
{
  "status": "success",
  "result": "Final answer from agent",
  "system_prompt": "Complete system prompt used",
  "conversation": [
    {"role": "user", "content": "User's query"},
    {"role": "assistant", "content": {"thought": "...", "tool": "...", "tool_args": {...}}},
    {"role": "system", "content": {...}}
  ],
  "steps_taken": 28,
  "duration": 123.45,
  "total_input_tokens": 15000,
  "total_output_tokens": 8000,
  "output_file": "/absolute/path/to/output.json"
}
```

## API & VSCode Integration

<Info>
  The Code Agent is available through the GAIA API Server as the `gaia-code` model, providing an OpenAI-compatible REST API for IDEs and automation.
</Info>

### Quick Start

<Steps>
  <Step title="Start Lemonade server">
    ```bash theme={null}
    lemonade-server serve --ctx-size 32768
    ```
  </Step>

  <Step title="Install API dependencies">
    ```bash theme={null}
    uv pip install -e ".[api]"
    ```
  </Step>

  <Step title="Start GAIA API server">
    ```bash theme={null}
    uv run gaia api start
    ```
  </Step>

  <Step title="Call the model">
    <Tabs>
      <Tab title="Linux/macOS">
        ```bash theme={null}
        curl -X POST http://localhost:8080/v1/chat/completions \
          -H "Content-Type: application/json" \
          -d '{
            "model": "gaia-code",
            "messages": [{"role": "user", "content": "Build me a movie tracking app in nextjs"}]
          }'
        ```
      </Tab>

      <Tab title="PowerShell">
        ```powershell theme={null}
        $body = @{
            model = "gaia-code"
            messages = @(
                @{
                    role = "user"
                    content = "Build me a movie tracking app in nextjs"
                }
            )
        } | ConvertTo-Json -Depth 10

        Invoke-RestMethod -Uri "http://localhost:8080/v1/chat/completions" `
            -Method Post `
            -ContentType "application/json" `
            -Body $body
        ```
      </Tab>
    </Tabs>
  </Step>
</Steps>

### API Highlights

* **OpenAI Compatible**: Works with OpenAI clients and compatible tooling
* **Streaming Support**: Real-time updates while generating
* **Multi-Turn**: Maintain context across requests

<CardGroup cols={2}>
  <Card title="VSCode Integration Guide" icon="code" href="/docs/integrations/vscode" />

  <Card title="API Server Documentation" icon="server" href="/docs/reference/api">
    REST examples and usage
  </Card>
</CardGroup>

## Workflow Capabilities

<Steps>
  <Step title="Analyze Requirements">
    Interpret the prompt and determine the minimum viable schema
  </Step>

  <Step title="Generate Prisma Schema">
    Create models with IDs, timestamps, and inferred field types
  </Step>

  <Step title="Build API Routes">
    Scaffold REST endpoints with Zod validation for CRUD operations
  </Step>

  <Step title="Create React Pages">
    Generate list, creation, and detail pages wired to the APIs
  </Step>

  <Step title="Apply Styling">
    Add Tailwind-powered layouts, forms, and state handling
  </Step>

  <Step title="Validate & Build">
    Run TypeScript checks and Next.js build; collect any errors
  </Step>

  <Step title="Auto-Fix Loop">
    Apply targeted fixes and re-run validation/build until clean
  </Step>
</Steps>

## Available Tools

<AccordionGroup>
  <Accordion title="Project Bootstrap & Processes">
    * `run_cli_command` - Execute npm/yarn commands and capture output
    * `cleanup_all_processes` / `stop_process` / `list_processes` - Manage background runs
  </Accordion>

  <Accordion title="Data Modeling & APIs">
    * `manage_data_model` - Create or update Prisma models
    * `manage_api_endpoint` - Generate REST routes with Zod validation
    * `validate_crud_structure` - Ensure CRUD files exist for each resource
  </Accordion>

  <Accordion title="UI & Styling">
    * `manage_react_component` - Generate list, form, detail React pages
    * `setup_app_styling` - Apply Tailwind design system and globals
    * `update_landing_page` - Wire navigation and landing content
  </Accordion>

  <Accordion title="Validation & Quality">
    * `validate_typescript` - Run TypeScript compiler checks
    * `test_crud_api` - Smoke-test CRUD endpoints
    * `validate_styles` - Check CSS and design consistency
  </Accordion>

  <Accordion title="Debugging & Error Fixes">
    * `fix_code` - LLM-driven targeted file fix for validation/build errors (used in remediation checklists)
  </Accordion>

  <Accordion title="Tooling Setup">
    * `setup_prisma` - Initialize Prisma and database config
    * `setup_nextjs_testing` - Configure Vitest where needed
  </Accordion>
</AccordionGroup>

## External Information Lookup

The agent can optionally use web search (Perplexity) when `PERPLEXITY_API_KEY` is set in `.env` to unblock documentation or best-practice questions.

## Troubleshooting

<AccordionGroup>
  <Accordion title="LLM server not running">
    ```
    ❌ Error: Lemonade server is not running or not accessible.
    ```

    Start the server with:

    ```bash theme={null}
    lemonade-server serve --ctx-size 32768
    ```
  </Accordion>

  <Accordion title="TypeScript or build errors keep returning">
    * Ensure dependencies are installed: `npm install`
    * Regenerate Prisma client: `npx prisma generate`
    * Push schema: `npx prisma db push`
    * Re-run the agent with `--debug --trace` to inspect fixes
  </Accordion>

  <Accordion title="Agent gets stuck on a simple bug">
    * Occasionally the agent can loop on a minor issue; try rerunning the command
    * If it persists, update the prompt to call out the failing component or file
  </Accordion>

  <Accordion title="Prisma client issues">
    * Check `prisma/schema.prisma` for typos
    * Delete `node_modules` and reinstall
    * Verify `DATABASE_URL` (if using a custom provider)
  </Accordion>

  <Accordion title="Port already in use">
    * Stop existing dev servers or run `npm run dev -- --port 3001`
  </Accordion>
</AccordionGroup>

## VS Code Debugging (Developers)

Use the existing launch configurations to step through the agent when it generates Next.js projects.

<Accordion title="Available Debug Configurations">
  1. **Code Agent Debug - Next.js App** - Full project generation workflow
  2. **Code Agent Debug - REST API** - Focus on API route generation
  3. **Code Agent Debug - Interactive** - Step through with `--step-through`
  4. **Code Agent Debug - With Breakpoint** ⭐ - Stops before execution for setting breakpoints
</Accordion>

**Useful breakpoint locations:**

* `hub/agents/python/code/gaia_agent_code/agent.py` - Agent initialization and orchestration
* `hub/agents/python/code/gaia_agent_code/tools/typescript_tools.py` - TypeScript/Next.js tooling
* `hub/agents/python/code/gaia_agent_code/orchestration/checklist_executor.py` - Full-stack checklist workflow
* `src/gaia/agents/base/agent.py` - Base agent loop

## Best Practices

<CardGroup cols={2}>
  <Card title="Be Specific" icon="seedling">
    Include required fields and relationships in the prompt to shape the Prisma schema
  </Card>

  <Card title="Run Setup Commands" icon="terminal">
    After generation, just `cd <path>` and run `npm run dev` (the agent installs dependencies for you)
  </Card>

  <Card title="Review Before Shipping" icon="eye">
    Inspect API validation, UI flows, and database types before deploying
  </Card>

  <Card title="Iterate with Data" icon="repeat">
    Start with the MVP output, then rerun the agent with refined prompts to add features
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="VSCode Integration" icon="code" href="/docs/integrations/vscode" />

  <Card title="API Server" icon="server" href="/docs/reference/api">
    Integrate via OpenAI-compatible API
  </Card>

  <Card title="Playbook" icon="book" href="/docs/playbooks/code-agent/part-1-introduction">
    Deep dive into how the Code Agent builds Next.js apps
  </Card>

  <Card title="Features Overview" icon="wand-magic-sparkles" href="/docs/reference/features">
    Explore all GAIA capabilities
  </Card>
</CardGroup>

***

<small style="color: #666;">
  **License**

  Copyright(C) 2024-2026 Advanced Micro Devices, Inc. All rights reserved.

  SPDX-License-Identifier: MIT
</small>
