JavaScript/TypeScript SDK

Official JavaScript/TypeScript SDK for TalonAI with full type support, React hooks, and Express middleware.

Installation

npm install @talonai/sdk

Quick Start

index.ts
1import TalonAI from '@talonai/sdk';
2
3const talon = new TalonAI('sk_live_your_api_key');
4
5// Analyze content
6const result = await talon.analyze('Hello, how are you?');
7console.log(result.allowed); // true
8console.log(result.riskScore); // 0

Client Options

config.ts
1const talon = new TalonAI('sk_live_...', {
2 // Base URL (default: https://api.talonai.io)
3 baseUrl: 'https://api.talonai.io',
4
5 // Request timeout in milliseconds (default: 30000)
6 timeout: 30000,
7
8 // Default risk threshold (0-100, default: 70)
9 riskThreshold: 70,
10
11 // Retry configuration
12 maxRetries: 3,
13 retryDelay: 1000,
14
15 // Custom fetch implementation
16 fetch: customFetch,
17});

API Methods

analyze()

Analyze content for security threats. Returns detailed analysis including risk score and detected threats.

analyze.ts
1const result = await talon.analyze(content, {
2 // Optional: Custom categories to check
3 categories: ['PROMPT_INJECTION', 'PII_EXPOSURE'],
4
5 // Optional: Enable detailed explanations
6 detailed: true,
7
8 // Optional: Custom risk threshold for this request
9 riskThreshold: 80,
10
11 // Optional: Additional context
12 context: {
13 userId: 'user123',
14 sessionId: 'session456',
15 },
16});
17
18// Result structure
19interface AnalyzeResult {
20 allowed: boolean; // Whether content is allowed
21 riskScore: number; // 0-100 risk score
22 action: 'ALLOW' | 'BLOCK' | 'FLAG' | 'MODIFY';
23 threats: Threat[]; // Detected threats
24 processingTimeMs: number;
25}

protect()

Analyze and sanitize content. Returns sanitized content with PII and sensitive data redacted.

protect.ts
1const result = await talon.protect('My email is john@example.com');
2
3console.log(result.sanitizedContent);
4// "My email is [EMAIL_REDACTED]"
5
6console.log(result.allowed); // true (after sanitization)
7console.log(result.analysis.threats);
8// [{ category: 'PII_EXPOSURE', severity: 'MEDIUM', ... }]

isAllowed()

Quick check if content is allowed. Returns a boolean.

is-allowed.ts
1const allowed = await talon.isAllowed(userInput);
2
3if (!allowed) {
4 return res.status(403).json({ error: 'Content not allowed' });
5}

getRiskScore()

Get the risk score for content (0-100).

risk-score.ts
1const score = await talon.getRiskScore(content);
2
3if (score > 70) {
4 flagForReview(content);
5}

Express Middleware

Automatically protect all incoming requests with the Express middleware:

server.ts
1import express from 'express';
2import { talonMiddleware } from '@talonai/sdk/express';
3
4const app = express();
5
6// Apply globally
7app.use(talonMiddleware({
8 apiKey: 'sk_live_...',
9 blockOnThreat: true,
10 riskThreshold: 70,
11 contentFields: ['prompt', 'message', 'content'],
12}));
13
14// Or apply to specific routes
15app.post('/chat', talonMiddleware({ apiKey: '...' }), (req, res) => {
16 // req.talonAnalysis contains the analysis result
17 console.log(req.talonAnalysis?.riskScore);
18});

Middleware Options

The middleware supports custom error handlers, content field extraction, and fail-open/fail-closed modes.

React Hooks

Use TalonAI in React applications with hooks:

ChatInput.tsx
1import { TalonProvider, useTalon } from '@talonai/sdk/react';
2
3// Wrap your app
4function App() {
5 return (
6 <TalonProvider apiKey="sk_live_...">
7 <ChatInput />
8 </TalonProvider>
9 );
10}
11
12// Use in components
13function ChatInput() {
14 const { analyze, isLoading, error } = useTalon();
15 const [message, setMessage] = useState('');
16
17 const handleSubmit = async () => {
18 const result = await analyze(message);
19
20 if (!result.allowed) {
21 alert('Message blocked: ' + result.threats[0]?.description);
22 return;
23 }
24
25 // Safe to send
26 sendMessage(message);
27 };
28
29 return (
30 <div>
31 <input
32 value={message}
33 onChange={(e) => setMessage(e.target.value)}
34 disabled={isLoading}
35 />
36 <button onClick={handleSubmit} disabled={isLoading}>
37 {isLoading ? 'Checking...' : 'Send'}
38 </button>
39 {error && <p className="error">{error.message}</p>}
40 </div>
41 );
42}

Error Handling

errors.ts
1import TalonAI, {
2 TalonAIError,
3 AuthenticationError,
4 RateLimitError,
5 ValidationError,
6} from '@talonai/sdk';
7
8try {
9 const result = await talon.analyze(content);
10} catch (error) {
11 if (error instanceof AuthenticationError) {
12 // Invalid API key
13 console.error('Check your API key');
14 } else if (error instanceof RateLimitError) {
15 // Rate limited - wait and retry
16 console.log(`Retry after ${error.retryAfter}s`);
17 await sleep(error.retryAfter * 1000);
18 } else if (error instanceof ValidationError) {
19 // Invalid request
20 console.error('Invalid request:', error.message);
21 } else if (error instanceof TalonAIError) {
22 // Other API error
23 console.error(`API error [${error.code}]: ${error.message}`);
24 }
25}

TypeScript Support

Full TypeScript support with exported types:

types.ts
1import type {
2 AnalyzeResult,
3 ProtectResult,
4 Threat,
5 ThreatCategory,
6 ThreatSeverity,
7 TalonOptions,
8 AnalyzeOptions,
9} from '@talonai/sdk';
10
11// All types are exported and documented
12const handleResult = (result: AnalyzeResult) => {
13 result.threats.forEach((threat: Threat) => {
14 console.log(threat.category, threat.severity, threat.confidence);
15 });
16};

Next Steps