> ## Documentation Index
> Fetch the complete documentation index at: https://docs.greenflash.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Get started with Greenflash's [Python SDK](https://github.com/greenflash-ai/python) for seamless integration with the Greenflash REST API in your Python applications.

## Quick Start

Install the package and start logging messages in minutes:

```bash theme={"theme":{"light":"github-light","dark":"vesper"}}
# From PyPI (pre-release)
pip install --pre greenflash

# Optional: better async performance
pip install --pre "greenflash[aiohttp]"
```

### Logging Your First Message

```python theme={"theme":{"light":"github-light","dark":"vesper"}}
import os
from greenflash import Greenflash

client = Greenflash(api_key=os.environ.get("GREENFLASH_API_KEY"))

# Log your first conversation
create_response = client.messages.create(
    product_id="YOUR_PRODUCT_ID",
    external_user_id="USER_ID",
    external_conversation_id="CONVO_ID",
    messages=[
        { "role": "user", "content": "Hello, how can you help me today?" },
        { "role": "assistant", "content": "I can answer any questions you have!" },
    ],
)
```

**Pro tip:** Use python-dotenv and store `GREENFLASH_API_KEY` in a `.env` file to avoid hard-coding sensitive information.

### Async Support

For better performance in async applications:

```python theme={"theme":{"light":"github-light","dark":"vesper"}}
import os
import asyncio
from greenflash import AsyncGreenflash

client = AsyncGreenflash(api_key=os.environ.get("GREENFLASH_API_KEY"))

async def main():
    response = client.messages.create(
        product_id="YOUR_PRODUCT_ID",
        external_user_id="USER_ID",
        external_conversation_id="CONVO_ID",
        messages=[{ "role": "user", "content": "..." }],
    )
    print(f"Conversation ID: {response.conversation_id}")

asyncio.run(main())
```

**Performance Note:** Install the `[aiohttp]` extra and pass `DefaultAiohttpClient()` for optimal async performance.

## Type Safety

The SDK provides comprehensive type support for better development experience:

```python theme={"theme":{"light":"github-light","dark":"vesper"}}
from greenflash import Greenflash

client = Greenflash(api_key=os.environ.get("GREENFLASH_API_KEY"))

# Type-safe message creation with TypedDict
params: dict = {
    "product_id": "YOUR_PRODUCT_ID",
    "external_user_id": "USER_ID",
    "external_conversation_id": "CONVO_ID",
    "messages": [{ "role": "user", "content": "..." }],
}

response = client.messages.create(**params)
```

**Type Features:**

* **Requests**: Use TypedDict for type-safe parameters
* **Responses**: Pydantic models with `.to_dict()` and `.to_json()` methods
* **VS Code**: Enable `python.analysis.typeCheckingMode = "basic"` for inline validation

## Handle Errors Gracefully

The SDK provides specific error classes for different failure scenarios:

```python theme={"theme":{"light":"github-light","dark":"vesper"}}
import greenflash
from greenflash import Greenflash

client = Greenflash(api_key=os.environ.get("GREENFLASH_API_KEY"))

try:
    response = client.messages.create(/* ... */)
except greenflash.APIConnectionError:
    # Handle network connection issues
    print("Network error occurred")
except greenflash.RateLimitError:
    # Handle rate limiting
    print("Rate limit exceeded")
except greenflash.APIStatusError as e:
    # Handle API errors with status codes
    print(f"API Error {e.status_code}: {e.response}")
except greenflash.APIError:
    # Catch any other API-related errors
    print("API error occurred")
```

**Available Error Classes:**

* `APIConnectionError` - Network connection issues
* `RateLimitError` - Too many requests
* `APIStatusError` - Non-2xx responses with status codes
* `APITimeoutError` - Request timeout
* `APIError` - Base class for all API errors

## Configure Retry Behavior

Automatically retry failed requests with intelligent backoff:

```python theme={"theme":{"light":"github-light","dark":"vesper"}}
from greenflash import Greenflash

# Disable retries globally
client = Greenflash(max_retries=0)

# Override retries for specific request
client.with_options(max_retries=5).messages.create(/* ... */)
```

**Default Retry Strategy:**

* Retries on connection errors, `408`, `409`, `429`, and `5xx` responses
* Maximum of 2 retries with exponential backoff
* Configurable globally or per request

## Set Request Timeouts

Control how long to wait for responses:

```python theme={"theme":{"light":"github-light","dark":"vesper"}}
from greenflash import Greenflash

# Set global timeout to 20 seconds
client = Greenflash(timeout=20.0)

# Override timeout for specific request
client.with_options(timeout=5.0).messages.create(/* ... */)
```

**Timeout Behavior:**

* Default timeout: 60 seconds
* Throws `APITimeoutError` on timeout
* Configurable globally or per request

## Advanced Features

### Access Raw HTTP Response

Get full control over the HTTP response for custom handling:

```python theme={"theme":{"light":"github-light","dark":"vesper"}}
# Get raw response with headers
raw_response = client.messages.create(/* ... */).with_raw_response()
print("Custom header:", raw_response.headers.get("X-My-Header"))

# Stream response body
stream_response = client.messages.create(/* ... */).with_streaming_response()
for chunk in stream_response.iter_content():
    print(chunk)
```

### Configure Logging

Control SDK logging verbosity using environment variables:

```bash theme={"theme":{"light":"github-light","dark":"vesper"}}
# Set log level via environment variable
export GREENFLASH_LOG=info
# or
export GREENFLASH_LOG=debug
```

**Log Levels:**

* `error` - Only errors (default)
* `info` - General information
* `debug` - Detailed debugging info

**Note:** The SDK uses Python's standard logging module, so you can integrate with your existing logging configuration.
