Skip to main content

Official Python SDK for BriefcaseBrain Legal AI Platform

Project description

BriefcaseBrain Python SDK

PyPI version Python License: 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

pip install briefcasebrain-sdk

Quick Start

1. Get Your API Key

Sign up at BriefcaseBrain and get your API key from the dashboard.

2. Set Environment Variable

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

3. Basic Usage

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:

# 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:

# 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:

# 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:

# 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:

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:

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:

# 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:

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

Examples

The examples/ directory contains comprehensive examples:

Run an example:

cd examples
python chat_completion.py

API Reference

BriefcaseBrain Client

Constructor

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

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

Running Tests

pytest

Code Formatting

black briefcasebrain/
isort briefcasebrain/

Type Checking

mypy briefcasebrain/

Support

License

This project is licensed under the MIT License - see the 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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

briefcasebrain_sdk-2.0.0.tar.gz (50.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

briefcasebrain_sdk-2.0.0-py3-none-any.whl (25.0 kB view details)

Uploaded Python 3

File details

Details for the file briefcasebrain_sdk-2.0.0.tar.gz.

File metadata

  • Download URL: briefcasebrain_sdk-2.0.0.tar.gz
  • Upload date:
  • Size: 50.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for briefcasebrain_sdk-2.0.0.tar.gz
Algorithm Hash digest
SHA256 bc065b7021fcc8f6733da236b80d3d329b34a023aae39c6ceccfd6b167505d72
MD5 f27a7ae8aff64823c9907b668278f393
BLAKE2b-256 529d17d79ea9795652c0745450c46b89f929a877820a045e43f4e187d13b4a70

See more details on using hashes here.

File details

Details for the file briefcasebrain_sdk-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for briefcasebrain_sdk-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1439b309fa368dc2f3d0677a9dfee717a69bbd336e3292b12372d6709a20d43c
MD5 e864fd15ef0f4513fa74112f43cc3b63
BLAKE2b-256 2bb0b8e7d9d8415bb92447c7bc570132ca674cc7655f8e60ba1fb47ae89daee1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page