@velatir/sdk
Version:
Official TypeScript SDK for Velatir - Monitor and approve/reject AI function calls
263 lines (198 loc) • 7.31 kB
Markdown
# @velatir/sdk
[](https://badge.fury.io/js/%40velatir%2Fsdk)
[](https://opensource.org/licenses/MIT)
Official TypeScript/JavaScript SDK for [Velatir](https://velatir.com), a service that allows you to monitor and approve/reject AI function calls through review tasks.
## Installation
```bash
npm install @velatir/sdk
```
## Quick Start
```typescript
import * as velatir from '@velatir/sdk';
// Initialize the SDK with your API key
velatir.init({ apiKey: "your-api-key" });
class EmailService {
// Decorate methods you want to monitor
@velatir.reviewTask() // or @velatir.watch() for backward compatibility
async sendEmail(to: string, subject: string, body: string): Promise<void> {
console.log(`Sending email to ${to}: ${subject}`);
// Your email sending logic here
}
}
// Call the method as usual (or from LLM tool)
const emailService = new EmailService();
await emailService.sendEmail("customer@example.com", "Welcome!", "Hello from Velatir!");
```
## How It Works
The `@reviewTask()` (or `@watch()`) decorator intercepts function calls and:
1. Creates a review task with function details and arguments via the Velatir API
2. Processes the API response:
- If `approved`: The function runs immediately
- If `pending`: The SDK polls the API every 5 seconds until approved or denied
- If `denied`: An exception is thrown and the function doesn't run
## Features
- Monitor function calls in real-time through review tasks
- Approve or reject function execution with optional feedback
- Automatically handle pending approval states
- Works with both synchronous and asynchronous functions
- Customizable polling intervals and timeout settings
- Full TypeScript support with type safety
- Review task chaining via parent task IDs
- LLM explanation support for better context
## Advanced Usage
### Custom Polling Configuration
```typescript
class UserService {
@velatir.reviewTask({ pollingInterval: 2, maxAttempts: 30 })
async deleteUser(userId: string): Promise<void> {
// Deletion logic here
}
}
```
### Adding Metadata
```typescript
class PaymentService {
@velatir.reviewTask({ metadata: { priority: "high", team: "billing" } })
async chargeCreditCard(cardId: string, amount: number): Promise<void> {
// Charging logic here
}
}
```
### Logging and Retries
The SDK supports configurable logging and automatic retries for network failures:
```typescript
import * as velatir from '@velatir/sdk';
// Configure with logging and retries
velatir.init({
apiKey: "your-api-key",
logLevel: velatir.LogLevel.INFO, // Or use int: 0=NONE, 1=ERROR, 2=INFO, 3=DEBUG
maxRetries: 3, // Number of retries for failed requests
retryBackoff: 0.5 // Base backoff time (exponential)
});
// Configure Velatir's logger specifically (optional)
velatir.configureLogging(velatir.LogLevel.INFO);
```
### Using the Client Directly
While the decorator works with both async and sync functions, you can also use the client methods directly:
```typescript
// Get the global client
const client = velatir.getClient();
// Create a review task
const response = await client.createReviewTask(
"charge_card",
{ cardId: "card_123", amount: 99.99 },
"Charge a customer's credit card",
"LLM is requesting to charge the customer",
{ priority: "high" }
);
// Wait for approval if pending
if (response.isPending) {
const approval = await client.waitForApproval(
response.reviewTaskId,
2000 // polling interval in milliseconds
);
}
```
## Error Handling
When a function is denied:
```typescript
try {
await riskyFunction();
} catch (error) {
// Both old and new error types are supported
if (error instanceof velatir.VelatirReviewTaskDeniedError) {
console.log(`Review task denied: ${error.message}`);
console.log(`Review Task ID: ${error.reviewTaskId}`);
console.log(`Requested Change: ${error.requestedChange}`);
} else if (error instanceof velatir.VelatirWatchDeniedError) {
// Legacy error type (still supported)
console.log(`Function denied: ${error.message}`);
console.log(`Request ID: ${error.requestId}`);
}
}
```
### Available Error Types
```typescript
// Base error class
velatir.VelatirError
// API-specific errors
velatir.VelatirAPIError // API returned an error
velatir.VelatirTimeoutError // Request timed out
velatir.VelatirReviewTaskDeniedError // Review task execution denied
velatir.VelatirWatchDeniedError // Legacy: function execution denied (extends VelatirReviewTaskDeniedError)
```
## Configuration Options
```typescript
interface ClientConfig {
apiKey?: string; // Your Velatir API key
baseUrl?: string; // Custom API base URL
timeout?: number; // Request timeout in milliseconds (default: 10000)
logLevel?: LogLevel; // Logging verbosity level
maxRetries?: number; // Maximum number of retries (default: 3)
retryBackoff?: number; // Base backoff time in seconds (default: 0.5)
}
```
## Decorator Options
```typescript
interface ReviewTaskOptions {
pollingInterval?: number; // Seconds between polling attempts (default: 5)
maxAttempts?: number; // Maximum number of polling attempts
metadata?: Record<string, unknown>; // Additional metadata to send
}
```
## TypeScript Support
The SDK is written in TypeScript and provides full type safety:
```typescript
import { VelatirResponse, LogLevel, ClientConfig, ReviewTaskOptions } from '@velatir/sdk';
// All types are exported for your use
const config: ClientConfig = {
apiKey: "your-key",
logLevel: LogLevel.DEBUG
};
// Response object contains review task information
const handleResponse = (response: VelatirResponse) => {
console.log(`Review Task ID: ${response.reviewTaskId}`);
console.log(`State: ${response.state}`);
console.log(`Requested Change: ${response.requestedChange}`);
};
```
## Examples
Check out the [examples](./examples/) directory for complete working examples:
- **[basic_usage.ts](./examples/basic_usage.ts)** - Simple email sending example
- **[logging_and_retries.ts](./examples/logging_and_retries.ts)** - Advanced configuration with logging
- **[sync_client.ts](./examples/sync_client.ts)** - Using the client directly
- **[chatgpt_usage.ts](./examples/chatgpt_usage.ts)** - Integration with OpenAI ChatGPT
### Running Examples
```bash
# Install dependencies
npm install
# Run examples
npm run build
node dist/examples/basic_usage.js
```
## Development
### Building the SDK
```bash
npm install
npm run build
```
### Running Tests
```bash
npm test
npm run test:coverage
```
### Linting
```bash
npm run lint
npm run lint:fix
```
## Node.js Compatibility
This SDK requires Node.js 16.0.0 or higher.
## Documentation
For detailed documentation, visit [https://www.velatir.com/docs](https://www.velatir.com/docs)
## License
This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.
## Support
- 🐛 [Report bugs](https://github.com/velatir/velatir-sdk/issues)
- 💬 [Get help](https://www.velatir.com/docs)
- 📧 [Contact support](mailto:hello@velatir.com)