# Autocolant AI Chatbot API - Project Analysis

## Overview
This is a Flask-based AI chatbot API system that integrates OpenAI's Assistant API with ManyChat and Voiceflow platforms. The system manages AI conversations, lead generation, and customer relationship management for the Autocolant business.

## Architecture

### Core Components

1. **Flask API Server** (`main.py`)
   - Runs on port 5001
   - Provides multiple endpoints for different platforms
   - Handles async and sync chat operations

2. **ManyChat Integration** (`manychat.py`)
   - Async background processing for ManyChat webhooks
   - API callbacks to send responses back to ManyChat
   - Uses custom field updates to deliver responses

3. **OpenAI Assistant Integration** (`assistants.py`)
   - Multiple specialized assistants:
     - Main chatbot assistant
     - Memory/history assistant
     - Summary generation assistant
   - Thread management for conversation continuity

4. **Airtable CRM** (`airtable.py`)
   - Lead capture and storage
   - Conversation logging and analytics
   - Thread processing and summarization

5. **Email System** (`emails.py`)
   - Lead notification emails
   - Report generation and delivery
   - SMTP integration

6. **Utility Functions** (`functions.py`)
   - Configuration loading from `.ini` files
   - Product search functionality
   - Memory management

## Configuration System

The system uses `.ini` files in the `/bobs` directory for multi-tenant configuration:

**Current Bot: HvUM (Autocolant)**
- OpenAI Assistant IDs for main, memory, and summary bots
- Airtable database configuration
- ManyChat API credentials
- Voiceflow project IDs
- Email SMTP settings

## API Endpoints

### Core Chat Endpoints
- `POST /manychatasync` - Async chat for ManyChat (returns immediately, processes in background)
- `POST /voiceflow` - Sync chat for Voiceflow (waits for response)
- `POST /memory` - Chat without saving history (for testing)

### Management Endpoints
- `POST /management` - Returns dashboard URLs for bot management
- `POST /demo` - Returns demo page configuration
- `POST /login` - Authentication endpoint
- `POST /processreport` - Processes unprocessed conversation threads
- `POST /delay` - 4-second delay endpoint (ManyChat flow control)

### Utility
- `GET /` - Simple API status page

## Data Flow

### ManyChat Flow (Async)
1. ManyChat sends webhook to `/manychatasync`
2. API returns immediate response with thread_id
3. Background process handles OpenAI conversation
4. Response sent back to ManyChat via API callback
5. Conversation logged to Airtable

### Voiceflow Flow (Sync)
1. Voiceflow sends request to `/voiceflow`
2. API processes OpenAI conversation synchronously
3. Returns response directly in HTTP response
4. Conversation logged to Airtable

## Key Features

### Function Calling
The OpenAI assistants can call two functions:
- `create_lead` - Captures customer contact information
- `search_products` - Searches the products.json database

### Lead Management
- Automatic lead capture during conversations
- Email notifications to business owner
- Lead data stored in Airtable CRM
- Phone number formatting and validation

### Conversation Analytics
- Response time tracking
- Token usage monitoring
- Conversation summarization
- Thread processing for insights

### Memory System
- Persistent conversation threads
- Knowledge base updates from conversations
- Historical context for improved responses

## File Structure

```
├── main.py                 # Flask API server
├── manychat.py            # ManyChat integration
├── airtable.py            # Airtable CRM operations
├── functions.py           # Utility functions
├── assistants.py          # OpenAI assistant operations
├── emails.py              # Email system
├── bobs/                  # Bot configurations
│   └── HvUM.ini          # Autocolant bot config
├── memories/              # Bot memory files
├── email_templates/       # Email HTML templates
├── web_templates/         # Web UI templates (if any)
├── products.json          # Product database
├── pyproject.toml         # Python dependencies
└── .htaccess             # Web server routing
```

## Dependencies

- **Flask** - Web framework
- **OpenAI** - AI assistant API
- **pyairtable** - Airtable database client
- **requests** - HTTP client for API calls
- **phonenumbers** - Phone number validation
- **jinja2** - Email templating
- **markdown2** - Text formatting

## Current Issues & Debugging Areas

Based on the log activity showing multiple `/delay` calls, there appears to be ManyChat flow issues that may need investigation:

1. **ManyChat Flow Logic** - Multiple delay calls suggest retry loops
2. **Response Timing** - 4-second delays may indicate timeout issues
3. **Error Handling** - Need to check for failed API callbacks
4. **Thread Management** - Verify proper thread_id handling

## Security Considerations

- API keys and credentials stored in `.ini` files
- No authentication on most endpoints
- CORS headers enabled for API access
- Production deployment uses development server (security warning in logs)

## Monitoring & Logs

- Flask access logs in `flask.log`
- Console logging for debugging
- Airtable stores conversation analytics
- Email notifications for system events