briefcasebrain-sdk
v2.0.2
Published
Official TypeScript SDK for BriefcaseBrain Legal AI Platform - Full-featured client with streaming support
Maintainers
Readme
BriefcaseBrain TypeScript SDK
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-sdkQuick 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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Support
- Email: [email protected]
- Documentation: https://briefcasebrain.ai/developers/docs
- Issues: GitHub Issues
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
