> For the complete documentation index, see [llms.txt](https://docs.archibase.app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.archibase.app/readme.md).

# AI Architecture - Clean Documentation

## Current State (After Cleanup)

### Architecture Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                         USER INTERFACE                          │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│  AIAssistant.tsx                                                │
│  • Manages conversation UI                                       │
│  • Handles user messages                                         │
│  • Shows proposal review                                         │
│  • Coordinates approval workflow                                 │
└─────────────────────────────────────────────────────────────────┘
       │                                           │
       │ 1. Send message                          │ 3. Execute approved ops
       ▼                                           ▼
┌──────────────────────────┐        ┌───────────────────────────────┐
│  aiService.ts            │        │  operationsExecutor.ts        │
│  (API Client)            │        │  (Client-Side Execution)      │
│                          │        │                               │
│  • processMessage()      │        │  • executeApprovedOperations()│
│    POST /api/ai-modeling │        │  • Sorts by priority          │
│                          │        │  • Calls store operations     │
└──────────────────────────┘        └───────────────────────────────┘
       │                                           │
       │ 2. Get proposals                         │ 4. Mutate store
       ▼                                           ▼
┌─────────────────────────────────────────────────────────────────┐
│  CLOUDFLARE PAGES FUNCTION: /api/ai-modeling                    │
│  • Stateless proposal generator                                  │
│  • Does NOT execute operations                                   │
│  • Does NOT persist state                                        │
└─────────────────────────────────────────────────────────────────┘
       │
       │ Uses LangGraph
       ▼
┌─────────────────────────────────────────────────────────────────┐
│  functions/lib/ai-graph/                                         │
│                                                                   │
│  • nodes.ts        → LangGraph nodes (understand, design, etc.)  │
│  • prompts.ts      → System prompts for each phase               │
│  • tools.ts        → Tool definitions (reference only)           │
│  • operations.ts   → Operation simulation (NOT used for exec)    │
└─────────────────────────────────────────────────────────────────┘
       │
       │ Calls OpenAI
       ▼
┌─────────────────────────────────────────────────────────────────┐
│  CLOUDFLARE AI GATEWAY                                           │
│  • Proxies to OpenAI                                             │
│  • Provides caching & monitoring                                 │
└─────────────────────────────────────────────────────────────────┘
       │
       ▼
┌─────────────────────────────────────────────────────────────────┐
│  OpenAI API (gpt-4o-mini)                                        │
└─────────────────────────────────────────────────────────────────┘
```

***

## Detailed Flow

### 1. User Sends Message

```
User types: "Add a Customer table"
       ↓
AIAssistant.handleSendMessage()
       ↓
aiService.processMessage(userMessage, database, conversationHistory)
       ↓
POST /api/ai-modeling
{
  userMessage: "Add a Customer table",
  database: {...current normalized database...},
  conversationHistory: [{role: 'user', content: '...'}, ...]
}
```

### 2. Server Processes & Returns Proposals

```
/api/ai-modeling handler:
       ↓
1. understandRequest(state, env)
   → Classifies intent: 'design'
   → Determines workType: 'conceptual'
       ↓
2. conceptualDesign(state, env)
   → Calls OpenAI with tools
   → AI suggests: create_entity("Customer")
       ↓
3. Return proposals (NO EXECUTION)
{
  message: {
    content: "I'll create a Customer table for you.",
    proposals: [
      {
        id: "tc_123",
        name: "create_entity",
        arguments: { name: "Customer", description: "..." }
      }
    ],
    needsApproval: true
  },
  state: {...}
}
```

### 3. User Reviews & Approves

```
AIAssistant renders ProposalReview
       ↓
User clicks "Approve All"
       ↓
handleApproveProposals(approvedIds)
       ↓
executeApprovedOperations(approvedOps)  ← CLIENT-SIDE EXECUTION
```

### 4. Client Executes Operations

```
operationsExecutor.executeApprovedOperations():
       ↓
1. Sort operations by priority:
   - create_entity: 1
   - create_field: 2
   - create_relationship: 3
   - create_index: 4
       ↓
2. For each operation:
   session = useAppStore.getState().session

   switch (operation.name) {
     case 'create_entity':
       → session.createTable({...})
           ↓
       Zustand store updated
           ↓
       Database lenses updated
           ↓
       UI re-renders with new table
   }
```

***

## Key Components

### Active Files

| File                                      | Purpose          | Role                                     |
| ----------------------------------------- | ---------------- | ---------------------------------------- |
| `src/components/AI/AIAssistant.tsx`       | Main UI          | Conversation interface, coordinates flow |
| `src/components/AI/aiService.ts`          | API Client       | Makes requests to /api/ai-modeling       |
| `src/components/AI/operationsExecutor.ts` | Execution Engine | **ONLY place that modifies database**    |
| `src/components/AI/ProposalReview.tsx`    | Review UI        | Shows proposals, approval buttons        |
| `functions/api/ai-modeling.ts`            | API Endpoint     | Stateless proposal generator             |
| `functions/lib/ai-graph/nodes.ts`         | LangGraph Nodes  | AI workflow logic                        |
| `functions/lib/ai-graph/prompts.ts`       | Prompts          | System prompts for each phase            |

### Reference-Only Files (Don't Execute)

| File                                   | Purpose              | Status                                   |
| -------------------------------------- | -------------------- | ---------------------------------------- |
| `functions/lib/ai-graph/operations.ts` | Operation simulation | Simulates operations but doesn't execute |
| `functions/lib/ai-graph/tools.ts`      | Tool definitions     | Referenced by nodes for schema           |

***

## Operation Types & Priorities

### Execution Order (enforced by operationsExecutor.ts)

1. **Priority 1**: `create_entity` - Create tables first
2. **Priority 2**: `create_field` - Add fields to tables
3. **Priority 3**: `create_relationship`, `create_foreign_key` - Connect entities
4. **Priority 4**: `create_index` - Optimize queries
5. **Priority 5**: `update_entity`, `update_field` - Modify existing
6. **Priority 6**: `delete_field` - Remove fields
7. **Priority 7**: `delete_entity` - Remove tables last

### Available Operations

**Conceptual Phase:**

* `create_entity` - Create table without fields
* `create_relationship` - Define entity relationships
* `update_entity` - Rename or change entity description
* `delete_entity` - Remove entity

**Logical Phase:**

* `create_field` - Add field with data type
* `update_field` - Change field properties
* `delete_field` - Remove field
* `create_foreign_key` - Create FK relationship

**Physical Phase:**

* `create_index` - Add index for performance
* `set_physical_type` - Set DB-specific type
* `add_constraint` - Add CHECK/UNIQUE constraints
* `add_default_value` - Set default values

***

## Design Patterns

### Pattern: Stateless Server, Stateful Client

**Why this pattern?**

* Server is on Cloudflare Workers (stateless by design)
* Client has Zustand store with full application state
* AI gateway calls are expensive - minimize them
* User approval required before changes

**Benefits:**

* ✅ Fast client-side execution
* ✅ No server persistence required
* ✅ User sees changes immediately
* ✅ Easy to undo (store has history)

**Tradeoffs:**

* ⚠️ No server-side validation of execution
* ⚠️ Client must handle all error cases
* ⚠️ Operations could fail silently

### Pattern: Proposal Review Before Execution

**Flow:**

1. AI suggests operations (server-side)
2. User reviews proposals (client-side)
3. User approves/rejects (client-side)
4. Client executes approved operations

**Benefits:**

* ✅ User control over changes
* ✅ Transparency in AI actions
* ✅ Can reject bad suggestions
* ✅ Builds trust in AI

***

## Data Flow

### GraphState Interface

```typescript
interface GraphState {
  database: NormalizedDatabase;           // Current schema
  messages: Message[];                    // Conversation history
  userIntent?: string;                    // 'design' | 'question' | 'explain' | 'validate'
  workType?: string;                      // 'conceptual' | 'logical' | 'physical' | 'mixed'
  currentGoal?: string;                   // What user wants
  proposedOperations: ToolCall[];         // Operations AI suggests
  approvedOperations: string[];           // IDs of approved ops
  rejectedOperations: string[];           // IDs of rejected ops
  suggestions: Suggestion[];              // AI suggestions/warnings
  error?: string;                         // Error message if any
}
```

### Message Flow

```typescript
// User message → Server
POST /api/ai-modeling
{
  userMessage: "Add a User table",
  database: NormalizedDatabase,
  conversationHistory: Message[]
}

// Server → Client response
{
  message: {
    content: string,              // AI response text
    proposals: ToolCall[],        // Operations to review
    suggestions: Suggestion[],    // Optional suggestions
    needsApproval: boolean        // Whether to show review UI
  },
  state: GraphState               // Full graph state
}
```

***

## Error Handling

### Server-Side Errors

* OpenAI API failures → Return error message
* Invalid state → Return error in GraphState
* Missing env vars → Return 500 error

### Client-Side Errors

* Operation execution failures → Continue with remaining ops
* Network errors → Show error message in chat
* Invalid operations → Skip and log warning

### Error Recovery

* Operations are independent - one failure doesn't stop others
* User can retry failed operations
* Chat history preserved across errors

***

## Performance Considerations

### Client-Side Execution Benefits

* No server round-trip for execution
* Immediate UI updates
* Can batch multiple operations
* Offline execution possible

### Optimization Opportunities

* Cache AI responses for similar queries
* Batch operation execution
* Debounce user input
* Stream AI responses (future)

***

## Security Considerations

### Current Security Measures

* Server validates all inputs
* Operations limited to schema changes only
* No SQL injection risk (uses store operations)
* AI Gateway rate limiting

### Potential Risks

* Client can execute any operation (no server validation)
* AI could suggest harmful operations
* No audit trail of changes

### Recommendations

* Add operation validation before execution
* Log all AI suggestions and user approvals
* Implement rate limiting on client
* Add undo/redo functionality

***

## Future Improvements

### Potential Enhancements

1. **Streaming Responses**: Stream AI text as it's generated
2. **Undo/Redo**: Full operation history with rollback
3. **Server-Side Execution**: Optional server validation/execution
4. **Operation Batching**: Group related operations
5. **AI Memory**: Remember user preferences across sessions
6. **Conflict Detection**: Warn about conflicting operations
7. **Schema Validation**: Validate operations before execution
8. **Multi-User**: Handle concurrent schema edits

### Architecture Evolution

* Consider moving execution to server for validation
* Add WebSocket for real-time collaboration
* Implement CRDT for conflict-free schema merging
* Add event sourcing for full audit trail

***

## Troubleshooting

### "Unknown operation" Error

* **Cause**: operationsExecutor.ts missing operation handler
* **Fix**: Add operation case to executeOperation() switch

### "Cannot create relationship: table not found"

* **Cause**: Operations executed out of order
* **Fix**: Check priority map in operationsExecutor.ts

### AI suggests invalid operations

* **Cause**: Prompts need refinement or tool schemas unclear
* **Fix**: Update prompts in functions/lib/ai-graph/prompts.ts

### Operations not persisting

* **Cause**: Store operations failing silently
* **Fix**: Check console for errors, ensure session is valid

***

## Testing Strategy

### Unit Tests

* ✅ operationsExecutor: Each operation type
* ✅ aiService: API client mocking
* ❌ LangGraph nodes: Mock OpenAI responses

### Integration Tests

* ✅ Full flow: Message → Proposal → Execution
* ❌ Error handling: Failed operations
* ❌ Edge cases: Invalid operations, missing tables

### E2E Tests

* ❌ User creates table via AI
* ❌ User creates relationship via AI
* ❌ User rejects proposal
* ❌ Undo/redo operations

***

## Glossary

**LangGraph**: Framework for building AI workflows with nodes and edges **GraphState**: State object passed between LangGraph nodes **Operation**: A schema change action (create\_entity, create\_field, etc.) **Proposal**: AI-suggested operation awaiting user approval **ToolCall**: OpenAI function call representing an operation **Session**: Zustand store session with database operations **NormalizedDatabase**: DBML schema representation

***

## Maintainers

**Last Updated**: 2025-10-30 **Architecture Version**: 2.0 (post-cleanup) **Status**: Stable


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.archibase.app/readme.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
