@rws-framework/ai-tools 0.0.1 → 0.0.3

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/README.md CHANGED
@@ -1,862 +1,3 @@
1
- # Realtime Web Suit server setup and configuration guide
1
+ # Realtime Web Suit server AI tools
2
2
 
3
- Realtime Web Suit is a flexible fullstack-server for seting up web servers, WebSocket servers and more while keeping it in sync with your frontend.
4
-
5
-
6
- *(TBA: RWS Prisma models + RWS Custom CLI Engine + Nest + Nest-RWS front routing mapper)*
7
-
8
- ## Table of Contents
9
- 1. [Prerequisites](#prerequisites)
10
- 2. [Setting Up](#setting-up)
11
- - [Install Package](#install-package)
12
- - [Package File](#package-file)
13
- - [TS Config File](#tsconfig-file)
14
- - [Initialize Server Setup](#initialize-server-setup)
15
- - [Server Configuration](#server-configuration)
16
- 3. [Creating Server Configuration](#creating-server-configuration)
17
- - [Example Webpack Config](#example-webpack-config)
18
- - [RWS Webpack Config](#rws-webpack-config)
19
- - [RWS App Configuration](#rws-app-configuration)
20
- 4. [Commands](#commands)
21
- - [Sample Command](#sample-command)
22
- - [New Command](#new-command)
23
- - [Database Models](#database-models)
24
- 5. [Route Configuration](#route-configuration)
25
- - [Request Route Configuration](#request-route-configuration)
26
- - [Websocket Route Configuration](#websocket-route-configuration)
27
- 6. [Running the Server](#running-the-server)
28
- - [Server Initialization](#server-initialization)
29
- - [DB Service](#db-service)
30
- - [Implementation](#implementation)
31
- 7. [BASH Installs for Node Libraries](#bash-installs-for-node-libraries)
32
-
33
-
34
- ## Prerequisites
35
-
36
- Make sure you have Node.js and yarn installed on your local machine. If not, you can download it from the [official Node.js website](https://nodejs.org).
37
-
38
- ## Setting Up
39
-
40
- ### Install yarn
41
-
42
- ```bash
43
- npm install -g yarn
44
- ```
45
-
46
- ### Install package
47
-
48
- ```bash
49
- yarn add @rws-framework/server
50
- ```
51
-
52
- ### Package file
53
-
54
- **To use serve you need this packages in your package.json:**
55
-
56
- ```json
57
- {
58
- "dependencies": {,
59
- "@types/archiver": "^6.0.2",
60
- "@types/body-parser": "^1.19.5",
61
- "@types/express": "^4.17.21",
62
- "compression": "^1.7.4",
63
- "dotenv": "^16.3.1",
64
- "jsonwebtoken": "9.0.2",
65
- "nodemon": "^1.12.1",
66
- "npm-run-all": "^4.1.1",
67
- "puppeteer": "^21.0.3",
68
- "readable-stream": "^4.5.2",
69
- "reflect-metadata": "^0.2.1",
70
- "@rws-framework/server": "*",
71
- "ts-transformer-keys": "^0.4.4",
72
- "tsconfig-paths-webpack-plugin": "^4.1.0",
73
- "typescript": "^5.3.3",
74
- "webpack-node-externals": "^3.0.0"
75
- },
76
- "devDependencies": {
77
- "@types/chai": "^4.3.5",
78
- "@types/chai-like": "^1.1.1",
79
- "@types/chai-things": "^0.0.35",
80
- "@types/compression": "^1.7.5",
81
- "@types/jsonwebtoken": "9.0.2",
82
- "@types/lodash": "^4.14.202",
83
- "@types/mocha": "^10.0.1",
84
- "chai": "^4.3.7",
85
- "chai-like": "^1.1.1",
86
- "chai-things": "^0.2.0",
87
- "mocha": "^10.2.0",
88
- "ts-node": "^10.9.1",
89
- "webpack": "^5.75.0",
90
- "webpack-bundle-analyzer": "^4.10.1",
91
- "webpack-cli": "^5.1.4"
92
- }
93
- }
94
- ```
95
-
96
- ### Tsconfig file
97
-
98
- **tsconfig.json:**
99
-
100
- ```json
101
- {
102
- "compilerOptions": {
103
- "baseUrl": ".",
104
- "experimentalDecorators": true,
105
- "emitDecoratorMetadata": true,
106
- "target": "ES2018",
107
- "module": "commonjs",
108
- "moduleResolution": "node",
109
- "strict": true,
110
- "esModuleInterop": true,
111
- "sourceMap": true,
112
- "resolveJsonModule": true,
113
- "outDir": "dist",
114
- "strictNullChecks": false,
115
- "allowSyntheticDefaultImports": true,
116
- "paths": {
117
- }
118
- },
119
- "include": ["./src"],
120
- "exclude": []
121
- }
122
- ```
123
-
124
- ### Initialzie server setup (by default uses src/config/config.ts)
125
-
126
- ```bash
127
-
128
- yarn rws init
129
- ```
130
-
131
- ### OR with specifig config path
132
-
133
- ```bash
134
-
135
- yarn rws init path/to/cfg.ts/from/src
136
- ```
137
-
138
- ## Creating Server Configuration
139
-
140
- Create a new file named `config.ts` in the root of your project. This file will export a function that returns a configuration object.
141
-
142
- ### Example webpack config
143
-
144
- ```Js
145
- const path = require('path');
146
- const keysTransformer = require('ts-transformer-keys/transformer').default;
147
- const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
148
-
149
- const RWSWebPackSettings = require('@rws-framework/server/rws.webpack.config');
150
-
151
- RWSWebPackSettings.resolve.plugins = [
152
- new TsconfigPathsPlugin({configFile: './tsconfig.json'})
153
- ]
154
-
155
- RWSWebPackSettings.output.path = path.resolve(__dirname, 'build');
156
- RWSWebPackSettings.output.filename = 'jtrainer.server.js',
157
-
158
-
159
- RWSWebPackSettings.devtool = 'source-map';
160
- RWSWebPackSettings.mode = 'development';
161
-
162
- // console.log(RWSWebPackSettings);
163
-
164
- module.exports = RWSWebPackSettings;
165
- ```
166
-
167
- ### RWS webpack config
168
-
169
-
170
- **rws.webpack.config.js:**
171
- ```Js
172
- const path = require('path');
173
- const keysTransformer = require('ts-transformer-keys/transformer').default;
174
- const webpackFilters = require('./webpackFilters');
175
- const nodeExternals = require('webpack-node-externals');
176
- const UtilsService = require('./_tools');
177
-
178
- const rootPackageNodeModules = path.resolve(UtilsService.findRootWorkspacePath(process.cwd()), 'node_modules')
179
-
180
- const modules_setup = [rootPackageNodeModules];
181
-
182
- // console.log(modules_setup)s;
183
-
184
- module.exports = {
185
- entry: `${process.cwd()}/src/index.ts`,
186
- mode: 'development',
187
- target: 'node',
188
- devtool: 'source-map',
189
- output: {
190
- path: path.resolve(__dirname, 'build'),
191
- filename: 'rws.server.js',
192
- sourceMapFilename: '[file].map',
193
- },
194
- resolve: {
195
- modules: modules_setup,
196
- extensions: ['.ts', '.js', '.node'],
197
- alias: {
198
-
199
- },
200
- symlinks: false
201
- },
202
- context: process.cwd(),
203
- module: {
204
- rules: [
205
- {
206
- test: /\.(ts)$/,
207
- use: [
208
- {
209
- loader: 'ts-loader',
210
- options: {
211
- allowTsInNodeModules: true,
212
- configFile: path.resolve(process.cwd() + '/tsconfig.json'),
213
- // compilerOptions: {
214
- // paths: {
215
- // '*': [rootPackageNodeModules + '/*']
216
- // }
217
- // }
218
- }
219
- }
220
- ],
221
- exclude: /node_modules\/(?!@rws-framework/server)/,
222
- },
223
- {
224
- test: /\.node$/,
225
- use: 'node-loader',
226
- }
227
- ],
228
- },
229
- plugins: [
230
- ],
231
- stats: {
232
- warningsFilter: webpackFilters,
233
- },
234
- externals: [nodeExternals({
235
- allowlist: ['@rws-framework/server'],
236
- })],
237
- };
238
- ```
239
-
240
- ### RWS App Configuration
241
-
242
- Define the connection details for your MongoDB instance and server configurations:
243
-
244
- **src/config/config.ts**:
245
-
246
- ```typescript
247
- import { ConsoleService, IAppConfig } from "@rws-framework/server";
248
-
249
- import JWTUser from "../user/model";
250
- import { getModels } from "../models";
251
- import ControllerList from '../controllers/index';
252
- import TimeTrackerSocket from "../sockets/ChatSocket";
253
- import routes from '../routing/routes';
254
- import ws_routes from '../routing/sockets';
255
- import CommandList from '../commands';
256
- import dotenv from 'dotenv';
257
-
258
-
259
- export default (): IAppConfig => {
260
- dotenv.config();
261
- const DB_NAME: string = process.env.MONGO_DB_NAME;
262
- const DB_HOST: string = process.env.MONGO_HOST;
263
- const DB_PORT: number = parseInt(process.env.MONGO_PORT);
264
- const DB_USER: string = process.env.MONGO_INITDB_ROOT_USERNAME;
265
- const DB_PASS: string = process.env.MONGO_INITDB_ROOT_PASSWORD;
266
-
267
- const AWS_ACCESS_KEY: string = process.env.AWS_ACCESS_KEY;
268
- const AWS_SECRET_KEY: string = process.env.AWS_SECRET_KEY;
269
-
270
- const APP_DOMAIN: string = process.env.APP_DOMAIN;
271
- const PUB_FOLDER: string = process.env.PUB_FOLDER;
272
-
273
- const APP_PORT: number = parseInt(process.env.APP_PORT);
274
- const APP_WS_PORT: number = parseInt(process.env.APP_WS_PORT);
275
- const TESTING_PORT: number = parseInt(process.env.TESTING_PORT);
276
- const APP_SSL: boolean = process.env.APP_SSL === 'True';
277
- const APP_CORS_ALLOW: string = process.env.APP_CORS_ALLOW ? process.env.APP_CORS_ALLOW : APP_DOMAIN;
278
-
279
- const dbString: string = `mongodb+srv://${DB_USER}:${DB_PASS}@${DB_HOST}/${DB_NAME}?retryWrites=true&w=majority`;
280
-
281
- return {
282
- features: {
283
- ws_enabled: true,
284
- routing_enabled: true,
285
- ssl: APP_SSL
286
- },
287
- mongo_url: dbString,
288
- mongo_db: DB_NAME,
289
- port: APP_PORT,
290
- ws_port: APP_WS_PORT,
291
- test_port: TESTING_PORT,
292
- domain: APP_DOMAIN,
293
- cors_domain: APP_CORS_ALLOW,
294
- ssl_cert: '',
295
- ssl_key: '',
296
- secret_key: '',
297
- user_class: JWTUser,
298
- user_models: getModels(),
299
- controller_list: ControllerList,
300
- ws_routes: ws_routes,
301
- http_routes: routes(),
302
- commands: CommandList,
303
- aws_lambda_region: null,
304
- aws_access_key: AWS_ACCESS_KEY,
305
- aws_secret_key: AWS_SECRET_KEY,
306
- aws_lambda_role: null,
307
- aws_lambda_bucket: null,
308
- pub_dir: PUB_FOLDER,
309
- }
310
- }
311
- ```
312
-
313
- ### Commands
314
-
315
- ***A sample command***:
316
-
317
- ```typescript
318
- import { ICmdParams, RWSCommand } from '@rws-framework/server';
319
-
320
- class HelloCommand extends RWSCommand {
321
- constructor(){
322
- super('hello', module); // "module" in constructor is required
323
- }
324
-
325
- execute(params?: ICmdParams): void {
326
- console.log('<HELLO COMMAND>\n')
327
- console.log(' Thanks for installing RWS junction instance, ' + params.user + '\n\n');
328
- console.log(' This is output of example command for RWS JS server framework.');
329
- console.log(' (src/commands/HelloCommand.ts).');
330
- console.log(' Develop your server with "yarn dev"\n');
331
- console.log(' Or build and start with "yarn build" and "yarn server"');
332
- console.log('\n\n\n Params passed to this command (those starting with "_" are autogenrated by console script)');
333
- console.log(params);
334
- console.log('\n</HELLO COMMAND>')
335
- }
336
- }
337
-
338
- export default new HelloCommand();
339
- ```
340
-
341
- Command name is set in RWSCommand class constructor params
342
-
343
- args are passed to execute() method
344
-
345
- ```typescript
346
- class NewCommand extends RWSCommand {
347
- constructor(){
348
- super('newcommand');
349
- }
350
-
351
- execute(args){
352
- console.log('DATABASE NAME IS: ', args._rws_config.mongo_db)
353
- }
354
- }
355
- ```
356
-
357
- args are passed like this:
358
-
359
- ```bash
360
- npx rws newcommand arg1=val1,arg2=val2
361
- ```
362
-
363
- ### Database models
364
-
365
- You need to create and export your models in a separate models.ts file. In this example, the getModels() function returns an array of RWS models:
366
-
367
- ```typescript
368
- import TimeSeries from "./TimeSeries";
369
- import TimeTracker from "./TimeTracker";
370
-
371
- export function getModels(): any[] {
372
- return [
373
- TimeTracker,
374
- TimeSeries
375
- ]
376
- }
377
- ```
378
-
379
- RWSModel example:
380
-
381
- ```typescript
382
- import { RWSannotations, RWSModel } from "@rws-framework/server";
383
-
384
- import ITimeTracker from "./interfaces/ITimeTracker";
385
- import 'reflect-metadata';
386
-
387
- import TimeSeries from "./TimeSeries";
388
- const { InverseTimeSeries, TrackType } = RWSannotations.modelAnnotations;
389
-
390
- class TimeTracker extends RWSModel<TimeTracker> implements ITimeTracker {
391
- @TrackType(String, { required: true }, ['unique'])
392
- asset_id: string;
393
-
394
- @TrackType(Number)
395
- elapsed_time: number = 0;
396
-
397
- @TrackType(String, { required: true })
398
- obj_id: string;
399
-
400
- @TrackType(String)
401
- asset_type: string;
402
-
403
- @TrackType(Date)
404
- trace_date: Date;
405
-
406
- @TrackType(String)
407
- user_id: string;
408
-
409
- @TrackType(Boolean)
410
- instructor: boolean;
411
-
412
- @TrackType(Object)
413
- params: any;
414
-
415
- @InverseTimeSeries('time_tracker_measurements', 'measurements')
416
- measurements_ids: string[] = [];
417
- measurements: TimeSeries[] = [];
418
-
419
- static _collection = 'time_tracker';
420
- // static _interface = ITimeTracker;
421
-
422
- constructor(data?: ITimeTracker) {
423
- super(data);
424
-
425
- this.trace_date = new Date();
426
- }
427
-
428
-
429
- addTime(series: TimeSeries){
430
- this.measurements_ids.push(series.id);
431
- this.measurements.push(series);
432
-
433
- let sum = 0;
434
-
435
- this.measurements.forEach(measurement => {
436
- sum += measurement.value;
437
- });
438
-
439
- this.elapsed_time = sum;
440
- }
441
-
442
- getTimes(): TimeSeries[]{
443
- return this.measurements;
444
- }
445
- }
446
-
447
- export default TimeTracker;
448
- ```
449
-
450
- **AFTER EVERY MODEL FIELD CHANGE RUN:**
451
-
452
- ```shell
453
- yarn rws init
454
- ```
455
-
456
- this will update prisma schema for async DB Calls with new fields and their types
457
-
458
- ## Route Configuration
459
-
460
- ### Request Route Configuration
461
- Define your http routes in file that returns array IHTTPRoutes interfaces
462
-
463
- ```typescript
464
- import routes from './routing/routes';
465
- ```
466
-
467
- **routes.ts**:
468
-
469
- *"name"* is annotation route name for controllers
470
- *"path"* is request path
471
-
472
- ```typescript
473
- import {IHTTPRoute} from "@rws-framework/server";
474
-
475
- export default (): IHTTPRoute[] => {
476
- return [
477
- {
478
- prefix: '/prefix',
479
- routes: [
480
- {
481
- name: 'prefix:controller:route',
482
- path: '/prefix/route/path/with/:param'
483
- },
484
- ]
485
- },
486
- {
487
- name: 'home:route',
488
- path: '/*',
489
- noParams: true, // this route will not process parameters and put them to request object
490
- },
491
- ]
492
- }
493
- ```
494
-
495
- Controller routing usage:
496
-
497
- ```typescript
498
- import {
499
- RWSannotations,
500
- RWSController,
501
- IRequestParams
502
- } from "@rws-framework/server";
503
-
504
- const { Route } = RWSannotations.routingAnnotations;
505
- class HomeController extends RWSController{
506
- @Route('home:index', 'GET')
507
- public indexAction(params: IRequestParams): Object
508
- {
509
-
510
- return {
511
- 'success': true
512
- 'data': {
513
- //your response stuff
514
- }
515
- } // Send a response for the root route
516
- }
517
- }
518
-
519
- export default HomeController.getSingleton();
520
- ```
521
-
522
- A controller action with route ":param" usage - this one is called ":bookId'
523
-
524
- ```typescript
525
- @Route('train:get:book', 'GET')
526
- public async getBookAction(params: IRequestParams<any>): Promise<IBook>
527
- {
528
- return await Book.findOneBy({ id: params.req.params.bookId });
529
- }
530
- ```
531
-
532
- A controller action that outputs "template_name" HTML file from "pub_dir" config setting.
533
-
534
- default responseType for @Route is 'json'
535
-
536
- ```typescript
537
- @Route('home:index', 'GET', { responseType: 'html' })
538
- public indexAction(params: IRequestParams<any>): any
539
- {
540
- return {
541
- template_name: 'index',
542
- template_params: {
543
- hello: 'world'
544
- }
545
- }
546
- }
547
- ```
548
-
549
- ### Websocket Route Configuration
550
-
551
- Define your websocket routes in file that returns object with key being event name to be handled and a socket class definition that extends RWSSocket
552
-
553
- ```typescript
554
- import TimeTrackerSocket from "./sockets/TimeTrackerSocket";
555
-
556
- const ws_routes = {
557
- 'time': TimeTrackerSocket
558
- },
559
- ```
560
-
561
- those routes goes to config file in "ws_routes" field
562
-
563
- ## Running the Server
564
-
565
- Create a new index.ts file in the root of your project. This file will import the serverInit function from @rws-framework/server, and your configuration function from config.ts.
566
-
567
- **serverInit() takes in IAppConfig interface:**
568
-
569
- ```typescript
570
- import { RWSHTTPRoutingEntry, WsRoutes, RWSController, RWSCommand } from "../index"
571
-
572
- export default interface IAppConfig {
573
- features?: {
574
- ws_enabled?: boolean
575
- routing_enabled?: boolean
576
- test_routes?: boolean
577
- ssl?: boolean
578
- }
579
- mongo_url: string
580
- mongo_db: string
581
- port: number
582
- ws_port?: number
583
- domain: string
584
- test_port?: number
585
- test_ws_port?: number
586
- ssl_cert: string
587
- ssl_key: string
588
- secret_key: string
589
- user_class: any
590
- user_models: any[]
591
- controller_list: RWSController[]
592
- ws_routes: WsRoutes
593
- http_routes: RWSHTTPRoutingEntry[]
594
- front_routes?: Record<string, unknown>[],
595
- commands?: RWSCommand[]
596
- aws_lambda_region?: string
597
- aws_access_key?: string
598
- aws_secret_key?: string
599
- aws_lambda_role?: string
600
- aws_lambda_bucket?: string
601
- pub_dir?: string
602
- cors_domain?: string
603
- }
604
- ```
605
-
606
- The **serverInit()** cfg to AppConfigService singleton in @RWS module.
607
- It reinstantiates if created empty and had passed config once.
608
-
609
- Every service in @RWS uses AppConfigService
610
-
611
- **serverInit()** from ***{packageDir}/init.ts***
612
- ```typescript
613
- import IAppConfig from "./interfaces/IAppConfig";
614
- import getConfigService, { AppConfigService } from "./services/AppConfigService";
615
- import ServerService, { IInitOpts } from "./services/ServerService";
616
- import ConsoleService from "./services/ConsoleService";
617
- import UtilsService from "./services/UtilsService";
618
-
619
- import fs from "fs";
620
- import ProcessService from "./services/ProcessService";
621
-
622
-
623
- async function init(cfg: IAppConfig, serverOptions: IInitOpts = {}, addToConfig: (configService: AppConfigService) => Promise<void> = null){
624
- const AppConfigService = getConfigService(cfg);
625
- const port = await AppConfigService.get('port');
626
- const ws_port = await AppConfigService.get('ws_port');
627
- const wsRoutes = await AppConfigService.get('ws_routes');
628
- const httpRoutes = await AppConfigService.get('http_routes');
629
- const controler_list = await AppConfigService.get('controller_list');
630
- const pub_dir = await AppConfigService.get('pub_dir');
631
- const cors_domain = await AppConfigService.get('cors_domain');
632
-
633
- const sslCert = AppConfigService.get('ssl_cert');
634
- const sslKey = AppConfigService.get('ssl_key');
635
-
636
- if(addToConfig !== null){
637
- await addToConfig(AppConfigService);
638
- }
639
-
640
- let https = true;
641
-
642
- if(!sslCert || !sslKey){
643
- https = false;
644
- }
645
-
646
- const executeDir: string = process.cwd();
647
- const packageRootDir = UtilsService.findRootWorkspacePath(executeDir)
648
- const moduleCfgDir = `${packageRootDir}/node_modules/.rws`;
649
- const moduleCfgFile = `${moduleCfgDir}/_rws_installed`;
650
-
651
- if(!fs.existsSync(moduleCfgFile)){
652
- ConsoleService.log(ConsoleService.color().yellow('No config path generated for CLI. Trying to initialize with "yarn rws init config/config"'));
653
- await ProcessService.runShellCommand('yarn rws init config/config');
654
- UtilsService.setRWSVar('_rws_installed', 'OK');
655
- }
656
-
657
- const theServer = await ServerService.initializeApp({...{
658
- wsRoutes: wsRoutes,
659
- httpRoutes: httpRoutes,
660
- controllerList: controler_list,
661
- pub_dir: pub_dir,
662
- domain: `http${(await AppConfigService.get('features')?.ssl ? 's' : '')}://${await AppConfigService.get('domain')}`,
663
- cors_domain: cors_domain
664
- },...serverOptions});
665
-
666
- const wsStart = async () => {
667
- return (await theServer.websocket.starter());
668
- }
669
-
670
- const httpStart = async () => {
671
- return (await theServer.http.starter());
672
- }
673
-
674
- wsStart();
675
- await httpStart();
676
- }
677
-
678
- export default init;
679
-
680
-
681
- ```
682
-
683
- ###
684
-
685
- **DBService**
686
-
687
- reading config from config singleton filled with cfg data passed to @RWS
688
-
689
- ```typescript
690
- class DBService extends TheService {
691
- private client: PrismaClient;
692
- private opts:IDBClientCreate = null;
693
- private connected = false;
694
-
695
- constructor(opts: IDBClientCreate = null){
696
- super();
697
- }
698
-
699
- private connectToDB(opts: IDBClientCreate = null) {
700
- if(opts){
701
- this.opts = opts;
702
- }else{
703
- this.opts = {
704
- dbUrl: getConfig().get('mongo_url'),
705
- dbName: getConfig().get('mongo_db'),
706
- }
707
- }
708
-
709
- if(!this.opts.dbUrl){
710
- return;
711
- }
712
-
713
- try{
714
- this.client = new PrismaClient({
715
- datasources: {
716
- db: {
717
- url: this.opts.dbUrl
718
- },
719
- },
720
- });
721
-
722
- this.connected = true;
723
- } catch (e){
724
- ConsoleService.error('PRISMA CONNECTION ERROR');
725
- }
726
- }
727
-
728
- private async createBaseMongoClient(): Promise<MongoClient>
729
- {
730
- const dbUrl = this.opts?.dbUrl || getConfig().get('mongo_url');
731
- const client = new MongoClient(dbUrl);
732
-
733
- await client.connect();
734
-
735
- return client;
736
-
737
- }
738
-
739
- //(...)
740
- ```
741
- ## Implementation
742
- ### index.ts from your root/src directory##:
743
-
744
- ```typescript
745
- import { serverInit, ConsoleService, getAppConfig } from "@rws-framework/server";
746
- import config from './config/config'
747
- import BedrockService from "./services/BedrockService";
748
-
749
- // import path from 'path';
750
-
751
- async function main(){
752
- await serverInit(config());
753
-
754
- getAppConfig().set('extra_param', 'value');
755
- }
756
-
757
- main().then(() => {
758
- ConsoleService.log("Initialization complete");
759
- }).catch((e) => {
760
- ConsoleService.error(e);
761
- console.error(e);
762
- });
763
-
764
- ```
765
-
766
- *The prisma client will have generated Prisma models called exactly like _collection variable in RWS models. You can dierectly act on it without traversing dynamic prisma collections array inside the started client import.*
767
-
768
- ```typescript
769
- import { track_type } from "@prisma/client";
770
- ```
771
-
772
- to start server in dev env:
773
-
774
-
775
- **in root package.json:**
776
- ```Json
777
- {
778
- "scripts": {
779
- "dev": "npm-run-all --parallel watch:transpile watch:run",
780
- "watch:run": "nodemon \"./build/rws.server.js\" --watch \"./build\"",
781
- "watch:transpile": "webpack --config webpack.config.js --watch",
782
- "build": "webpack --config webpack.config.js --output-path ./dist",
783
- "server": "node dist/rws.server.js",
784
- "hello": "npx rws hello user=$USER",
785
- "postinstall": "npx rws init config=config/config && yarn hello",
786
- "test": "npx mocha"
787
- }
788
- }
789
-
790
- ```
791
-
792
- ## Executing server
793
-
794
-
795
- ### build:
796
-
797
- ```bash
798
- yarn build
799
- ```
800
-
801
- ### watch:
802
-
803
- ```bash
804
- yarn dev
805
- ```
806
- ### run:
807
-
808
- ```bash
809
- yarn server
810
- ```
811
-
812
- ### test:
813
-
814
- ```bash
815
- yarn test
816
- ```
817
-
818
- *("hello" is a sample command)*
819
-
820
- ## BASH installs for node libraries
821
-
822
- for local servers - libs are in docker/ Dockerfiles
823
-
824
- ```bash
825
- apt-get install -y \
826
- libgtk-3-0 \
827
- libxss1 \
828
- libasound2 \
829
- libnss3 \
830
- libxtst6 \
831
- gconf-service \
832
- libatk1.0-0 \
833
- libatk-bridge2.0-0 \
834
- libc6 \
835
- libcairo2 \
836
- libcups2 \
837
- libdbus-1-3 \
838
- libexpat1 \
839
- libfontconfig1 \
840
- libgcc1 \
841
- libgconf-2-4 \
842
- libgdk-pixbuf2.0-0 \
843
- libglib2.0-0 \
844
- libnspr4 \
845
- libpango-1.0-0 \
846
- libpangocairo-1.0-0 \
847
- libstdc++6 \
848
- libx11-6 \
849
- libx11-xcb1 \
850
- libxcb1 \
851
- libxcomposite1 \
852
- libxcursor1 \
853
- libxdamage1 \
854
- libxext6 \
855
- libxfixes3 \
856
- libxi6 \
857
- libxrandr2 \
858
- libxrender1 \
859
- libappindicator1 \
860
- lsb-release \
861
- xdg-utils
862
- ```
3
+ AI tools for Realtime Web Suit
package/package.json CHANGED
@@ -1,24 +1,25 @@
1
1
  {
2
2
  "name": "@rws-framework/ai-tools",
3
3
  "private": false,
4
- "version": "0.0.1",
4
+ "version": "0.0.3",
5
5
  "description": "",
6
6
  "main": "src/index.ts",
7
- "scripts": {
8
- },
7
+ "scripts": {},
9
8
  "author": "papablack",
10
9
  "license": "ISC",
11
10
  "dependencies": {
12
- "@nestjs/common": "^10.3.2",
13
- "@nestjs/core": "^10.3.2",
14
- "@rws-framework/console": "*",
15
11
  "@langchain/community": "^0.2.27",
16
12
  "@langchain/core": "^0.2.27",
13
+ "@nestjs/common": "^10.3.2",
14
+ "@nestjs/core": "^10.3.2",
15
+ "@rws-framework/console": "*",
16
+ "@rws-framework/server": "3.2.9-alpha",
17
17
  "langchain": "^0.2.16",
18
18
  "uuid": "^9.0.0",
19
19
  "xml2js": "^0.6.2"
20
20
  },
21
21
  "devDependencies": {
22
+ "@types/xml2js": "^0.4.14"
22
23
  },
23
24
  "resolutions": {
24
25
  "@langchain/community/**/@langchain/core": "0.2.27",
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import RWSPrompt, { ILLMChunk, IRWSPromptRequestExecutor, IRWSSinglePromptReques
3
3
  import RWSConvo, { IConvoDebugXMLData, IEmbeddingsHandler, ISplitterParams } from './models/convo/ConvoLoader';
4
4
  import RWSVectorStore from './models/convo/VectorStore';
5
5
  import { VectorStoreService } from './services/VectorStoreService';
6
+ import { IContextToken } from './types/IContextToken';
6
7
 
7
8
  export {
8
9
  VectorStoreService,
@@ -18,5 +19,6 @@ export {
18
19
  ChainStreamType,
19
20
  IConvoDebugXMLData,
20
21
  IEmbeddingsHandler,
21
- ISplitterParams
22
+ ISplitterParams,
23
+ IContextToken
22
24
  };
@@ -21,8 +21,6 @@ import fs from 'fs';
21
21
  import path from 'path';
22
22
 
23
23
 
24
- const { Error500 } = RWSErrorCodes;
25
-
26
24
  interface ISplitterParams {
27
25
  chunkSize: number
28
26
  chunkOverlap: number
@@ -87,19 +85,24 @@ class ConvoLoader<LLMChat extends BaseChatModel> {
87
85
 
88
86
  public _baseSplitterParams: ISplitterParams;
89
87
 
90
- constructor(chatConstructor: new (config: any) => LLMChat, embeddings: IEmbeddingsHandler<any> | null = null, convoId: string | null = null, baseSplitterParams: ISplitterParams = {
91
- chunkSize:400, chunkOverlap:80, separators: ['/n/n','.']
92
- }){
88
+ constructor(
89
+ chatConstructor: new (config: any) => LLMChat,
90
+ embeddings: IEmbeddingsHandler<any> | null = null,
91
+ convoId: string | null = null,
92
+ baseSplitterParams: ISplitterParams = {
93
+ chunkSize: 400,
94
+ chunkOverlap: 80,
95
+ separators: ['/n/n','.']
96
+ }
97
+ ) {
93
98
  this.embeddings = embeddings;
94
-
95
- if(convoId === null){
99
+ if(convoId === null) {
96
100
  this.convo_id = ConvoLoader.uuid();
97
101
  } else {
98
102
  this.convo_id = convoId;
99
103
  }
100
-
101
104
  this.chatConstructor = chatConstructor;
102
- this._baseSplitterParams = baseSplitterParams;
105
+ this._baseSplitterParams = baseSplitterParams;
103
106
  }
104
107
 
105
108
  static uuid(): string
@@ -112,7 +115,7 @@ class ConvoLoader<LLMChat extends BaseChatModel> {
112
115
  {
113
116
 
114
117
  if(!this.embeddings){
115
- throw new Error500('No embeddings provided for ConvoLoader\'s constructor. ConvoLoader.splitDocs aborting...');
118
+ throw new Error('No embeddings provided for ConvoLoader\'s constructor. ConvoLoader.splitDocs aborting...');
116
119
  }
117
120
 
118
121
  const splitDir = ConvoLoader.debugSplitDir(this.getId());
@@ -208,7 +211,7 @@ class ConvoLoader<LLMChat extends BaseChatModel> {
208
211
  return documents.reduce((sum, doc: Document) => sum + doc.pageContent.length, 0) / documents.length;
209
212
  };
210
213
 
211
- async call(values: ChainValues, cfg: Partial<RunnableConfig>, debugCallback: (debugData: IConvoDebugXMLData) => Promise<IConvoDebugXMLData> = null): Promise<RWSPrompt>
214
+ async call(values: ChainValues, cfg: any, debugCallback: (debugData: IConvoDebugXMLData) => Promise<IConvoDebugXMLData> = null): Promise<RWSPrompt>
212
215
  {
213
216
  const output = await (this.chain()).invoke(values, cfg) as IChainCallOutput;
214
217
  this.thePrompt.listen(output.text);
@@ -218,33 +221,6 @@ class ConvoLoader<LLMChat extends BaseChatModel> {
218
221
  return this.thePrompt;
219
222
  }
220
223
 
221
- async *callStreamGenerator(
222
- this: ConvoLoader<LLMChat>,
223
- values: ChainValues,
224
- cfg: Partial<RunnableConfig>,
225
- debugCallback: (debugData: IConvoDebugXMLData) => Promise<IConvoDebugXMLData> = null
226
- ): AsyncGenerator<string>
227
- {
228
- // const _self = this;
229
- // const chain = this.chain() as ConversationChain;
230
- // console.log('call stream');
231
- // const stream = await chain.call(values, [{
232
- // handleLLMNewToken(token: string) {
233
- // yield token;
234
- // }
235
- // }
236
- // ]);
237
-
238
- // console.log('got stream');
239
-
240
-
241
-
242
- // Listen to the stream and yield data chunks as they come
243
- // for await (const chunk of stream) {
244
- // yield chunk.response;
245
- // }
246
- }
247
-
248
224
  async callStream(values: ChainValues, callback: (streamChunk: ILLMChunk) => void, end: () => void = () => {}, cfg: Partial<RunnableConfig> = {}, debugCallback?: (debugData: IConvoDebugXMLData) => Promise<IConvoDebugXMLData>): Promise<RWSPrompt>
249
225
  {
250
226
  const _self = this;
@@ -303,7 +279,7 @@ class ConvoLoader<LLMChat extends BaseChatModel> {
303
279
  }
304
280
 
305
281
  if(!this.thePrompt){
306
- throw new Error500(new Error('No prompt initialized for conversation'), __filename);
282
+ throw new Error('No prompt initialized for conversation');
307
283
  }
308
284
 
309
285
  const chainParams: { prompt: PromptTemplate, values?: ChainValues } = {
@@ -318,8 +294,8 @@ class ConvoLoader<LLMChat extends BaseChatModel> {
318
294
  private async createChain(input: { prompt: PromptTemplate, values?: ChainValues }): Promise<BaseChain>
319
295
  {
320
296
  this.llmChain = new ConversationChain({
321
- llm: this.llmChat,
322
- prompt: input.prompt,
297
+ llm: this.llmChat as any,
298
+ prompt: input.prompt as any,
323
299
  });
324
300
 
325
301
  return this.llmChain;
@@ -6,6 +6,7 @@ import { IterableReadableStream } from '@langchain/core/utils/stream';
6
6
  import { ChainValues } from '@langchain/core/utils/types';
7
7
 
8
8
  import { IContextToken } from '../../types/IContextToken';
9
+ import { BaseChatModel } from '@langchain/core/language_models/chat_models';
9
10
 
10
11
  interface IPromptHyperParameters {
11
12
  temperature: number,
@@ -214,14 +215,14 @@ class RWSPrompt {
214
215
  return this.multiTemplate;
215
216
  }
216
217
 
217
- setConvo(convo: ConvoLoader<BedrockChat>): RWSPrompt
218
+ setConvo(convo: ConvoLoader<BaseChatModel>): RWSPrompt
218
219
  {
219
220
  this.convo = convo.setPrompt(this);
220
221
 
221
222
  return this;
222
223
  }
223
224
 
224
- getConvo<T extends BedrockChat>(): ConvoLoader<T>
225
+ getConvo<T extends BaseChatModel>(): ConvoLoader<T>
225
226
  {
226
227
  return this.convo;
227
228
  }
@@ -0,0 +1,6 @@
1
+ interface IContextToken {
2
+ value: string
3
+ }
4
+
5
+
6
+ export { IContextToken };