briefcasebrain-sdk 2.0.0
Official Python SDK for BriefcaseBrain Legal AI Platform
License: MIT
Requires Python: >=3.9
Keywords: legal, ai, research, law, api, sdk

# BriefcaseBrain Python SDK

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

The official Python SDK for the BriefcaseBrain Legal AI Platform. Access powerful legal research, chat completions, literature review, and other AI-powered legal tools with a simple, Pythonic interface.

## Features

- **Legal Research**: Search cases, statutes, and perform comprehensive legal analysis
- **Chat Completions**: OpenAI-compatible chat API optimized for legal queries
- **Literature Review**: Manage academic sources and citations
- **Secure Authentication**: API key-based authentication with automatic rate limiting
- **Async/Await Support**: Built for modern Python async applications
- **Type Hints**: Full type annotation support for better IDE experience
- **Automatic Retries**: Built-in retry logic with exponential backoff
- **Streaming Support**: Real-time streaming for chat completions

## Installation

```bash
pip install briefcasebrain-sdk
```

## Quick Start

### 1. Get Your API Key

Sign up at [BriefcaseBrain](https://briefcasebrain.ai) and get your API key from the dashboard.

### 2. Set Environment Variable

```bash
export BRIEFCASEBRAIN_API_KEY="rsk-your-api-key-here"
```

### 3. Basic Usage

```python
import asyncio
from briefcasebrain import BriefcaseBrain

async def main():
    # Initialize client
    client = BriefcaseBrain()

    # Simple chat completion
    response = await client.chat.create_simple(
        message="What are the elements of a valid contract?",
        model="legal-research-v1"
    )
    print(response)

    # Legal research
    research = await client.research.research(
        query="negligence tort law elements",
        jurisdiction="california",
        max_cases=5
    )
    print(research.main_content)

    # Clean up
    await client.close()

# Run the example
asyncio.run(main())
```

## Documentation

### Authentication

The SDK supports multiple authentication methods:

```python
# Method 1: Environment variable (recommended)
client = BriefcaseBrain()  # Uses BRIEFCASEBRAIN_API_KEY

# Method 2: Direct API key
client = BriefcaseBrain(api_key="rsk-your-key")

# Method 3: Custom configuration
client = BriefcaseBrain(
    api_key="rsk-your-key",
    base_url="https://briefcasebrain.ai",
    timeout=30.0,
    max_retries=3
)
```

### Chat Completions

The chat API provides OpenAI-compatible completions optimized for legal queries:

```python
# Simple completion
response = await client.chat.create_simple(
    message="Explain force majeure clauses",
    model="legal-research-v1"
)

# Advanced completion
response = await client.chat.create(
    model="legal-analysis-v1",
    messages=[
        {"role": "system", "content": "You are a contract law expert."},
        {"role": "user", "content": "Draft a non-disclosure agreement."}
    ],
    temperature=0.1,
    max_tokens=1000
)

# Streaming completion
async for chunk in await client.chat.create(
    model="legal-research-v1",
    messages=[{"role": "user", "content": "Explain copyright law"}],
    stream=True
):
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
```

### Legal Research

Perform comprehensive legal research with cases, statutes, and analysis:

```python
# Basic research
research = await client.research.research(
    query="contract breach remedies",
    jurisdiction="federal",
    quality_mode="standard"
)

# Search specific cases
cases = await client.research.search_cases(
    query="software patent validity",
    jurisdiction="federal",
    max_results=10
)

# Search statutes
statutes = await client.research.search_statutes(
    query="employment discrimination",
    jurisdiction="california",
    max_results=5
)

# Legal analysis
analysis = await client.research.analyze_legal_question(
    question="Can an employer mandate overtime?",
    jurisdiction="california",
    practice_area="employment"
)

# Find precedents
precedents = await client.research.get_legal_precedents(
    topic="software licensing disputes",
    jurisdiction="federal",
    date_range={"start_date": "2020-01-01", "end_date": "2024-12-31"}
)
```

### Models

List and inspect available models:

```python
# List all models
models = await client.models.list()
for model in models.data:
    print(f"{model.id} - {model.owned_by}")

# Get available model IDs
model_ids = await client.models.get_available_models()
print(model_ids)  # ['legal-research-v1', 'legal-analysis-v1']

# Check if model exists
exists = await client.models.is_model_available("legal-research-v1")
print(exists)  # True

# Get model info
info = await client.models.get_model_info("legal-research-v1")
print(info.owned_by)  # 'briefcase-ai'
```

## Advanced Usage

### Context Manager

Use the client as an async context manager for automatic cleanup:

```python
async with BriefcaseBrain() as client:
    response = await client.chat.create_simple(
        "What is consideration in contract law?"
    )
    print(response)
# Client automatically closed
```

### Error Handling

The SDK provides specific exception types for different error scenarios:

```python
from briefcasebrain import (
    BriefcaseBrainError,
    AuthenticationError,
    RateLimitError,
    ValidationError,
    APIError
)

try:
    response = await client.chat.create_simple("Legal question")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
    print(f"Invalid request: {e}")
except APIError as e:
    print(f"API error: {e.status_code} - {e.message}")
except BriefcaseBrainError as e:
    print(f"General error: {e}")
```

### Rate Limiting

The SDK automatically handles rate limiting with built-in retry logic:

```python
# Check current rate limits
remaining = client.rate_limiter.get_remaining_requests()
print(f"Remaining: {remaining['minute']}/minute, {remaining['hour']}/hour")

# Configure custom rate limits
client = BriefcaseBrain(
    rate_limit_requests_per_minute=30,
    rate_limit_requests_per_hour=500
)
```

### Custom Headers

Add custom headers for tracking or identification:

```python
client = BriefcaseBrain(
    headers={
        "X-Client-Version": "1.0.0",
        "X-User-ID": "user-123"
    }
)
```

## Examples

The `examples/` directory contains comprehensive examples:

- [`chat_completion.py`](examples/chat_completion.py) - Chat completion examples
- [`legal_research.py`](examples/legal_research.py) - Legal research examples
- [`models_and_auth.py`](examples/models_and_auth.py) - Authentication and model examples

Run an example:

```bash
cd examples
python chat_completion.py
```

## API Reference

### BriefcaseBrain Client

#### Constructor

```python
BriefcaseBrain(
    api_key: Optional[str] = None,
    base_url: str = "https://api.briefcasebrain.ai",
    timeout: float = 60.0,
    max_retries: int = 3,
    rate_limit_requests_per_minute: int = 60,
    rate_limit_requests_per_hour: int = 1000,
    headers: Optional[Dict[str, str]] = None
)
```

#### Properties

- `client.chat` - Chat completions API
- `client.models` - Models API
- `client.research` - Legal research API

### Chat API

#### Methods

- `create()` - Create chat completion
- `create_simple()` - Simple single-message completion
- `create_conversation()` - Multi-turn conversation

### Research API

#### Methods

- `research()` - Comprehensive legal research
- `search_cases()` - Search for legal cases
- `search_statutes()` - Search for statutes
- `analyze_legal_question()` - Analyze legal questions
- `get_legal_precedents()` - Find legal precedents

### Models API

#### Methods

- `list()` - List all available models
- `get_available_models()` - Get model IDs
- `get_model_info()` - Get model details
- `is_model_available()` - Check if model exists

## Requirements

- Python 3.9+
- httpx >= 0.24.0
- pydantic >= 2.0.0
- python-dateutil >= 2.8.0

## Development

### Setup

```bash
git clone https://github.com/briefcasebrain/python-sdk
cd python-sdk
pip install -e ".[dev]"
```

### Running Tests

```bash
pytest
```

### Code Formatting

```bash
black briefcasebrain/
isort briefcasebrain/
```

### Type Checking

```bash
mypy briefcasebrain/
```

## Support

- Email: [support@briefcasebrain.ai](mailto:support@briefcasebrain.ai)
- Documentation: [https://docs.briefcasebrain.ai](https://docs.briefcasebrain.ai)
- Issues: [GitHub Issues](https://github.com/briefcasebrain/python-sdk/issues)

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Changelog

### 2.0.0 (2025-10-05)

- Complete rewrite with modern async/await API
- Added comprehensive type hints with Pydantic models
- Improved error handling and rate limiting
- Added streaming support for chat completions
- Enhanced legal research capabilities
- Better documentation and examples

### 1.0.0 (2024-08-23)

- Initial release with basic API coverage