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-ai-sdk-legal

v2.0.1

Published

Legal research provider for Vercel AI SDK - enables AI-powered legal research with case law, statutes, and cross-jurisdictional analysis

Readme

@briefcase/ai-sdk-legal

Legal research provider for Vercel AI SDK - enables AI-powered legal research with case law, statutes, and cross-jurisdictional analysis.

npm version TypeScript License: MIT AI SDK V2

Version 2.0.0 - Now fully implements the AI SDK V2 protocol with enhanced streaming, error handling, and provider-specific options support.

Overview

This package provides a seamless integration between the Briefcase Legal Research API and the Vercel AI SDK, enabling developers to add AI-powered legal research capabilities to their applications with just a few lines of code.

Features

  • 🔍 Legal Case Research - Search and analyze case law across jurisdictions
  • 📜 Statute & Regulation Lookup - Find relevant statutes, codes, and regulations
  • 📄 Contract Analysis - Analyze contracts for risks and compliance issues
  • ⚖️ Jurisdiction Comparison - Compare legal frameworks across different jurisdictions
  • Citation Validation - Validate and format legal citations
  • 🌐 Multi-Jurisdiction Support - US Federal/State, UK, Canada, Australia, EU
  • 🚀 Streaming Support - Real-time streaming responses
  • 🛠️ AI Tools Integration - Built-in tools for function calling
  • 📊 Usage Tracking - Monitor API usage and rate limits

Installation

npm install @briefcase/ai-sdk-legal ai

Quick Start

1. Get Your API Key

Visit https://briefcasebrain.ai/developers/api-access to request an API key.

2. Basic Usage

import { legalResearch } from '@briefcase/ai-sdk-legal';
import { generateText } from 'ai';

const legal = legalResearch({
  apiKey: process.env.LEGAL_API_KEY
});

const { text } = await generateText({
  model: legal('legal-research-standard'),
  prompt: 'What are the key precedents for employment discrimination in New York?'
});

console.log(text);

3. Using Legal Research Tools

import { legalResearch } from '@briefcase/ai-sdk-legal';
import { generateText } from 'ai';

const legal = legalResearch({
  apiKey: process.env.LEGAL_API_KEY
});

const { text, toolCalls } = await generateText({
  model: legal('legal-research-standard'),
  prompt: 'Find relevant cases about employment discrimination and analyze the contract clauses',
  tools: {
    searchCases: legal.tools.searchCases,
    analyzeContract: legal.tools.analyzeContract,
    compareJurisdictions: legal.tools.compareJurisdictions
  }
});

// Access tool results
toolCalls.forEach(call => {
  console.log(`Tool: ${call.toolName}`);
  console.log(`Result:`, call.result);
});

Configuration

Provider Settings

import { legalResearch } from '@briefcase/ai-sdk-legal';

const legal = legalResearch({
  apiKey: 'your-api-key',                    // Required
  baseURL: 'https://briefcasebrain.ai/api/v1', // Optional, defaults to official API
  organizationId: 'your-org-id',             // Optional, for multi-tenant setups
  rateLimitTier: 'Standard',                 // Optional, inferred from API key
  timeout: 30000,                            // Optional, request timeout in ms
  headers: {                                 // Optional, custom headers
    'Custom-Header': 'value'
  }
});

Environment Variables

# Primary API key (required)
LEGAL_API_KEY=your-api-key

# Alternative API key name
BRIEFCASE_API_KEY=your-api-key

# Optional configuration
LEGAL_API_BASE_URL=https://briefcasebrain.ai/api/v1
LEGAL_ORGANIZATION_ID=your-org-id
LEGAL_RATE_LIMIT_TIER=Standard

Auto-configuration from Environment

import { createLegalProviderFromEnv } from '@briefcase/ai-sdk-legal';

// Automatically uses environment variables
const legal = createLegalProviderFromEnv();

Models

| Model ID | Tier Required | Description | Rate Limits | |----------|---------------|-------------|-------------| | legal-research-basic | Basic | Entry-level legal research | 20/min, 500/hour | | legal-research-standard | Standard | Advanced legal research with contract analysis | 60/min, 1000/hour | | legal-research-premium | Premium | Professional-grade with full jurisdiction coverage | 120/min, 2000/hour | | legal-research-enterprise | Premium | Enterprise-grade with unlimited access | 500/min, 10000/hour |

Model Selection

// Use specific model
const { text } = await generateText({
  model: legal('legal-research-premium'),
  prompt: 'Your legal query'
});

// Get recommended model for your tier
const recommendedModel = await legal.getRecommendedModel();
const { text } = await generateText({
  model: legal(recommendedModel),
  prompt: 'Your legal query'
});

Available Tools

Case Search

Search for legal cases by query, jurisdiction, court, or date range.

const result = await legal.tools.searchCases.execute({
  query: 'employment discrimination',
  jurisdiction: 'US-NY',
  court: 'Supreme Court',
  dateRange: {
    start: '2020-01-01',
    end: '2024-01-01'
  },
  limit: 10
});

Statute Search

Find statutes, regulations, and codes.

const result = await legal.tools.searchStatutes.execute({
  query: 'data privacy',
  jurisdiction: 'US-CA',
  title: 'Civil Code',
  limit: 5
});

Contract Analysis

