# KeiroLabs Python SDK

Official Python SDK for the KeiroLabs API - providing easy access to search, research, and web crawling capabilities.

[![PyPI version](https://badge.fury.io/py/keirolabs.svg)](https://badge.fury.io/py/keirolabs)
[![Python Support](https://img.shields.io/pypi/pyversions/keirolabs.svg)](https://pypi.org/project/keirolabs/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 🚀 Installation

```bash
pip install keirolabs
```

## 📖 Quick Start

```python
from keirolabs import Keiro

# Initialize the client
client = Keiro(api_key="your-api-key-here")

# Perform a basic search (costs 1 credit)
result = client.search("What is machine learning?")
print(result['data'])
print(f"Credits remaining: {result['creditsRemaining']}")

# Get a detailed answer (costs 5 credits)
answer = client.answer("Explain quantum computing in simple terms")
print(answer['data'])

# Perform research
research = client.research("Latest developments in AI")
print(research)
```

## 🔧 Configuration

### Using with Different Environments

```python
# Development (localhost)
client = Keiro(
    api_key="your-api-key",
    base_url="http://localhost:8000/api"
)

# Production
client = Keiro(
    api_key="your-api-key",
    base_url="https://keiro-production.up.railway.app/api"
)

# Or update dynamically
client.set_base_url("https://keiro-production.up.railway.app/api")
```

### Environment Variables

You can also use environment variables in your application:

```python
import os
from keirolabs import Keiro

api_key = os.getenv("KEIRO_API_KEY")
base_url = os.getenv("KEIRO_BASE_URL", "http://localhost:8000/api")

client = Keiro(api_key=api_key, base_url=base_url)
```

Create a `.env` file in your project:
```bash
KEIRO_API_KEY=your-api-key-here
KEIRO_BASE_URL=http://localhost:8000/api
```

And load it using `python-dotenv`:
```bash
pip install python-dotenv
```

```python
from dotenv import load_dotenv
load_dotenv()

import os
from keirolabs import Keiro

client = Keiro(
    api_key=os.getenv("KEIRO_API_KEY"),
    base_url=os.getenv("KEIRO_BASE_URL")
)
```

## 📚 API Reference

### Search APIs

#### `search(query, **kwargs)`
Perform basic search operation.
- **Cost:** 1 credit
- **Args:**
  - `query` (str): Search query
  - `**kwargs`: Additional parameters
- **Returns:** Dict with search results and credits remaining

```python
result = client.search("Python programming tutorials")
```

#### `search_pro(query, **kwargs)`
Advanced search with Pro features.
```python
result = client.search_pro("Advanced Python concepts")
```

#### `search_engine(query, **kwargs)`
Use the search engine functionality.
```python
result = client.search_engine("Best Python libraries 2024")
```

### Answer API

#### `answer(query, **kwargs)`
Generate detailed answers to questions.
- **Cost:** 5 credits
- **Args:**
  - `query` (str): Question to answer
  - `**kwargs`: Additional parameters
- **Returns:** Dict with answer and credits remaining

```python
answer = client.answer("How does blockchain work?")
```

### Research APIs

#### `research(query, **kwargs)`
Perform research on a topic.
```python
research = client.research("Climate change solutions")
```

#### `research_pro(query, **kwargs)`
Advanced research with Pro features.
```python
research = client.research_pro("Advanced AI research papers")
```

### Web Crawler API

#### `web_crawler(url, **kwargs)`
Crawl and extract data from websites.
```python
data = client.web_crawler("https://example.com")
```

### Utility Methods

#### `health_check()`
Check API health status.
```python
health = client.health_check()
print(health)
```

#### `set_base_url(base_url)`
Update the base URL.
```python
client.set_base_url("https://api.keiro.com/api")
```

## 🛡️ Error Handling

The SDK provides specific exception classes for different error scenarios:

```python
from keirolabs import Keiro
from keirolabs.exceptions import (
    KeiroAuthError,
    KeiroRateLimitError,
    KeiroValidationError,
    KeiroConnectionError,
    KeiroAPIError,
)

client = Keiro(api_key="your-api-key")

try:
    result = client.search("test query")
except KeiroAuthError:
    print("Invalid API key")
except KeiroRateLimitError:
    print("Out of credits")
except KeiroValidationError as e:
    print(f"Validation error: {e}")
except KeiroConnectionError as e:
    print(f"Connection failed: {e}")
except KeiroAPIError as e:
    print(f"API error: {e}")
```

### Exception Types

- **`KeiroError`**: Base exception for all SDK errors
- **`KeiroAuthError`**: Invalid API key or authentication failure
- **`KeiroRateLimitError`**: Out of credits or rate limit exceeded
- **`KeiroValidationError`**: Invalid request parameters
- **`KeiroConnectionError`**: Network or connection issues
- **`KeiroAPIError`**: General API errors

## 🔐 Context Manager

Use the SDK with context manager for automatic cleanup:

```python
with Keiro(api_key="your-api-key") as client:
    result = client.search("query")
    print(result)
# Session automatically closed
```

## ⚙️ Advanced Usage

### Custom Timeout

```python
client = Keiro(
    api_key="your-api-key",
    timeout=60  # 60 seconds timeout
)
```

### Passing Additional Parameters

```python
# All methods accept **kwargs for additional parameters
result = client.search(
    query="Python",
    custom_param="value",
    another_param=123
)
```

## 📝 Examples

### Example 1: Basic Search and Answer

```python
from keirolabs import Keiro

client = Keiro(api_key="your-api-key")

# Search for information
search_result = client.search("Best practices for Python")
print("Search Results:", search_result['data'])

# Get detailed answer
answer = client.answer("What are Python decorators?")
print("Answer:", answer['data'])
print(f"Credits Used: {answer['creditsRemaining']}")
```

### Example 2: Web Crawling

```python
from keirolabs import Keiro

client = Keiro(api_key="your-api-key")

# Crawl a website
crawl_data = client.web_crawler("https://example.com")
print("Crawled Data:", crawl_data)
```

### Example 3: Error Handling

```python
from keirolabs import Keiro
from keirolabs.exceptions import KeiroRateLimitError, KeiroAuthError

client = Keiro(api_key="your-api-key")

try:
    results = []
    queries = ["query1", "query2", "query3"]
    
    for query in queries:
        result = client.search(query)
        results.append(result)
        
except KeiroRateLimitError:
    print("Ran out of credits! Please add more credits to continue.")
except KeiroAuthError:
    print("Authentication failed. Check your API key.")
```

## 🧪 Testing

Create a test file to verify your setup:

```python
# test_keiro.py
from keirolabs import Keiro
import os

def test_sdk():
    client = Keiro(
        api_key=os.getenv("KEIRO_API_KEY"),
        base_url="http://localhost:8000/api"
    )
    
    # Test health check
    health = client.health_check()
    print("✓ Health check passed:", health)
    
    # Test search
    result = client.search("test query")
    print("✓ Search passed:", result)
    
    print("\n✅ All tests passed!")

if __name__ == "__main__":
    test_sdk()
```

## 📦 Requirements

- Python >= 3.7
- requests >= 2.28.0

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🔗 Links

- **Homepage:** https://keiro.com
- **Documentation:** https://docs.keiro.com
- **GitHub:** https://github.com/yourusername/keiro-python-sdk
- **PyPI:** https://pypi.org/project/keirolabs/

## 💬 Support

For support, email support@keiro.com or open an issue on GitHub.

## 📋 Changelog

### Version 0.1.0 (Initial Release)
- ✅ Basic search functionality
- ✅ Answer generation
- ✅ Research capabilities
- ✅ Web crawler
- ✅ Comprehensive error handling
- ✅ Environment-aware base URL configuration
- ✅ Context manager support

---

Made with ❤️ by the KeiroLabs Team
