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
Maintainers
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.
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 aiQuick 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=StandardAuto-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:
Default Export Removed: Use named imports instead
// v1 import legalResearch from '@briefcase/ai-sdk-legal'; // v2 import { legalResearch } from '@briefcase/ai-sdk-legal';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
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
- 📚 Documentation: https://docs.briefcasebrain.ai
- 🐛 Issues: GitHub Issues
- 💬 Support: [email protected]
- 🔑 API Access: https://briefcasebrain.ai/developers/api-access
License
MIT © Briefcase AI
Contributing
We welcome contributions! Please see our Contributing Guide for details.
Made with ⚖️ by Briefcase AI