Analyze contracts for risks and compliance.

const result = await legal.tools.analyzeContract.execute({
  contractText: 'Your contract text here...',
  analysisType: 'risk',
  jurisdiction: 'US-NY',
  contractType: 'employment'
});

Jurisdiction Comparison

Compare legal frameworks across jurisdictions.

const result = await legal.tools.compareJurisdictions.execute({
  topic: 'employment law',
  jurisdictions: ['US-NY', 'US-CA', 'UK'],
  aspectsToCompare: ['overtime rules', 'termination procedures']
});

Citation Validation

Validate and format legal citations.

const result = await legal.tools.validateCitations.execute({
  citations: [
    'Brown v. Board of Education, 347 U.S. 483 (1954)',
    'Roe v. Wade, 410 US 113 (1973)'
  ],
  format: 'bluebook'
});

Streaming

Support for real-time streaming responses:

import { streamText } from 'ai';

const { textStream } = await streamText({
  model: legal('legal-research-standard'),
  prompt: 'Explain the evolution of privacy law in the digital age'
});

for await (const chunk of textStream) {
  process.stdout.write(chunk);
}

Usage Monitoring

Track your API usage and rate limits:

// Get current usage
const usage = await legal.usage();
console.log(`Requests this month: ${usage.requestsThisMonth}`);
console.log(`Requests remaining: ${usage.requestsRemaining}`);

// Check health
const isHealthy = await legal.healthCheck();
console.log(`API Status: ${isHealthy ? 'OK' : 'Error'}`);

// Get available models for your tier
const availableModels = await legal.getAvailableModels();
console.log('Available models:', availableModels);

Migration from v1 to v2

Breaking Changes

Version 2.0.0 introduces the following breaking changes:

  1. Default Export Removed: Use named imports instead

    // v1
    import legalResearch from '@briefcase/ai-sdk-legal';
    
    // v2
    import { legalResearch } from '@briefcase/ai-sdk-legal';
  2. AI SDK V2 Protocol: Now implements LanguageModelV2 specification

    • Enhanced streaming with more event types
    • Better error handling with typed errors
    • Support for provider-specific options
  3. Improved TypeScript Types: Stricter type checking for better development experience

New Features in v2

  • Provider-Specific Options: Pass custom options to messages and tools
  • Enhanced Streaming: Support for reasoning, sources, and file events
  • Better Error Types: Proper typed error responses
  • Transparent UI Metadata: Automatically included in all requests

Error Handling

The package includes comprehensive error handling:

import {
  LegalAPIError,
  RateLimitError,
  AuthenticationError
} from '@briefcase/ai-sdk-legal';

try {
  const { text } = await generateText({
    model: legal('legal-research-standard'),
    prompt: 'Your query'
  });
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log(`Rate limited. Reset time: ${error.resetTime}`);
  } else if (error instanceof AuthenticationError) {
    console.log('Invalid API key');
  } else if (error instanceof LegalAPIError) {
    console.log(`API Error: ${error.message} (${error.code})`);
  }
}

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import type {
  LegalModelId,
  CaseSearchResult,
  LegalProviderSettings
} from '@briefcase/ai-sdk-legal';

const settings: LegalProviderSettings = {
  apiKey: 'your-key',
  rateLimitTier: 'Standard'
};

const modelId: LegalModelId = 'legal-research-standard';

Supported Jurisdictions

  • United States: Federal, all 50 states (NY, CA, TX, FL, etc.)
  • United Kingdom: England, Scotland, Wales, Northern Ireland
  • Canada: Federal, all provinces (ON, BC, AB, QC, etc.)
  • Australia: Federal, all states (NSW, VIC, QLD, etc.)
  • European Union: EU-wide, major countries (DE, FR, IT, ES, NL, etc.)

Rate Limits

| Tier | Requests/Min | Requests/Hour | Requests/Day | |------|--------------|---------------|--------------| | Basic | 20 | 500 | 2,000 | | Standard | 60 | 1,000 | 5,000 | | Premium | 120 | 2,000 | 10,000 |

Examples

Legal Research Assistant

import { legalResearch } from '@briefcase/ai-sdk-legal';
import { generateText } from 'ai';

const legal = legalResearch({ apiKey: process.env.LEGAL_API_KEY });

async function researchAssistant(query: string) {
  const { text, toolCalls } = await generateText({
    model: legal('legal-research-standard'),
    prompt: `Research this legal question: ${query}`,
    tools: {
      searchCases: legal.tools.searchCases,
      searchStatutes: legal.tools.searchStatutes,
      compareJurisdictions: legal.tools.compareJurisdictions
    }
  });

  return { analysis: text, sources: toolCalls };
}

// Usage
const result = await researchAssistant(
  'What are the requirements for establishing a limited liability company in New York?'
);

Contract Review Assistant

async function reviewContract(contractText: string, jurisdiction: string) {
  const { text, toolCalls } = await generateText({
    model: legal('legal-research-premium'),
    prompt: `Review this contract and identify potential risks and compliance issues.`,
    tools: {
      analyzeContract: legal.tools.analyzeContract,
      searchStatutes: legal.tools.searchStatutes
    }
  });

  return { review: text, analysis: toolCalls };
}

Support

License

MIT © Briefcase AI

Contributing

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


Made with ⚖️ by Briefcase AI