npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

briefcasebrain-sdk

v2.0.2

Published

Official TypeScript SDK for BriefcaseBrain Legal AI Platform - Full-featured client with streaming support

Readme

BriefcaseBrain TypeScript SDK

npm version TypeScript License: MIT

Official TypeScript SDK for the BriefcaseBrain Legal AI Platform. This is a complete rewrite of the original SDK with full TypeScript support, streaming capabilities, and modern async/await patterns.

Features

  • Full TypeScript Support - Complete type definitions and IntelliSense
  • Streaming Support - Real-time chat completions with async iterators
  • Modern API - Built with async/await and modern JavaScript features
  • Built-in Rate Limiting - Token bucket algorithm with configurable limits
  • Automatic Retries - Exponential backoff for robust error handling
  • OpenAI Compatible - Drop-in replacement for OpenAI chat completions
  • Legal AI Specialized - Purpose-built for legal research and analysis
  • Tree-shakeable - ES modules with minimal bundle size
  • Configurable - Extensive configuration options for all use cases

Installation

npm install briefcasebrain-sdk

Quick Start

import { BriefcaseBrain } from 'briefcasebrain-sdk';

// Initialize the client
const client = new BriefcaseBrain({
  apiKey: 'rsk-your-api-key', // or set BRIEFCASEBRAIN_API_KEY env var
});

// Simple chat completion
const response = await client.chat.createSimple(
  'What are the elements of a valid contract?'
);
console.log(response);

// Legal research
const research = await client.research.quickResearch(
  'negligence tort law elements',
  { jurisdiction: 'california', maxResults: 5 }
);
console.log(research.summary);

API Documentation

Client Configuration

const client = new BriefcaseBrain({
  apiKey: 'rsk-your-key',                    // API key (required)
  baseUrl: 'https://briefcasebrain.ai',      // API base URL
  timeout: 60000,                            // Request timeout (ms)
  maxRetries: 3,                             // Max retry attempts
  rateLimitRequestsPerMinute: 60,            // Rate limit per minute
  rateLimitRequestsPerHour: 1000,            // Rate limit per hour
  headers: { 'X-Custom': 'header' }          // Additional headers
});

Chat API

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

Simple Chat

// Quick one-off question
const answer = await client.chat.createSimple(
  'Explain the statute of limitations for personal injury in Texas'
);

Full Chat Completion

const response = await client.chat.create({
  model: 'legal-research-v1',
  messages: [
    { role: 'system', content: 'You are a legal research assistant.' },
    { role: 'user', content: 'What is the difference between civil and criminal law?' }
  ],
  temperature: 0.7,
  max_tokens: 1000
});

console.log(response.choices[0].message.content);

Streaming Chat

const stream = await client.chat.create({
  model: 'legal-research-v1',
  messages: [{ role: 'user', content: 'Explain copyright law' }],
  stream: true
});

for await (const chunk of stream) {
  if (chunk.choices[0]?.delta?.content) {
    process.stdout.write(chunk.choices[0].delta.content);
  }
}

Conversation Management

const messages = [
  { role: 'user', content: 'What is a contract?' },
  { role: 'assistant', content: 'A contract is a legally binding agreement...' },
  { role: 'user', content: 'What makes a contract enforceable?' }
];

const response = await client.chat.createConversation(messages);

Legal Research API

Comprehensive legal research capabilities with case law, statutes, and analysis:

Quick Research

const research = await client.research.quickResearch(
  'employment discrimination laws',
  {
    jurisdiction: 'federal',
    qualityMode: 'high',
    maxResults: 10
  }
);

console.log(research.summary);
console.log(research.cases);
console.log(research.statutes);

Detailed Research

const research = await client.research.research({
  query: 'breach of contract remedies',
  jurisdiction: 'new york',
  practice_area: 'contract law',
  quality_mode: 'standard',
  max_cases: 5,
  max_statutes: 3,
  include_summary: true,
  context: 'Commercial real estate transaction dispute'
});

Case Search

const cases = await client.research.searchCases({
  query: 'reasonable accommodation disability',
  jurisdiction: 'california',
  max_results: 10,
  include_summary: true
});

for (const case_ of cases) {
  console.log(`${case_.citation}: ${case_.summary}`);
}

Statute Search

