@lov3kaizen/agentsea-gateway 0.5.1

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 lovekaizen
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,298 @@
1
+ # @lov3kaizen/agentsea-gateway
2
+
3
+ High-performance TypeScript-native LLM gateway with unified API access, intelligent routing, caching, and cost optimization.
4
+
5
+ ## Features
6
+
7
+ - **Unified API**: OpenAI-compatible API for all providers (OpenAI, Anthropic, Google)
8
+ - **Intelligent Routing**: Round-robin, failover, cost-optimized, and latency-optimized strategies
9
+ - **Virtual Models**: Use `best`, `cheapest`, or `fastest` to auto-route to optimal providers
10
+ - **Caching**: Built-in LRU cache to reduce costs and latency
11
+ - **Streaming**: Full streaming support with SSE
12
+ - **Metrics**: Request tracking, cost calculation, and latency monitoring
13
+ - **Failover**: Automatic retry with circuit breaker protection
14
+ - **Type-Safe**: Full TypeScript support with comprehensive types
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pnpm add @lov3kaizen/agentsea-gateway
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ### As HTTP Proxy
25
+
26
+ ```typescript
27
+ import {
28
+ Gateway,
29
+ createHTTPServer,
30
+ startServer,
31
+ } from '@lov3kaizen/agentsea-gateway';
32
+
33
+ const gateway = new Gateway({
34
+ providers: [
35
+ {
36
+ name: 'openai',
37
+ apiKey: process.env.OPENAI_API_KEY,
38
+ models: ['gpt-4o', 'gpt-4o-mini'],
39
+ },
40
+ {
41
+ name: 'anthropic',
42
+ apiKey: process.env.ANTHROPIC_API_KEY,
43
+ models: ['claude-3-5-sonnet-20241022'],
44
+ },
45
+ ],
46
+ routing: {
47
+ strategy: 'cost-optimized',
48
+ },
49
+ });
50
+
51
+ const app = createHTTPServer({ gateway });
52
+ startServer(app, { port: 3000 });
53
+ ```
54
+
55
+ Then use it like the OpenAI API:
56
+
57
+ ```bash
58
+ curl http://localhost:3000/v1/chat/completions \
59
+ -H "Content-Type: application/json" \
60
+ -d '{
61
+ "model": "cheapest",
62
+ "messages": [{"role": "user", "content": "Hello!"}]
63
+ }'
64
+ ```
65
+
66
+ ### As SDK
67
+
68
+ ```typescript
69
+ import { Gateway } from '@lov3kaizen/agentsea-gateway';
70
+
71
+ const gateway = new Gateway({
72
+ providers: [
73
+ { name: 'openai', apiKey: process.env.OPENAI_API_KEY, models: ['gpt-4o'] },
74
+ ],
75
+ });
76
+
77
+ // OpenAI-compatible interface
78
+ const response = await gateway.chat.completions.create({
79
+ model: 'gpt-4o',
80
+ messages: [{ role: 'user', content: 'Hello!' }],
81
+ });
82
+
83
+ console.log(response.choices[0].message.content);
84
+ console.log(response._gateway); // Gateway metadata (provider, cost, latency)
85
+ ```
86
+
87
+ ## Virtual Models
88
+
89
+ Instead of specifying a model, use virtual models for automatic routing:
90
+
91
+ ```typescript
92
+ // Route to highest quality available model
93
+ await gateway.chat.completions.create({
94
+ model: 'best',
95
+ messages: [{ role: 'user', content: 'Complex reasoning task...' }],
96
+ });
97
+
98
+ // Route to cheapest model
99
+ await gateway.chat.completions.create({
100
+ model: 'cheapest',
101
+ messages: [{ role: 'user', content: 'Simple task...' }],
102
+ });
103
+
104
+ // Route to fastest provider
105
+ await gateway.chat.completions.create({
106
+ model: 'fastest',
107
+ messages: [{ role: 'user', content: 'Time-sensitive task...' }],
108
+ });
109
+ ```
110
+
111
+ ## Routing Strategies
112
+
113
+ ### Round-Robin
114
+
115
+ Distributes requests evenly across providers:
116
+
117
+ ```typescript
118
+ const gateway = new Gateway({
119
+ providers: [...],
120
+ routing: {
121
+ strategy: 'round-robin',
122
+ weights: { openai: 2, anthropic: 1 }, // 2:1 ratio
123
+ },
124
+ });
125
+ ```
126
+
127
+ ### Failover
128
+
129
+ Tries providers in order until one succeeds:
130
+
131
+ ```typescript
132
+ const gateway = new Gateway({
133
+ providers: [...],
134
+ routing: {
135
+ strategy: 'failover',
136
+ fallbackChain: ['openai', 'anthropic', 'google'],
137
+ },
138
+ });
139
+ ```
140
+
141
+ ### Cost-Optimized
142
+
143
+ Selects the cheapest model meeting quality requirements:
144
+
145
+ ```typescript
146
+ import { CostOptimizedStrategy } from '@lov3kaizen/agentsea-gateway';
147
+
148
+ const gateway = new Gateway({
149
+ providers: [...],
150
+ routing: { strategy: 'cost-optimized' },
151
+ });
152
+ ```
153
+
154
+ ### Latency-Optimized
155
+
156
+ Routes to the fastest provider based on observed latencies:
157
+
158
+ ```typescript
159
+ const gateway = new Gateway({
160
+ providers: [...],
161
+ routing: { strategy: 'latency-optimized' },
162
+ });
163
+ ```
164
+
165
+ ## Caching
166
+
167
+ Enable caching to reduce costs and latency for repeated requests:
168
+
169
+ ```typescript
170
+ const gateway = new Gateway({
171
+ providers: [...],
172
+ cache: {
173
+ enabled: true,
174
+ ttl: 3600, // 1 hour
175
+ maxEntries: 1000,
176
+ type: 'exact', // Hash-based matching
177
+ },
178
+ });
179
+ ```
180
+
181
+ ## Request Metadata
182
+
183
+ Add gateway-specific options to requests:
184
+
185
+ ```typescript
186
+ const response = await gateway.chat.completions.create({
187
+ model: 'gpt-4o',
188
+ messages: [...],
189
+ _gateway: {
190
+ preferredProvider: 'anthropic',
191
+ excludeProviders: ['google'],
192
+ maxCost: 0.01, // Max $0.01 per request
193
+ maxLatency: 5000, // Max 5 seconds
194
+ cachePolicy: 'no-cache', // Skip cache
195
+ tags: { user: 'user-123' },
196
+ },
197
+ });
198
+ ```
199
+
200
+ ## Response Metadata
201
+
202
+ Every response includes gateway metadata:
203
+
204
+ ```typescript
205
+ const response = await gateway.chat.completions.create({ ... });
206
+
207
+ console.log(response._gateway);
208
+ // {
209
+ // provider: 'openai',
210
+ // originalModel: 'cheapest',
211
+ // latencyMs: 1234,
212
+ // cost: 0.000123,
213
+ // cached: false,
214
+ // retries: 0,
215
+ // routingDecision: { ... }
216
+ // }
217
+ ```
218
+
219
+ ## Streaming
220
+
221
+ Full streaming support:
222
+
223
+ ```typescript
224
+ const stream = await gateway.chat.completions.create({
225
+ model: 'gpt-4o',
226
+ messages: [{ role: 'user', content: 'Tell me a story' }],
227
+ stream: true,
228
+ });
229
+
230
+ for await (const chunk of stream) {
231
+ process.stdout.write(chunk.choices[0]?.delta?.content || '');
232
+ }
233
+ ```
234
+
235
+ ## Metrics
236
+
237
+ Track usage and costs:
238
+
239
+ ```typescript
240
+ const metrics = gateway.getMetrics();
241
+
242
+ console.log(metrics.requests.total);
243
+ console.log(metrics.cost.total);
244
+ console.log(metrics.cost.byProvider);
245
+ console.log(metrics.latency.avg);
246
+ console.log(metrics.cache.hitRate);
247
+ ```
248
+
249
+ ## Events
250
+
251
+ Listen to gateway events:
252
+
253
+ ```typescript
254
+ gateway.on('request:complete', (event) => {
255
+ console.log(`${event.provider}: ${event.latencyMs}ms, $${event.cost}`);
256
+ });
257
+
258
+ gateway.on('request:error', (event) => {
259
+ console.error(`Error: ${event.error.message}`);
260
+ });
261
+
262
+ gateway.on('provider:unhealthy', (provider) => {
263
+ console.warn(`Provider ${provider} is unhealthy`);
264
+ });
265
+ ```
266
+
267
+ ## API Reference
268
+
269
+ ### Gateway
270
+
271
+ Main gateway class:
272
+
273
+ - `constructor(config: GatewayConfig)`
274
+ - `chat.completions.create(request)` - Create completion
275
+ - `getMetrics()` - Get usage metrics
276
+ - `getRegistry()` - Get provider registry
277
+ - `getRouter()` - Get router instance
278
+ - `checkHealth()` - Check provider health
279
+ - `shutdown()` - Clean shutdown
280
+
281
+ ### Providers
282
+
283
+ Built-in providers:
284
+
285
+ - `OpenAIProvider` - OpenAI/Azure OpenAI
286
+ - `AnthropicProvider` - Anthropic Claude
287
+ - `GoogleProvider` - Google Gemini
288
+
289
+ ### Routing Strategies
290
+
291
+ - `RoundRobinStrategy` - Even distribution
292
+ - `FailoverStrategy` - Ordered fallback
293
+ - `CostOptimizedStrategy` - Cheapest model
294
+ - `LatencyOptimizedStrategy` - Fastest provider
295
+
296
+ ## License
297
+
298
+ MIT