@velatir/sdk
v1.0.0
Published
Official TypeScript SDK for Velatir - Monitor and approve/reject AI function calls
Downloads
13
Maintainers
Readme
@velatir/sdk
Official TypeScript/JavaScript SDK for Velatir, a service that allows you to monitor and approve/reject AI function calls through review tasks.
Installation
npm install @velatir/sdkQuick Start
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("[email protected]", "Welcome!", "Hello from Velatir!");How It Works
The @reviewTask() (or @watch()) decorator intercepts function calls and:
- Creates a review task with function details and arguments via the Velatir API
- 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
- If
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
class UserService {
@velatir.reviewTask({ pollingInterval: 2, maxAttempts: 30 })
async deleteUser(userId: string): Promise<void> {
// Deletion logic here
}
}Adding Metadata
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:
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:
// 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:
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
// 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
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
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:
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 directory for complete working examples:
- basic_usage.ts - Simple email sending example
- logging_and_retries.ts - Advanced configuration with logging
- sync_client.ts - Using the client directly
- chatgpt_usage.ts - Integration with OpenAI ChatGPT
Running Examples
# Install dependencies
npm install
# Run examples
npm run build
node dist/examples/basic_usage.jsDevelopment
Building the SDK
npm install
npm run buildRunning Tests
npm test
npm run test:coverageLinting
npm run lint
npm run lint:fixNode.js Compatibility
This SDK requires Node.js 16.0.0 or higher.
Documentation
For detailed documentation, visit https://www.velatir.com/docs
License
This project is licensed under the MIT License - see the LICENSE file for details.