const statutes = await client.research.searchStatutes({
  query: 'consumer protection',
  jurisdiction: 'federal',
  max_results: 5
});

Legal Analysis

const analysis = await client.research.analyzeLegalQuestion({
  question: 'What are the requirements for establishing adverse possession?',
  context: 'Rural property in Texas, 20-year period',
  jurisdiction: 'texas',
  practice_area: 'real estate law'
});

Precedent Research

const precedents = await client.research.getLegalPrecedents({
  topic: 'first amendment free speech',
  jurisdiction: 'federal',
  max_results: 8
});

Models API

Manage and query available AI models:

// List all models
const models = await client.models.list();
console.log(models.data);

// Get available model IDs
const modelIds = await client.models.getAvailableModels();
console.log(modelIds); // ['legal-research-v1', ...]

// Check model availability
const isAvailable = await client.models.isModelAvailable('legal-research-v1');

// Get model info
const modelInfo = await client.models.getModelInfo('legal-research-v1');

// Get recommended models
const recommended = client.models.getRecommendedModels();
console.log(recommended.default); // 'legal-research-v1'

Advanced Usage

Error Handling

import {
  BriefcaseBrainError,
  AuthenticationError,
  RateLimitError
} from 'briefcasebrain-sdk';

try {
  const response = await client.chat.createSimple('What is tort law?');
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key:', error.message);
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded. Retry after:', error.retryAfter);
  } else if (error instanceof BriefcaseBrainError) {
    console.error('API error:', error.message, 'Status:', error.statusCode);
  } else {
    console.error('Unknown error:', error);
  }
}

Custom HTTP Configuration

const client = new BriefcaseBrain({
  apiKey: 'rsk-your-key',
  timeout: 30000,
  maxRetries: 5,
  headers: {
    'User-Agent': 'MyApp/1.0.0',
    'X-Client-Version': '2.0.0'
  }
});

Environment Variables

# Set your API key
export BRIEFCASEBRAIN_API_KEY="rsk-your-api-key"

# Alternative naming
export BRIEFCASE_BRAIN_API_KEY="rsk-your-api-key"

Quality Modes

Choose the appropriate quality mode for your use case:

  • fast - Quick responses with basic accuracy (~1-2 seconds)
  • standard - Balanced speed and quality (~3-5 seconds) [default]
  • high - Comprehensive research with highest accuracy (~8-15 seconds)
const research = await client.research.quickResearch(
  'corporate governance requirements',
  { qualityMode: 'high' }
);

TypeScript Support

The SDK is written in TypeScript and provides complete type definitions:

import type {
  ChatCompletionRequest,
  LegalResearchResponse,
  CaseResult
} from 'briefcasebrain-sdk';

// Full IntelliSense and type checking
const request: ChatCompletionRequest = {
  model: 'legal-research-v1',
  messages: [{ role: 'user', content: 'Legal question here' }],
  temperature: 0.7
};

const research: LegalResearchResponse = await client.research.quickResearch(
  'contract law question'
);

Browser Support

The SDK works in both Node.js and modern browsers:

// Browser usage
import { BriefcaseBrain } from 'briefcasebrain-sdk';

const client = new BriefcaseBrain({
  apiKey: 'rsk-your-key' // Don't expose API keys in client-side code
});

Security Note: Never expose your API key in client-side code. Use environment variables or secure proxy endpoints for browser applications.

Migration from v1.x

If you're upgrading from the previous version:

Changes in v2.0.0

  • Full TypeScript rewrite with complete type definitions
  • Streaming support for chat completions
  • Built-in rate limiting with token bucket algorithm
  • Improved error handling with specific error types
  • Modern async/await API throughout
  • Better validation for all inputs
  • Smaller bundle size with tree-shaking support

Breaking Changes

  • Constructor now takes a config object instead of positional parameters
  • All methods are now async and return Promises
  • Error classes have been reorganized
  • Some method names have changed for consistency

Migration Example

// v1.x
const client = new BriefcaseBrain('rsk-key', 'https://api.example.com');

// v2.x
const client = new BriefcaseBrain({
  apiKey: 'rsk-key',
  baseUrl: 'https://briefcasebrain.ai'
});

Examples

Check out the /examples directory for complete working examples:

Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Support

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

See CHANGELOG.md for a list of changes and version history.


BriefcaseBrain TypeScript SDK v2.0.0 - Built for the legal tech community