# {{name}}

{{description}}

## Overview

This project provides a web-based chat interface for Lab agents and RAG assistants using Gradio. Features include streaming responses, conversation history, and configurable model parameters.

## Prerequisites

1. **PyGEAI installed and configured:**
   ```bash
   pip install pygeai
   geai configure --key YOUR_API_KEY --url YOUR_API_URL
   ```

2. **Python 3.8+**

## Installation

Install dependencies:

```bash
pip install -r requirements.txt
```

## Usage

Start the application:

```bash
python app.py
```

The web interface will be available at:
- Local: http://localhost:7860
- Network: http://0.0.0.0:7860

## Features

### Chat Interface

- Real-time streaming responses
- Conversation history maintained in session
- Clear conversation button

### Configurable Settings

- **Model Selection**: Choose Lab agents or RAG assistants
- **Temperature**: Control response randomness (0.0 - 1.0)
- **Max Tokens**: Set maximum response length (100 - 4000)

### Model Formats

Specify models using these formats:

- **Lab Agent**: `saia:agent:agent_name`
- **RAG Assistant**: `saia:assistant:assistant_name`

## Example Usage

1. Start the app with `python app.py`
2. Open http://localhost:7860 in your browser
3. In the Settings panel, enter your model:
   - For Lab agent: `saia:agent:my_agent`
   - For RAG assistant: `saia:assistant:my_rag`
4. Adjust temperature and max tokens as needed
5. Type your message and click Send
6. Watch responses stream in real-time

## Customization

### Change Port

Edit `app.py`:

```python
if __name__ == "__main__":
    demo.queue()
    demo.launch(server_name="0.0.0.0", server_port=8080)  # Changed from 7860
```

### Add Authentication

```python
if __name__ == "__main__":
    demo.queue()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        auth=("username", "password")
    )
```

### Custom Theme

```python
with gr.Blocks(title="{{name}}", theme=gr.themes.Soft()) as demo:
    # ... rest of code
```

Available themes: `Base`, `Default`, `Glass`, `Monochrome`, `Soft`

### Add System Prompt

Modify the `chat_with_model` function:

```python
def chat_with_model(message, history, model_name, temperature, max_tokens):
    messages = [
        {"role": "system", "content": "You are a helpful assistant. Be concise."}
    ]
    
    for user_msg, assistant_msg in history:
        messages.append({"role": "user", "content": user_msg})
        messages.append({"role": "assistant", "content": assistant_msg})
    
    # ... rest of function
```

### Add File Upload

Add file upload component:

```python
with gr.Column(scale=3):
    chatbot = gr.Chatbot(...)
    
    file_upload = gr.File(
        label="Upload Document",
        file_types=[".txt", ".pdf", ".md"]
    )
    
    # ... rest of code
```

### Enable Sharing

For temporary public URL:

```python
if __name__ == "__main__":
    demo.queue()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True  # Creates public URL
    )
```

### Add Example Prompts

```python
with gr.Column(scale=3):
    chatbot = gr.Chatbot(...)
    
    gr.Examples(
        examples=[
            "What is machine learning?",
            "Explain the difference between AI and ML",
            "How does deep learning work?"
        ],
        inputs=msg
    )
    
    # ... rest of code
```

## Deployment

### With Docker

Create `Dockerfile`:

```dockerfile
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app.py .

EXPOSE 7860

CMD ["python", "app.py"]
```

Build and run:

```bash
docker build -t pygeai-gradio-ui .
docker run -p 7860:7860 pygeai-gradio-ui
```

### On Hugging Face Spaces

1. Create a new Space at https://huggingface.co/spaces
2. Upload `app.py` and `requirements.txt`
3. Set environment variables for PyGEAI credentials
4. Deploy

### On Cloud Platforms

#### AWS EC2

```bash
# Install dependencies
pip install -r requirements.txt

# Run with nohup
nohup python app.py > gradio.log 2>&1 &
```

#### Google Cloud Run

Create `Dockerfile` and deploy:

```bash
gcloud run deploy pygeai-ui \
  --source . \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated
```

## Troubleshooting

**Port already in use:**
Change the port in `app.py` or kill the process using port 7860:
```bash
lsof -ti:7860 | xargs kill -9
```

**Gradio not found:**
Install gradio: `pip install gradio`

**PyGEAI configuration errors:**
Run `geai config show` to verify credentials.

**Slow streaming:**
Check network connection and model performance.

**Interface not accessible:**
Ensure firewall allows port 7860.

## Advanced Features

### Add Conversation Export

```python
def export_conversation(history):
    import json
    return json.dumps(history, indent=2)

export_btn = gr.Button("Export Conversation")
output = gr.File(label="Download")

export_btn.click(
    export_conversation,
    inputs=chatbot,
    outputs=output
)
```

### Add Analytics

```python
import time

chat_logs = []

def log_interaction(user_msg, bot_response):
    chat_logs.append({
        "timestamp": time.time(),
        "user": user_msg,
        "bot": bot_response
    })
```

### Multi-Model Support

```python
model_dropdown = gr.Dropdown(
    choices=[
        "saia:agent:agent1",
        "saia:agent:agent2",
        "saia:assistant:rag1"
    ],
    label="Select Model",
    value="saia:agent:agent1"
)
```

## Resources

- [Gradio Documentation](https://www.gradio.app/docs/)
- [PyGEAI Chat Client](https://pygeai.readthedocs.io/en/latest/chat/)
- [Gradio Themes](https://www.gradio.app/guides/theming-guide)
- [Gradio Components](https://www.gradio.app/docs/components)

## Next Steps

- Add conversation persistence (save/load)
- Implement user authentication
- Add multi-language support
- Create conversation analytics dashboard
- Integrate document upload for RAG assistants
