@legionai/sdk
v0.2.2
Published
Connect browser and server applications to Legion accounts with OAuth 2.0, PKCE, and automatic token refresh.
Maintainers
Readme
Legion SDK 0.2
Connect your app to Legion accounts and let users pay for AI with their own funds.
Installation
npm install @legionai/sdkQuick Example
import { createLegion } from '@legionai/sdk';
const legion = createLegion({
clientId: 'your_client_id',
});
// Connect user's credits
legion.connect({ redirectUri: 'https://yourapp.com/callback' });
// After callback, exchange code for tokens
const tokens = await legion.exchangeCode(code, { state });
// Make API calls - costs come from user's credits
const response = await legion.chat([
{ role: 'user', content: 'Hello!' }
]);Documentation
- Quickstart - Get started in 5 minutes
- Authentication Guide - OAuth flow, tokens, and session management
- Error Handling - Handle errors gracefully
- API Reference - Complete API documentation
How It Works
- User authorizes your app to use their Legion account
- You get tokens to make API calls on their behalf
- AI costs are charged to the user's credits, not yours
- Users control spending limits and can deactivate anytime
Key Features
- Zero AI costs for developers - Users pay from their own accounts
- Simple OAuth flow - Standard authorization, familiar to users
- PKCE by default - Browser and CMS clients configure only the public client ID; the SDK sends
code_challengeduring authorization andcode_verifierduring token exchange - Auto token refresh - SDK handles token lifecycle automatically
- Graceful error handling - Structured errors with helper methods
- User control - Users set limits and can disconnect anytime
Error Handling
try {
await legion.chat(messages);
} catch (error) {
if (error.requiresReauth()) {
legion.connect(); // Re-authorize
} else if (error.isCapError()) {
legion.connect({ authorizationIntent: 'increase_cap' });
} else if (error.isPaymentMethodError()) {
legion.connect({ authorizationIntent: 'payment_method' });
} else if (error.isBillingError()) {
showMessage('Complete billing authorization in Legion');
}
}Support
- Documentation: Legion developer documentation
- Migration guide: Migrating to 0.2
- Support: Legion contact
License
MIT
