grokwrapper 0.2.0
Lightweight wrapper for Grok by xAI – access Grok models via web interface without API key
License: MIT
Requires Python: >=3.8

<div align="center">

# 🚀 grokwrapper

[![PyPI Version](https://img.shields.io/pypi/v/grokwrapper.svg)](https://pypi.org/project/grokwrapper/)
[![Python Version](https://img.shields.io/pypi/pyversions/grokwrapper.svg)](https://pypi.org/project/grokwrapper/)
[![Downloads](https://static.pepy.tech/badge/grokwrapper)](https://pepy.tech/project/grokwrapper)


### Lightweight wrapper for Grok by xAI

Access Grok models via web interface without API key • Reverse proxy to grok.x.ai • Easy to use

---

[Documentation](#documentation) • [Installation](#installation) • [Quick Start](#quick-start) • [Examples](#examples) • [API Reference](#api-reference)

</div>

---

## ⚠️ Disclaimer

This library is for **educational and research purposes only**. Use responsibly and respect xAI's terms of service. The authors are not responsible for any misuse or violations of terms of service.

---

## 🌟 Features

- ✨ **No API Key Required** – Access Grok through web interface
- 🚀 **Simple & Clean API** – Easy-to-use Python interface
- 💬 **Chat Completion** – Send prompts and receive responses
- 🔥 **Streaming Support** – Real-time token-by-token streaming
- 🌐 **Proxy Support** – HTTP/SOCKS5 proxy integration
- 🛡️ **Rate Limiting** – Automatic request throttling
- 🔒 **Session Management** – Persistent sessions with cookie handling
- 🔄 **Auto Retry** – Exponential backoff on failures
- 🎨 **Custom Headers** – User-agent rotation and custom headers
- ⚡ **Fast & Lightweight** – Minimal dependencies, no bloat

---

## 📦 Installation

### PyPI (Recommended)

```bash
pip install grokwrapper
```

## Quick Start
```python
from grokwrapper import GrokClient

# Initialize client
client = GrokClient()

# Send a simple chat message
response = client.chat("Hello! How are you today?")
print(response)

# Streaming example
for chunk in client.stream_chat("Explain quantum computing in simple terms"):
    print(chunk, end="", flush=True)
```

# 📖 Documentation
## Configuration

Create a .env file in your project root:
```env
# Proxy settings (optional)
# GROK_PROXY=http://user:pass@host:port
# GROK_PROXY=socks5://user:pass@host:port

# Custom User-Agent (optional)
# USER_AGENT=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36

# Request delay in seconds (default: 2.0)
# REQUEST_DELAY=2.0

# Request timeout in seconds (default: 30)
# REQUEST_TIMEOUT=30
```

## 💡 Examples
### Basic Chat
```python
from grokwrapper import GrokClient

client = GrokClient()

# Simple chat
response = client.chat("What is the capital of France?")
print(response)
# Output: "The capital of France is Paris."
```

### Streaming Chat
```python
from grokwrapper import GrokClient

client = GrokClient()

# Stream response token by token
print("Assistant: ", end="", flush=True)
for chunk in client.stream_chat("Write a short poem about AI"):
    print(chunk, end="", flush=True)
```

### Custom Model
```python
from grokwrapper import GrokClient

client = GrokClient()

# Specify model (grok-3, grok-beta, etc.)
response = client.chat(
    "Explain machine learning",
    model="grok-beta"
)
print(response)
```

### With Proxy
```python
from grokwrapper import GrokClient

# Using proxy
client = GrokClient(
    proxy="http://user:pass@proxy.example.com:8080",
    timeout=60,
    delay=3.0
)

response = client.chat("Hello!")
```

### Batch Processing
```python
from grokwrapper import batch_chat

prompts = [
    "What is Python?",
    "Explain recursion",
    "What is a decorator?"
]

responses = batch_chat(prompts, delay_between=1.5)

for prompt, response in zip(prompts, responses):
    print(f"Q: {prompt}")
    print(f"A: {response}\n")
```

### Error Handling
```python
from grokwrapper import GrokClient
from grokwrapper.exceptions import (
        RateLimitError,
        AuthenticationError,
        BlockedError,
        APIError,
        NetworkError,
    )

client = GrokClient()

try:
    response = client.chat("Hello!")
    print(response)
    
except RateLimitError:
    print("Rate limit exceeded. Wait and try again.")
    
except AuthenticationError:
    print("Authentication failed. Session may have expired.")
    
except BlockedError:
    print("Access blocked. IP or session restricted.")
    
except NetworkError:
    print("Network error. Check your connection.")
    
except APIError as e:
    print(f"API error: {e}")

```

### Context Manager
```python
from grokwrapper import GrokClient

# Automatically closes session
with GrokClient() as client:
    response = client.chat("What's the weather like?")
    print(response)
```

### Advanced Configuration
```python
from grokwrapper import GrokClient, setup_logging

# Setup logging
logger = setup_logging(level=20, filename="grokwrapper.log")

# Custom client
client = GrokClient(
    proxy="socks5://user:pass@proxy.example.com:1080",
    user_agent="Custom User Agent String",
    timeout=45,
    delay=2.5,
    auto_retry=True
)

response = client.chat("Tell me about space exploration")
print(response)

# Get client statistics
stats = client.get_stats()
print(f"Requests made: {stats['requests_made']}")
```

# 🔧 API Reference
## GrokClient
```python
class GrokClient(proxy=None, user_agent=None, timeout=None, delay=None, auto_retry=True)
```


# 🙏 Acknowledgments
    - Thanks to the xAI team for creating Grok
    - Inspired by other reverse-engineered AI wrappers
    - Built with ❤️ by the open-source community