gemini-connector 0.1.1
A Python library for connecting to and interacting with Google Gemini AI API
License: MIT
Requires Python: <4.0.0,>=3.11.5
Keywords: gemini-api, google-ai, llm-connector, ai-integration, natural-language-processing, nlp, api-client, generative-ai

# Gemini Connector

[![Python](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![Poetry](https://img.shields.io/badge/poetry-managed-blue.svg)](https://python-poetry.org/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Code style: autopep8](https://img.shields.io/badge/code%20style-autopep8-blue.svg)](https://github.com/hhatto/autopep8)

A generic Python library for connecting to and interacting with the Google Gemini API. This package provides reusable connectivity utilities for applications that need to communicate with Gemini.

## Purpose

This library is designed to be **prompt-agnostic**. It handles:
- API authentication and connectivity
- HTTP request/response handling
- Response parsing utilities
- Error handling

**What this library does NOT contain:**
- Specific prompts (those come from your application)
- Business logic
- Domain-specific functionality

## Installation

```bash
poetry add gemini-connector
```

Or add to your `pyproject.toml`:
```toml
[tool.poetry.dependencies]
gemini_connector = "*"
```

## Quick Start

### Basic Usage

```python
import os
from gemini_connector import GeminiClient, extract_text

# Initialize client (defaults to GeminiModel.GEMINI_2_5_FLASH)
api_key = os.getenv("GEMINI_API_KEY")
client = GeminiClient(api_key=api_key)

# Your application provides the prompt
prompt = "Your specific prompt here"

# Generate content
response = client.generate_content(prompt)

# Extract text from response
text = extract_text(response)
print(text)
```

### Model Selection with Enum

```python
from gemini_connector import GeminiClient, GeminiModel

# Use the enum for type-safe model selection
client = GeminiClient(
    api_key=api_key,
    model=GeminiModel.GEMINI_2_5_PRO  # High quality reasoning
)

# Or use helper methods
fastest_client = GeminiClient(api_key=api_key, model=GeminiModel.get_fastest())
cheapest_client = GeminiClient(api_key=api_key, model=GeminiModel.get_most_economical())
best_client = GeminiClient(api_key=api_key, model=GeminiModel.get_highest_quality())

# Check model properties
if GeminiModel.GEMINI_2_0_FLASH_EXP.is_experimental:
    print("Warning: experimental model")
```

### Advanced Usage

```python
from gemini_connector import (
    GeminiClient,
    GeminiModel,
    extract_text,
    get_finish_reason,
    get_safety_ratings
)

# Initialize with specific model using enum
client = GeminiClient(
    api_key=api_key,
    model=GeminiModel.GEMINI_2_5_FLASH  # Best price-performance
)

# Generate with additional parameters
response = client.generate_content(
    prompt="Your prompt",
    generationConfig={
        "temperature": 0.7,
        "maxOutputTokens": 100
    }
)

# Parse response components
text = extract_text(response)
finish_reason = get_finish_reason(response)
safety_ratings = get_safety_ratings(response)

# Switch models dynamically
client.set_model(GeminiModel.GEMINI_3_PRO)
```

## API Reference

### GeminiClient

Main client for interacting with Gemini API.

**Constructor:**
```python
GeminiClient(api_key: str, model: GeminiModel | str | None = None)
```

**Methods:**
- `generate_content(prompt: str, **kwargs) -> dict[str, any]` - Generate content from a prompt
- `set_model(model: GeminiModel | str) -> None` - Change the model for future requests

### GeminiModel Enum

Type-safe model selection with built-in metadata.

**Current Generation Models:**
- `GEMINI_3_PRO` - Best multimodal understanding, advanced reasoning (most expensive, highest quality)
- `GEMINI_2_5_PRO` - Complex reasoning, coding, STEM (premium pricing)
- `GEMINI_2_5_FLASH` - **Default** - Best price-performance balance (cost-efficient)
- `GEMINI_2_5_FLASH_LITE` - Fastest and cheapest (high-throughput, budget apps)
- `GEMINI_2_5_FLASH_IMAGE` - Image generation and understanding (specialized)

**Previous Generation Models:**
- `GEMINI_2_0_FLASH_EXP` - Experimental, 1M context (not for production)
- `GEMINI_2_0_FLASH` - Stable 2.0 workhorse (legacy apps)
- `GEMINI_2_0_FLASH_LITE` - Budget 2.0 option (simple tasks)

**Helper Methods:**
- `GeminiModel.get_default()` - Returns `GEMINI_2_5_FLASH` (recommended)
- `GeminiModel.get_fastest()` - Returns `GEMINI_2_5_FLASH_LITE`
- `GeminiModel.get_highest_quality()` - Returns `GEMINI_3_PRO`
- `GeminiModel.get_most_economical()` - Returns `GEMINI_2_5_FLASH_LITE`

**Properties:**
- `.is_experimental` - Check if model is experimental
- `.is_flash_variant` - Check if Flash model (speed/cost optimized)
- `.is_pro_variant` - Check if Pro model (quality optimized)

### Response Parser Utilities

Functions for extracting data from API responses:

- `extract_text(response) -> Optional[str]` - Get the first text response
- `extract_all_text_parts(response) -> List[str]` - Get all text parts
- `get_finish_reason(response) -> Optional[str]` - Get completion reason
- `get_safety_ratings(response) -> Optional[List[Dict]]` - Get safety ratings

### Exceptions

Custom exceptions for better error handling:

- `GeminiAPIError` - Base exception
- `GeminiAuthenticationError` - Authentication failures
- `GeminiRateLimitError` - Rate limit exceeded
- `GeminiModelError` - Model-related errors
- `GeminiResponseError` - Response parsing errors

## Usage Example

```python
import os
from gemini_connector import GeminiClient, extract_text

def process_request(user_input):
    # Get API key from environment or secrets manager
    api_key = os.getenv("GEMINI_API_KEY")

    # Initialize client
    client = GeminiClient(api_key=api_key)

    # Your domain-specific prompt
    prompt = build_your_specific_prompt(user_input)

    # Call Gemini
    response = client.generate_content(prompt)
    text = extract_text(response)

    return text
```

## Development

### Build

```bash
make build
```

### Test

```bash
make test
```

### Install

```bash
make install
```

## Examples

See the `examples/` directory for:
- `basic_usage.py` - Simple example
- `advanced_usage.py` - Advanced features

Run examples:
```bash
export GEMINI_API_KEY='your-key'
python examples/basic_usage.py
```

## API Documentation

Full Gemini API documentation: https://ai.google.dev/gemini-api/docs

## License

MIT License - see [LICENSE](LICENSE) file for details