-
Notifications
You must be signed in to change notification settings - Fork 742
Expand file tree
/
Copy pathbrowser-usage.ts
More file actions
520 lines (436 loc) · 16.7 KB
/
Copy pathbrowser-usage.ts
File metadata and controls
520 lines (436 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/**
* Browser Usage Example
*
* Demonstrates using cascadeflow in browser environments:
* - Client-side integration
* - Webpack/Vite bundling setup
* - Environment variable handling
* - CORS considerations
* - Browser-specific patterns
*
* This is a Node.js example that shows the patterns - for actual browser usage,
* bundle this with webpack/vite and load in HTML.
*
* Usage: npx tsx examples/nodejs/browser-usage.ts
*/
import { CascadeAgent } from '@cascadeflow/core';
/**
* Browser-Compatible Configuration
*
* In a real browser app, you would:
* 1. Bundle with Webpack/Vite
* 2. Use environment variables via import.meta.env or process.env
* 3. Handle API keys securely (never expose in client code!)
*/
console.log('\n╔═══════════════════════════════════════════════════════════════╗');
console.log('║ cascadeflow - Browser Integration Guide ║');
console.log('╚═══════════════════════════════════════════════════════════════╝\n');
console.log('📦 Browser Integration Patterns\n');
// ============================================================================
// Pattern 1: Basic Browser Setup
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('Pattern 1: Basic Browser Setup');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('1. Install cascadeflow:');
console.log(' npm install @cascadeflow/core\n');
console.log('2. Create your browser app:');
console.log(`
// src/app.ts
import { CascadeAgent } from '@cascadeflow/core';
// Initialize agent (API key from environment or backend)
const agent = new CascadeAgent({
models: [
{
name: 'gpt-4o-mini',
provider: 'openai',
cost: 0.00015,
apiKey: import.meta.env.VITE_OPENAI_API_KEY, // Vite
// OR: process.env.REACT_APP_OPENAI_API_KEY // Create React App
},
{
name: 'gpt-4o',
provider: 'openai',
cost: 0.00625,
},
],
});
// Use the agent
async function handleQuery(userInput: string) {
const result = await agent.run(userInput);
console.log(result.content);
}
`);
console.log('⚠️ Security Warning:');
console.log(' • Never expose API keys in client-side code');
console.log(' • Use backend proxy for production');
console.log(' • Environment variables can still be exposed\n');
// ============================================================================
// Pattern 2: Webpack Configuration
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('Pattern 2: Webpack Configuration');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('webpack.config.js:');
console.log(`
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
fallback: {
// cascadeflow may need these polyfills
"buffer": require.resolve("buffer/"),
"stream": require.resolve("stream-browserify"),
"util": require.resolve("util/"),
},
},
plugins: [
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
}),
new webpack.DefinePlugin({
'process.env.OPENAI_API_KEY': JSON.stringify(process.env.OPENAI_API_KEY),
}),
],
};
`);
console.log('Install dependencies:');
console.log(' npm install --save-dev webpack ts-loader buffer stream-browserify util\n');
// ============================================================================
// Pattern 3: Vite Configuration
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('Pattern 3: Vite Configuration (Recommended)');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('vite.config.ts:');
console.log(`
import { defineConfig } from 'vite';
export default defineConfig({
build: {
target: 'esnext',
},
define: {
// Make env vars available
'import.meta.env.VITE_OPENAI_API_KEY': JSON.stringify(
process.env.VITE_OPENAI_API_KEY
),
},
optimizeDeps: {
include: ['@cascadeflow/core'],
},
});
`);
console.log('.env file:');
console.log(`
VITE_OPENAI_API_KEY=your_api_key_here
`);
console.log('Usage in app:');
console.log(`
import { CascadeAgent } from '@cascadeflow/core';
const agent = new CascadeAgent({
models: [{
name: 'gpt-4o-mini',
provider: 'openai',
cost: 0.00015,
apiKey: import.meta.env.VITE_OPENAI_API_KEY,
}],
});
`);
console.log('\n');
// ============================================================================
// Pattern 4: React Integration
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('Pattern 4: React Integration');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('Custom Hook Pattern:');
console.log(`
// hooks/useCascadeflow.ts
import { useState, useCallback } from 'react';
import { CascadeAgent } from '@cascadeflow/core';
// Initialize agent outside component (singleton)
const agent = new CascadeAgent({
models: [
{ name: 'gpt-4o-mini', provider: 'openai', cost: 0.00015 },
{ name: 'gpt-4o', provider: 'openai', cost: 0.00625 },
],
});
export function useCascadeflow() {
const [loading, setLoading] = useState(false);
const [response, setResponse] = useState<string>('');
const [cost, setCost] = useState<number>(0);
const [error, setError] = useState<string | null>(null);
const query = useCallback(async (text: string) => {
setLoading(true);
setError(null);
try {
const result = await agent.run(text, { maxTokens: 200 });
setResponse(result.content);
setCost(result.totalCost);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
}, []);
return { query, loading, response, cost, error };
}
`);
console.log('Component Usage:');
console.log(`
// components/ChatBox.tsx
import React, ` + `{ useState }` + ` from 'react';
import ` + `{ useCascadeflow }` + ` from '../hooks/useCascadeflow';
export function ChatBox() {
const [input, setInput] = useState('');
const ` + `{ query, loading, response, cost, error }` + ` = useCascadeflow();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (input.trim()) {
query(input);
}
};
return (
<div className="chat-box">
<form onSubmit=` + `{handleSubmit}` + `>
<input
value=` + `{input}` + `
onChange=` + `{(e) => setInput(e.target.value)}` + `
placeholder="Ask anything..."
disabled=` + `{loading}` + `
/>
<button type="submit" disabled=` + `{loading}` + `>
` + `{loading ? 'Thinking...' : 'Send'}` + `
</button>
</form>
` + `{error && <div className="error">{error}</div>}` + `
` + `{response && (
<div className="response">
<p>{response}</p>
<small>Cost: $` + `{cost.toFixed(6)}` + `</small>
</div>
)}` + `
</div>
);
}
`);
console.log('\n');
// ============================================================================
// Pattern 5: Vue Integration
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('Pattern 5: Vue Integration');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('Composable Pattern:');
console.log(`
// composables/useCascadeflow.ts
import { ref } from 'vue';
import { CascadeAgent } from '@cascadeflow/core';
const agent = new CascadeAgent({
models: [
{ name: 'gpt-4o-mini', provider: 'openai', cost: 0.00015 },
],
});
export function useCascadeflow() {
const loading = ref(false);
const response = ref('');
const cost = ref(0);
const error = ref<string | null>(null);
const query = async (text: string) => {
loading.value = true;
error.value = null;
try {
const result = await agent.run(text);
response.value = result.content;
cost.value = result.totalCost;
} catch (err) {
error.value = err instanceof Error ? err.message : 'Unknown error';
} finally {
loading.value = false;
}
};
return { query, loading, response, cost, error };
}
`);
console.log('Component Usage:');
console.log(`
<!-- ChatBox.vue -->
<template>
<div class="chat-box">
<form @submit.prevent="handleSubmit">
<input
v-model="input"
placeholder="Ask anything..."
:disabled="loading"
/>
<button type="submit" :disabled="loading">
` + `{{ loading ? 'Thinking...' : 'Send' }}` + `
</button>
</form>
<div v-if="error" class="error">` + `{{ error }}` + `</div>
<div v-if="response" class="response">
<p>` + `{{ response }}` + `</p>
<small>Cost: $` + `{{ cost.toFixed(6) }}` + `</small>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useCascadeflow } from '../composables/useCascadeflow';
const input = ref('');
const ` + `{ query, loading, response, cost, error }` + ` = useCascadeflow();
const handleSubmit = () => {
if (input.value.trim()) {
query(input.value);
input.value = '';
}
};
</script>
`);
console.log('\n');
// ============================================================================
// Pattern 6: Production Backend Proxy
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('Pattern 6: Production Backend Proxy (Recommended)');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('⚠️ For production, use a backend proxy to protect API keys!\n');
console.log('Backend (Express):');
console.log(`
// server.ts
import express from 'express';
import { CascadeAgent } from '@cascadeflow/core';
const app = express();
app.use(express.json());
// Initialize agent on server (API key stays secure)
const agent = new CascadeAgent({
models: [
{
name: 'gpt-4o-mini',
provider: 'openai',
cost: 0.00015,
apiKey: process.env.OPENAI_API_KEY, // Secure server-side
},
],
});
app.post('/api/query', async (req, res) => {
try {
const { query } = req.body;
const result = await agent.run(query);
res.json({
content: result.content,
cost: result.totalCost,
model: result.modelUsed,
});
} catch (error) {
res.status(500).json({ error: 'Query failed' });
}
});
app.listen(3000);
`);
console.log('Frontend (Fetch API):');
console.log(`
// client.ts
async function queryCascadeflow(text: string) {
const response = await fetch('/api/query', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: text }),
});
if (!response.ok) throw new Error('Query failed');
const data = await response.json();
return data;
}
// Usage
const result = await queryCascadeflow('What is TypeScript?');
console.log(result.content);
`);
console.log('\n');
// ============================================================================
// Pattern 7: Streaming in Browser
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('Pattern 7: Streaming in Browser');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('Client-side streaming works with async iterators:');
console.log(`
import { CascadeAgent, StreamEventType } from '@cascadeflow/core';
const agent = new CascadeAgent({
models: [{ name: 'gpt-4o-mini', provider: 'openai', cost: 0.00015 }],
});
async function streamQuery(text: string, onChunk: (chunk: string) => void) {
for await (const event of agent.stream(text)) {
if (event.type === StreamEventType.CHUNK) {
onChunk(event.content);
}
}
}
// React usage
function StreamingChat() {
const [response, setResponse] = useState('');
const handleQuery = async (text: string) => {
setResponse('');
await streamQuery(text, (chunk) => {
setResponse(prev => prev + chunk);
});
};
return <div>{response}</div>;
}
`);
console.log('\n');
// ============================================================================
// Summary
// ============================================================================
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('📋 Browser Integration Summary');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('✅ Supported Bundlers:');
console.log(' • Webpack (with polyfills)');
console.log(' • Vite (recommended)');
console.log(' • Rollup');
console.log(' • esbuild');
console.log('');
console.log('✅ Supported Frameworks:');
console.log(' • React');
console.log(' • Vue');
console.log(' • Svelte');
console.log(' • Angular');
console.log(' • Vanilla JS/TS');
console.log('');
console.log('🔒 Security Best Practices:');
console.log(' 1. Never expose API keys in client code');
console.log(' 2. Use backend proxy for production');
console.log(' 3. Implement rate limiting');
console.log(' 4. Validate user input');
console.log(' 5. Use environment variables properly');
console.log('');
console.log('⚡ Performance Tips:');
console.log(' • Initialize agent once (singleton pattern)');
console.log(' • Use streaming for better UX');
console.log(' • Implement loading states');
console.log(' • Cache responses when appropriate');
console.log(' • Monitor costs in production');
console.log('');
console.log('📚 Next Steps:');
console.log(' • See express-integration.ts for backend setup');
console.log(' • See streaming-text.ts for streaming patterns');
console.log(' • Check framework docs for specific integration');
console.log('');
console.log('✨ Done! You now know how to use cascadeflow in browsers.');
console.log(' This was a guide - adapt patterns to your stack.\n');