# VeloxAI

⚡ **Fast and Simple AI Library** - Text generation (Vtext) and Image generation (Vimg)

## Installation

```bash
pip install veloxai
```

## Quick Start

```python
from veloxai import Vtext, Vimg

# Text Generation
vtext = Vtext(token="your-token")
response = vtext.chat("Hello, who are you?")
print(response['response'])

# Image Generation
vimg = Vimg(token="your-token")
result = vimg.create("A sunset over mountains")
print(result['images'])
```

---

## Features

### Vtext (Text Generation)
- ✅ Chat completions
- ✅ Streaming responses (like OpenAI)
- ✅ File attachments (images, PDFs)
- ✅ Multiple models
- ✅ Fine-tuning/training
- ✅ System prompts

### Vimg (Image Generation)
- ✅ Text-to-image
- ✅ Image-to-image
- ✅ Auto wait for completion
- ✅ Manual polling

---

## Vtext Usage

### Basic Chat

```python
from veloxai import Vtext

vtext = Vtext(token="your-token")

# Simple chat
response = vtext.chat("What is Python?")
if response['success']:
    print(response['response'])
```

### Streaming (OpenAI-style)

```python
# Stream the response word by word
for chunk in vtext.chat("Write a long story", stream=True):
    print(chunk, end='', flush=True)
```

### Chat with Files

```python
# Attach an image
response = vtext.chat(
    message="What's in this image?",
    file="photo.jpg"
)

# Attach a PDF
response = vtext.chat(
    message="Summarize this document",
    file="document.pdf"
)
```

### Use Different Models

```python
# List available models
models = vtext.models()
print(models['models'])

# Use specific model
response = vtext.chat(
    message="Write a poem",
    model="gpt-4"
)
```

### System Prompts

```python
response = vtext.chat(
    message="Tell me about yourself",
    system="You are a helpful Python tutor"
)
```

### OpenAI-Compatible Completion

```python
response = vtext.completion(
    prompt="Once upon a time",
    max_tokens=100,
    temperature=0.7,
    stream=False
)
```

### Fine-Tuning (Personal Training)

```python
# Train the AI
vtext.train(
    identity="Expert Python programmer",
    role="Help users write better code",
    extra="Always provide examples"
)

# Now chats use your training
response = vtext.chat("How do I use decorators?")

# Check current training
training = vtext.get_training()
print(training['training'])

# Clear training
vtext.clear_training()
```

---

## Vimg Usage

### Basic Image Generation

```python
from veloxai import Vimg

vimg = Vimg(token="your-token")

# Generate and wait for completion
result = vimg.create("A beautiful sunset over mountains")

if result['success']:
    for url in result['images']:
        print(f"Image: {url}")
```

### Manual Control

```python
# Start generation (don't wait)
result = vimg.generate("A futuristic city")
record_id = result['record_id']

# Check status manually
status = vimg.status(record_id)
print(status['status'])  # PENDING, PROCESSING, DONE, or FAILED

# Wait for completion
final = vimg.wait(record_id, timeout=180)
print(final['images'])
```

### Image-to-Image

```python
# Generate based on existing image
result = vimg.create(
    prompt="Make it look like a watercolor painting",
    init_image="photo.jpg"
)
```

### Quick Generation (No Wait)

```python
# Start generation and return immediately
result = vimg.create(
    prompt="A dragon",
    wait=False
)

# Returns record_id for later checking
record_id = result['record_id']
```

---

## Complete Examples

### Example 1: Simple Chatbot

```python
from veloxai import Vtext

vtext = Vtext(token="your-token")

while True:
    user_input = input("You: ")
    if user_input.lower() == 'quit':
        break
    
    response = vtext.chat(user_input)
    if response['success']:
        print(f"AI: {response['response']}\n")
```

### Example 2: Streaming Chat

```python
from veloxai import Vtext

vtext = Vtext(token="your-token")

print("AI: ", end='')
for chunk in vtext.chat("Tell me a story", stream=True):
    print(chunk, end='', flush=True)
print()
```

### Example 3: Image Generation with Progress

```python
from veloxai import Vimg
import time

vimg = Vimg(token="your-token")

# Start generation
result = vimg.generate("A beautiful landscape")
if not result['success']:
    print(f"Error: {result['error']}")
    exit()

record_id = result['record_id']
print(f"Generation started: {record_id}")

# Poll for completion
while True:
    status = vimg.status(record_id)
    
    if status['status'] == 'DONE':
        print("\nComplete!")
        for i, url in enumerate(status['images'], 1):
            print(f"Image {i}: {url}")
        break
    elif status['status'] == 'FAILED':
        print("\nFailed!")
        break
    
    print(".", end='', flush=True)
    time.sleep(3)
```

