Skip to main content

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

Metadata

Release files for briefcasebrain-sdk 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for briefcasebrain-sdk 2.0.0
File Size Uploaded Provenance Actions
briefcasebrain_sdk-2.0.0.tar.gz 50.4 kB Without provenance Details for briefcasebrain_sdk-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for briefcasebrain-sdk 2.0.0
File Interpreter ABI Platform Actions
briefcasebrain_sdk-2.0.0-py3-none-any.whl Python 3 none any Details for briefcasebrain_sdk-2.0.0-py3-none-any.whl

Total release size: 75.3 kB

Release files / briefcasebrain_sdk-2.0.0.tar.gz

Download URL briefcasebrain_sdk-2.0.0.tar.gz
Size 50.4 kB
Tags Source
SHA-256 checksum
How to use checksums
bc065b7021fcc8f6733da236b80d3d329b34a023aae39c6ceccfd6b167505d72
BLAKE2b-256 checksum
How to use checksums
529d17d79ea9795652c0745450c46b89f929a877820a045e43f4e187d13b4a70
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.7

Release files / briefcasebrain_sdk-2.0.0-py3-none-any.whl

Download URL briefcasebrain_sdk-2.0.0-py3-none-any.whl
Size 25.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1439b309fa368dc2f3d0677a9dfee717a69bbd336e3292b12372d6709a20d43c
BLAKE2b-256 checksum
How to use checksums
2bb0b8e7d9d8415bb92447c7bc570132ca674cc7655f8e60ba1fb47ae89daee1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.7

Security for briefcasebrain-sdk 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page