@altsafe/aidirector 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AI Director
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,203 @@
1
+ # @aidirector/client
2
+
3
+ Official TypeScript SDK for **AI Director** — the intelligent AI API gateway with automatic failover, response caching, and JSON extraction.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@aidirector/client.svg)](https://www.npmjs.com/package/@aidirector/client)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ ## Features
10
+
11
+ - 🔐 **HMAC Authentication** — Secure request signing (Node.js & browser)
12
+ - ⚡ **10-minute Timeout** — Handles long-running AI requests
13
+ - 🔄 **Automatic Retries** — Exponential backoff with configurable limits
14
+ - 📦 **Structured Errors** — Type-safe error handling
15
+ - 🌊 **Streaming Support** — Real-time response streaming
16
+ - 🎯 **Full TypeScript** — Complete type definitions
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @aidirector/client
22
+ # or
23
+ bun add @aidirector/client
24
+ # or
25
+ pnpm add @aidirector/client
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ```typescript
31
+ import { AIDirector } from '@aidirector/client';
32
+
33
+ const client = new AIDirector({
34
+ secretKey: process.env.AIDIRECTOR_SECRET_KEY!,
35
+ baseUrl: 'https://api.aidirector.dev', // Optional
36
+ });
37
+
38
+ const result = await client.generate({
39
+ chainId: 'your-chain-id',
40
+ prompt: 'Generate 5 user profiles with name and email',
41
+ schema: { name: 'string', email: 'string' },
42
+ });
43
+
44
+ if (result.success) {
45
+ console.log('Users:', result.data.valid);
46
+ console.log('Model:', result.meta.modelUsed);
47
+ console.log('Cached:', result.meta.cached);
48
+ }
49
+ ```
50
+
51
+ ## Usage Examples
52
+
53
+ ### Next.js Server Actions
54
+
55
+ ```typescript
56
+ 'use server';
57
+
58
+ import { AIDirector } from '@aidirector/client';
59
+
60
+ const client = new AIDirector({
61
+ secretKey: process.env.AIDIRECTOR_SECRET_KEY!,
62
+ });
63
+
64
+ export async function generateContent(prompt: string) {
65
+ return client.generate({
66
+ chainId: process.env.DEFAULT_CHAIN_ID!,
67
+ prompt,
68
+ });
69
+ }
70
+ ```
71
+
72
+ ### API Routes
73
+
74
+ ```typescript
75
+ // app/api/generate/route.ts
76
+ import { NextResponse } from 'next/server';
77
+ import { AIDirector } from '@aidirector/client';
78
+
79
+ const client = new AIDirector({
80
+ secretKey: process.env.AIDIRECTOR_SECRET_KEY!,
81
+ });
82
+
83
+ export async function POST(request: Request) {
84
+ const { prompt, chainId } = await request.json();
85
+ const result = await client.generate({ chainId, prompt });
86
+ return NextResponse.json(result);
87
+ }
88
+ ```
89
+
90
+ ### Streaming
91
+
92
+ ```typescript
93
+ await client.generateStream(
94
+ {
95
+ chainId: 'my-chain',
96
+ prompt: 'Write a long story...',
97
+ },
98
+ {
99
+ onChunk: (chunk) => process.stdout.write(chunk),
100
+ onComplete: (result) => console.log('\nDone!', result.meta),
101
+ onError: (error) => console.error('Error:', error),
102
+ }
103
+ );
104
+ ```
105
+
106
+ ### Error Handling
107
+
108
+ ```typescript
109
+ import {
110
+ AIDirector,
111
+ TimeoutError,
112
+ RateLimitError,
113
+ isAIDirectorError
114
+ } from '@aidirector/client';
115
+
116
+ try {
117
+ const result = await client.generate({ chainId, prompt });
118
+ } catch (error) {
119
+ if (error instanceof TimeoutError) {
120
+ console.log('Request timed out after', error.timeoutMs, 'ms');
121
+ } else if (error instanceof RateLimitError) {
122
+ console.log('Rate limited, retry after', error.retryAfterMs, 'ms');
123
+ } else if (isAIDirectorError(error)) {
124
+ console.log('AI Director error:', error.code, error.message);
125
+ }
126
+ }
127
+ ```
128
+
129
+ ## API Reference
130
+
131
+ ### `new AIDirector(config)`
132
+
133
+ | Option | Type | Default | Description |
134
+ |--------|------|---------|-------------|
135
+ | `secretKey` | `string` | — | **Required.** Your API secret key |
136
+ | `baseUrl` | `string` | `localhost:3000` | API base URL |
137
+ | `timeout` | `number` | `600000` | Request timeout (ms) |
138
+ | `maxRetries` | `number` | `3` | Max retry attempts |
139
+ | `debug` | `boolean` | `false` | Enable console logging |
140
+
141
+ ### `client.generate(options)`
142
+
143
+ | Option | Type | Required | Description |
144
+ |--------|------|----------|-------------|
145
+ | `chainId` | `string` | Yes | Fallback chain ID |
146
+ | `prompt` | `string` | Yes | Prompt to send |
147
+ | `schema` | `object` | No | JSON schema for validation |
148
+ | `timeout` | `number` | No | Override timeout for this request |
149
+ | `options.temperature` | `number` | No | Randomness (0-2) |
150
+ | `options.maxTokens` | `number` | No | Max output tokens |
151
+
152
+ ### Other Methods
153
+
154
+ ```typescript
155
+ // List available models
156
+ const models = await client.listModels();
157
+
158
+ // Get your chains (requires auth)
159
+ const chains = await client.listChains();
160
+
161
+ // Usage statistics
162
+ const usage = await client.getUsage({
163
+ startDate: new Date('2024-01-01')
164
+ });
165
+
166
+ // Health check
167
+ const { ok, latencyMs } = await client.health();
168
+
169
+ // Create new client with different config
170
+ const debugClient = client.withConfig({ debug: true });
171
+ ```
172
+
173
+ ## Error Classes
174
+
175
+ | Error | Code | Retryable | Description |
176
+ |-------|------|-----------|-------------|
177
+ | `ConfigurationError` | `CONFIGURATION_ERROR` | No | Invalid client setup |
178
+ | `AuthenticationError` | `AUTH_ERROR` | No | Invalid credentials |
179
+ | `RateLimitError` | `RATE_LIMITED` | Yes | Too many requests |
180
+ | `TimeoutError` | `TIMEOUT` | Yes | Request timed out |
181
+ | `NetworkError` | `NETWORK_ERROR` | Yes | Connection failed |
182
+ | `ChainExecutionError` | `CHAIN_FAILED` | No | All models failed |
183
+ | `ServerError` | `SERVER_ERROR` | Yes | Internal server error |
184
+
185
+ ## Security
186
+
187
+ ⚠️ **Server-side only!** Never expose your secret key to browsers.
188
+
189
+ - ✅ Next.js API routes / Server Actions
190
+ - ✅ Express.js / Fastify
191
+ - ✅ Angular Universal (SSR)
192
+ - ✅ Edge Functions (Vercel, Cloudflare)
193
+ - ❌ Client-side JavaScript
194
+
195
+ Store your secret key in environment variables:
196
+
197
+ ```bash
198
+ AIDIRECTOR_SECRET_KEY=aid_sk_your_secret_key_here
199
+ ```
200
+
201
+ ## License
202
+
203
+ MIT © AI Director