### Example 4: Multi-Modal Chat

```python
from veloxai import Vtext

vtext = Vtext(token="your-token")

# Analyze an image
response = vtext.chat(
    message="What objects are in this image?",
    file="room.jpg"
)
print(response['response'])

# Follow-up question
response = vtext.chat("What colors are dominant?")
print(response['response'])
```

---

## API Reference

### Vtext

#### `__init__(token, base_url=None)`
Initialize Vtext client.

#### `chat(message, model="perplexity-ai", system=None, file=None, stream=False)`
Send a chat message.
- Returns: `dict` or `Iterator[str]` if streaming

#### `completion(prompt, model, max_tokens, temperature, stream)`
OpenAI-style completion.

#### `models()`
Get available models.

#### `train(identity, role, extra="")`
Set fine-tuning.

#### `get_training()`
Get current training.

#### `clear_training()`
Clear training.

---

### Vimg

#### `__init__(token, base_url=None)`
Initialize Vimg client.

#### `generate(prompt, init_image=None)`
Start image generation.
- Returns: `{"success": bool, "record_id": str}`

#### `status(record_id)`
Check generation status.
- Returns: `{"status": str, "images": [str]}`

#### `wait(record_id, timeout=180, interval=3)`
Wait for completion.
- Returns: Final status with images

#### `create(prompt, init_image=None, wait=True)`
Generate and optionally wait.
- Returns: Images if `wait=True`, else `record_id`

---

## Advanced Usage

### Environment Variables

```python
import os
from veloxai import Vtext

token = os.getenv('VELOX_TOKEN')
vtext = Vtext(token=token)
```

### Error Handling

```python
response = vtext.chat("Hello")

if response['success']:
    print(response['response'])
else:
    print(f"Error: {response['error']}")
```

### Custom Base URL

```python
vtext = Vtext(
    token="your-token",
    base_url="https://custom-api.example.com"
)
```

### Streaming with Error Handling

```python
try:
    for chunk in vtext.chat("Hello", stream=True):
        if chunk.startswith("Error:"):
            print(f"Stream error: {chunk}")
            break
        print(chunk, end='')
except Exception as e:
    print(f"Exception: {e}")
```

---

## Integration Examples

### Flask API

```python
from flask import Flask, request, jsonify, Response
from veloxai import Vtext

app = Flask(__name__)
vtext = Vtext(token="your-token")

@app.route('/chat', methods=['POST'])
def chat():
    message = request.json['message']
    stream = request.json.get('stream', False)
    
    if stream:
        def generate():
            for chunk in vtext.chat(message, stream=True):
                yield f"data: {chunk}\n\n"
        return Response(generate(), mimetype='text/event-stream')
    else:
        response = vtext.chat(message)
        return jsonify(response)

@app.route('/image', methods=['POST'])
def image():
    prompt = request.json['prompt']
    vimg = Vimg(token="your-token")
    result = vimg.create(prompt)
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)
```

### Discord Bot

```python
import discord
from veloxai import Vtext

vtext = Vtext(token="your-velox-token")
bot = discord.Client()

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    
    if message.content.startswith('!ask'):
        question = message.content[5:]
        response = vtext.chat(question)
        if response['success']:
            await message.channel.send(response['response'])

bot.run('your-discord-token')
```

### Async Wrapper

```python
import asyncio
from veloxai import Vtext

async def async_chat(message):
    vtext = Vtext(token="your-token")
    loop = asyncio.get_event_loop()
    response = await loop.run_in_executor(
        None,
        vtext.chat,
        message
    )
    return response

# Usage
response = asyncio.run(async_chat("Hello"))
```

---

## Comparison with OpenAI

### OpenAI
```python
from openai import OpenAI
client = OpenAI(api_key="key")

response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello"}],
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content, end='')
```

### VeloxAI (Similar API)
```python
from veloxai import Vtext
vtext = Vtext(token="key")

for chunk in vtext.chat("Hello", stream=True):
    print(chunk, end='')
```

**Cleaner and simpler!** ✨

---

## Requirements

- Python 3.7+
- requests >= 2.25.0

---

## License

MIT License - see LICENSE file

---

## Support

- GitHub: https://github.com/yourusername/veloxai
- Issues: https://github.com/yourusername/veloxai/issues
- PyPI: https://pypi.org/project/veloxai/

---

## Changelog

### 1.0.0 (2024-02-08)
- Initial release
- Vtext: Chat, streaming, file support, training
- Vimg: Generation, img2img, auto-wait
- OpenAI-compatible API

---

## Credits

Made with ⚡ by VeloxAI Team