-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprint.html
More file actions
10092 lines (9713 loc) · 677 KB
/
print.html
File metadata and controls
10092 lines (9713 loc) · 677 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html lang="en" class="light sidebar-visible" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Light-4j Platform</title>
<meta name="robots" content="noindex">
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon-de23e50b.svg">
<link rel="shortcut icon" href="favicon-8114d1fc.png">
<link rel="stylesheet" href="css/variables-8adf115d.css">
<link rel="stylesheet" href="css/general-2459343d.css">
<link rel="stylesheet" href="css/chrome-ae938929.css">
<link rel="stylesheet" href="css/print-9e4910d8.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="fonts/fonts-9644e21d.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" id="mdbook-highlight-css" href="highlight-493f70e1.css">
<link rel="stylesheet" id="mdbook-tomorrow-night-css" href="tomorrow-night-4c0ae647.css">
<link rel="stylesheet" id="mdbook-ayu-highlight-css" href="ayu-highlight-3fdfc3ac.css">
<!-- Custom theme stylesheets -->
<!-- Provide site root and default themes to javascript -->
<script>
const path_to_root = "";
const default_light_theme = "light";
const default_dark_theme = "navy";
window.path_to_searchindex_js = "searchindex-4de36bde.js";
</script>
<!-- Start loading toc.js asap -->
<script src="toc-49b52dcd.js"></script>
</head>
<body>
<div id="mdbook-help-container">
<div id="mdbook-help-popup">
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
<div>
<p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p>
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
<p>Press <kbd>?</kbd> to show this help</p>
<p>Press <kbd>Esc</kbd> to hide this help</p>
</div>
</div>
</div>
<div id="mdbook-body-container">
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
let theme = localStorage.getItem('mdbook-theme');
let sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
let theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
const html = document.documentElement;
html.classList.remove('light')
html.classList.add(theme);
html.classList.add("js");
</script>
<input type="checkbox" id="mdbook-sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
let sidebar = null;
const sidebar_toggle = document.getElementById("mdbook-sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
sidebar_toggle.checked = false;
}
if (sidebar === 'visible') {
sidebar_toggle.checked = true;
} else {
html.classList.remove('sidebar-visible');
}
</script>
<nav id="mdbook-sidebar" class="sidebar" aria-label="Table of contents">
<!-- populated by js -->
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
<noscript>
<iframe class="sidebar-iframe-outer" src="toc.html"></iframe>
</noscript>
<div id="mdbook-sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<div id="mdbook-page-wrapper" class="page-wrapper">
<div class="page">
<div id="mdbook-menu-bar-hover-placeholder"></div>
<div id="mdbook-menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="mdbook-sidebar-toggle" class="icon-button" for="mdbook-sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="mdbook-sidebar">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z"/></svg></span>
</label>
<button id="mdbook-theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="mdbook-theme-list">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z"/></svg></span>
</button>
<ul id="mdbook-theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-default_theme">Auto</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-ayu">Ayu</button></li>
</ul>
<button id="mdbook-search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="mdbook-searchbar">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z"/></svg></span>
</button>
</div>
<h1 class="menu-title">Light-4j Platform</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<span class=fa-svg id="print-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z"/></svg></span>
</a>
</div>
</div>
<div id="mdbook-search-wrapper" class="hidden">
<form id="mdbook-searchbar-outer" class="searchbar-outer">
<div class="search-wrapper">
<input type="search" id="mdbook-searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="mdbook-searchresults-outer" aria-describedby="searchresults-header">
<div class="spinner-wrapper">
<span class=fa-svg id="fa-spin"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z"/></svg></span>
</div>
</div>
</form>
<div id="mdbook-searchresults-outer" class="searchresults-outer hidden">
<div id="mdbook-searchresults-header" class="searchresults-header"></div>
<ul id="mdbook-searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="mdbook-content" class="content">
<main>
<h1 id="introduction"><a class="header" href="#introduction">Introduction</a></h1>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="architecture"><a class="header" href="#architecture">Architecture</a></h1>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="design"><a class="header" href="#design">Design</a></h1>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="light-genai-4j"><a class="header" href="#light-genai-4j">light-genai-4j</a></h1>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="memory-and-embedding-design"><a class="header" href="#memory-and-embedding-design">Memory and Embedding Design</a></h1>
<h2 id="overview"><a class="header" href="#overview">Overview</a></h2>
<p>This document outlines the design decisions for memory management, embedding models, and storage architecture for the light-genai-4j agent system.</p>
<p>For agent skills and tool execution, see <a href="design/light-genai-4j/agent-skill.html">Agent Skill Design</a>.</p>
<h2 id="1-embedding-model-selection"><a class="header" href="#1-embedding-model-selection">1. Embedding Model Selection</a></h2>
<h3 id="11-chosen-model-bge-small-en-v15-quantized"><a class="header" href="#11-chosen-model-bge-small-en-v15-quantized">1.1 Chosen Model: BGE-small-en-v1.5 (Quantized)</a></h3>
<p><strong>Artifact</strong>: <code>bge-small-en-v15-q</code> (migrated from langchain4j)</p>
<p><strong>Specifications</strong>:</p>
<ul>
<li><strong>Dimensions</strong>: 384</li>
<li><strong>Pooling Mode</strong>: CLS (uses [CLS] token representation)</li>
<li><strong>Model Size</strong>: ~17MB (quantized version)</li>
<li><strong>Language</strong>: English (primary), supports basic multilingual capability</li>
<li><strong>Source</strong>: BAAI (Beijing Academy of Artificial Intelligence)</li>
</ul>
<h3 id="12-why-bge-small-en-v15"><a class="header" href="#12-why-bge-small-en-v15">1.2 Why BGE-small-en-v1.5?</a></h3>
<div class="table-wrapper">
<table>
<thead>
<tr><th>Use Case</th><th>Requirement</th><th>How BGE Fits</th></tr>
</thead>
<tbody>
<tr><td><strong>Short-term Memory</strong></td><td>Fast retrieval of recent context</td><td>Optimized for semantic similarity search</td></tr>
<tr><td><strong>Long-term Memory</strong></td><td>Finding relevant past conversations</td><td>State-of-the-art for asymmetric retrieval (query → document)</td></tr>
<tr><td><strong>Knowledge Base</strong></td><td>RAG (Retrieval-Augmented Generation)</td><td>Best-in-class for information retrieval</td></tr>
</tbody>
</table>
</div>
<h3 id="13-comparison-with-alternatives"><a class="header" href="#13-comparison-with-alternatives">1.3 Comparison with Alternatives</a></h3>
<div class="table-wrapper">
<table>
<thead>
<tr><th>Model</th><th>Dimensions</th><th>Best For</th><th>Why Not Chosen</th></tr>
</thead>
<tbody>
<tr><td>all-MiniLM-L6-v2</td><td>384</td><td>General similarity</td><td>Not optimized for retrieval tasks</td></tr>
<tr><td>E5-small-v2</td><td>384</td><td>Asymmetric search</td><td>Query/passage prefixes more complex</td></tr>
<tr><td>BGE-small-en</td><td>384</td><td>English retrieval</td><td>v1.5 has better performance</td></tr>
<tr><td>BGE-small-zh-v1.5</td><td>512</td><td>Chinese</td><td>Different dimensions (see Section 4)</td></tr>
</tbody>
</table>
</div>
<h3 id="14-usage-pattern"><a class="header" href="#14-usage-pattern">1.4 Usage Pattern</a></h3>
<pre><code class="language-java">// For queries (retrieving memories/knowledge)
String queryPrefix = "Represent this sentence for searching relevant passages:";
String query = queryPrefix + " " + userMessage;
// For storing (memories, knowledge documents)
String document = conversationText; // No prefix needed
</code></pre>
<h2 id="2-vector-database-postgresql-with-pgvector"><a class="header" href="#2-vector-database-postgresql-with-pgvector">2. Vector Database: PostgreSQL with pgvector</a></h2>
<h3 id="21-schema-design"><a class="header" href="#21-schema-design">2.1 Schema Design</a></h3>
<p>The schema adopts a <strong>scope-based memory model</strong> (similar to <a href="https://github.com/mem0ai/mem0">mem0</a>), organizing memory by lifetime and visibility rather than abstract types.</p>
<pre><code class="language-sql">-- Enable pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Session Memory (Short-term)
-- Stores in-flight conversation context. Auto-expires via TTL.
CREATE TABLE session_memories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
session_id UUID NOT NULL,
agent_id UUID NOT NULL,
user_id UUID, -- NULL allowed for anonymous sessions or background system tasks
content TEXT NOT NULL,
embedding VECTOR(384),
importance_score FLOAT DEFAULT 1.0,
created_at TIMESTAMP DEFAULT NOW(),
expires_at TIMESTAMP DEFAULT NOW() + INTERVAL '1 hour', -- TTL
metadata JSONB -- Rich filtering (e.g., {"topic": "debug", "turn": 5})
);
-- User Memory (Long-term)
-- Stores persistent facts/preferences about a user. Manual or inferred.
CREATE TABLE user_memories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
agent_id UUID NOT NULL,
user_id UUID NOT NULL, -- Must be tied to a specific user
content TEXT NOT NULL, -- e.g., "User prefers Java over Python"
embedding VECTOR(384),
memory_type VARCHAR(50), -- 'fact', 'preference', 'summary'
importance_score FLOAT DEFAULT 1.0,
access_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT NOW(),
last_accessed TIMESTAMP DEFAULT NOW(),
metadata JSONB -- e.g., {"confidence": 0.9, "source": "conversation_123"}
);
-- Agent Memory (Private/Operational)
-- Stores agent-specific learning, state, or persistent persona data.
-- Scope: Private to the agent, typically across multiple users or sessions.
CREATE TABLE agent_memories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
agent_id UUID NOT NULL,
-- NO user_id: This is agent-centric knowledge
content TEXT NOT NULL,
embedding VECTOR(384),
memory_type VARCHAR(50), -- 'learning', 'state', 'persona', 'scratchpad'
created_at TIMESTAMP DEFAULT NOW(),
metadata JSONB
);
-- Organizational Memory (Knowledge Base)
-- Stores global, shared knowledge available to all agents/users.
CREATE TABLE organizational_memories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
agent_id UUID NOT NULL,
source VARCHAR(255), -- Document source/name
content TEXT NOT NULL,
embedding VECTOR(384),
chunk_index INTEGER, -- For large documents split into chunks
document_id UUID, -- Reference to parent document
created_at TIMESTAMP DEFAULT NOW(),
metadata JSONB -- e.g., {"department": "HR", "version": "1.0"}
);
-- Indexes for similarity search and metadata filtering
CREATE INDEX idx_session_memory_embedding ON session_memories
USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
CREATE INDEX idx_session_metadata ON session_memories USING GIN (metadata);
CREATE INDEX idx_user_memory_embedding ON user_memories
USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
CREATE INDEX idx_user_metadata ON user_memories USING GIN (metadata);
CREATE INDEX idx_agent_memory_embedding ON agent_memories
USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
CREATE INDEX idx_agent_metadata ON agent_memories USING GIN (metadata);
CREATE INDEX idx_org_memory_embedding ON organizational_memories
USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
CREATE INDEX idx_org_metadata ON organizational_memories USING GIN (metadata);
</code></pre>
<h3 id="22-memory-lifecycle"><a class="header" href="#22-memory-lifecycle">2.2 Memory Lifecycle</a></h3>
<p>The system follows a promotion strategy:</p>
<pre><code>User Input
│
▼
┌─────────────────────────────────────┐
│ Query Embedding (with prefix) │
└─────────────────────────────────────┘
│
├──► Search Session Memory (Context)
│ └── Recent turns, immediate task context
│
├──► Search User Memory (Personalization)
│ └── User preferences, past decisions, facts
│
├──► Search Agent Memory (Self-Knowledge)
│ └── Agent persona, learned behaviors, operational state
│
└──► Search Organizational Memory (Knowledge)
└── Policies, docs, FAQs
│
▼
Consolidated Context → LLM
│
▼
Store Response ──────► Session Memory
│ │
│ ▼
│ (Optional: Extraction/Inference)
│ Run LLM to extract facts from conversation
│ │
│ ┌──────────────┴──────────────┐
│ ▼ ▼
│ User Memory Agent Memory
│ (User Facts) (Agent Learnings)
│
▼
(Session ends)
Session Memory Expires
</code></pre>
<h3 id="23-memory-retrieval-strategy"><a class="header" href="#23-memory-retrieval-strategy">2.3 Memory Retrieval Strategy</a></h3>
<pre><code class="language-java">public class MemoryService {
public List<Memory> retrieveRelevantMemories(String query, UUID sessionId, UUID userId, UUID agentId) {
// 1. Embed the query with prefix
String prefixedQuery = "Represent this sentence for searching relevant passages: " + query;
Embedding queryEmbedding = embeddingModel.embed(prefixedQuery);
// 2. Search Session Memory (Short-term context)
List<Memory> sessionContext = searchSession(queryEmbedding, sessionId, limit = 10);
// 3. Search User Memory (Personalization)
List<Memory> userFacts = searchUser(queryEmbedding, userId, limit = 5);
// 4. Search Agent Memory (Agent Self-Knowledge)
List<Memory> agentFacts = searchAgent(queryEmbedding, agentId, limit = 3);
// 5. Search Organizational Memory (Knowledge Base)
List<Memory> orgKnowledge = searchOrg(queryEmbedding, agentId, limit = 5);
// 6. Combine and Rerank
return combineAndRank(sessionContext, userFacts, agentFacts, orgKnowledge);
}
private List<Memory> searchSession(Embedding query, UUID sessionId, int limit) {
String sql = """
SELECT id, content, embedding <=> ? AS distance
FROM session_memories
WHERE session_id = ? AND expires_at > NOW()
ORDER BY embedding <=> ?
LIMIT ?
""";
// Execute query...
}
}
</code></pre>
<h2 id="3-scaling--advanced-patterns"><a class="header" href="#3-scaling--advanced-patterns">3. Scaling & Advanced Patterns</a></h2>
<h3 id="31-hnsw-indexing-hierarchical-navigable-small-world"><a class="header" href="#31-hnsw-indexing-hierarchical-navigable-small-world">3.1 HNSW Indexing (Hierarchical Navigable Small World)</a></h3>
<p>As the organizational memory grows (millions of records), standard <code>ivfflat</code> indexes may become too slow or inaccurate. We recommend using <strong>HNSW</strong> indexes for scalable vector search.</p>
<p><strong>Implementation in pgvector:</strong></p>
<pre><code class="language-sql">-- Replace standard index with HNSW
CREATE INDEX idx_org_memory_hnsw ON organizational_memories
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
</code></pre>
<ul>
<li><code>m</code>: Max connections per layer (higher = better recall, larger index).</li>
<li><code>ef_construction</code>: Size of dynamic list during build (higher = better quality, slower build).</li>
</ul>
<h3 id="32-graphrag-future-roadmap"><a class="header" href="#32-graphrag-future-roadmap">3.2 GraphRAG (Future Roadmap)</a></h3>
<p>To support multi-hop reasoning (e.g., “How does Project X relate to Policy Y?”), standard vector search is insufficient. <strong>GraphRAG</strong> combines vector search with knowledge graph traversal.</p>
<p><strong>Relational Graph Schema (PostgreSQL):</strong>
Instead of a separate Graph DB, we can model entities and relationships directly in SQL.</p>
<pre><code class="language-sql">-- Extracted Entities (Nodes)
CREATE TABLE entities (
id UUID PRIMARY KEY,
name VARCHAR(255),
type VARCHAR(50), -- 'Person', 'Project', 'Technology'
description TEXT,
embedding VECTOR(384) -- For hybrid search
);
-- Relationships (Edges)
CREATE TABLE relationships (
source_id UUID REFERENCES entities(id),
target_id UUID REFERENCES entities(id),
relation_type VARCHAR(50), -- 'CREATED_BY', 'DEPENDS_ON'
description TEXT,
weight FLOAT DEFAULT 1.0,
PRIMARY KEY (source_id, target_id, relation_type)
);
-- Linking Text Chunks to Knowledge Graph
CREATE TABLE memory_entities (
memory_id UUID REFERENCES organizational_memories(id),
entity_id UUID REFERENCES entities(id),
PRIMARY KEY (memory_id, entity_id)
);
</code></pre>
<h3 id="33-evaluation-of-recursive-language-models-rlm"><a class="header" href="#33-evaluation-of-recursive-language-models-rlm">3.3 Evaluation of Recursive Language Models (RLM)</a></h3>
<p>We evaluated <a href="https://alexzhang13.github.io/blog/2025/rlm/">Recursive Language Models (RLM)</a> as a potential solution for large-scale memory.</p>
<p><strong>Conclusion: NOT ADOPTED as Storage Architecture.</strong></p>
<p>RLM is an <em>inference strategy</em> (processing huge inputs by letting an LLM recursively chunk and summarize text via code execution), not a <em>storage solution</em>.</p>
<ul>
<li><strong>Pros</strong>: Can “reason” over 10M+ tokens without context rot.</li>
<li><strong>Cons</strong>: Extremely slow (minutes), high cost, and requires complex code execution sandboxing.</li>
</ul>
<p><strong>Recommendation</strong>: Use PostgreSQL/pgvector (with HNSW) as the primary storage. Implement RLM-like logic only as a specific <strong>“Deep Research” Skill</strong> (e.g., <code>analyze_large_document</code>) if the agent needs to process massive files on-demand, but do not use it for general memory retrieval.</p>
<h2 id="4-internationalization-chinese-support"><a class="header" href="#4-internationalization-chinese-support">4. Internationalization: Chinese Support</a></h2>
<h3 id="31-the-dimension-problem"><a class="header" href="#31-the-dimension-problem">3.1 The Dimension Problem</a></h3>
<ul>
<li><strong>BGE-small-en-v1.5</strong>: 384 dimensions</li>
<li><strong>BGE-small-zh-v1.5</strong>: 512 dimensions</li>
</ul>
<p><strong>Cannot mix in same vector column!</strong></p>
<h3 id="32-solutions"><a class="header" href="#32-solutions">3.2 Solutions</a></h3>
<h4 id="option-a-separate-tables-recommended"><a class="header" href="#option-a-separate-tables-recommended">Option A: Separate Tables (Recommended)</a></h4>
<pre><code class="language-sql">-- English memories
CREATE TABLE short_term_memories_en (
-- ... same schema ...
embedding VECTOR(384)
);
-- Chinese memories
CREATE TABLE short_term_memories_zh (
-- ... same schema ...
embedding VECTOR(512)
);
-- Query both and merge results in application layer
</code></pre>
<h4 id="option-b-unified-multilingual-model"><a class="header" href="#option-b-unified-multilingual-model">Option B: Unified Multilingual Model</a></h4>
<p>When adding Chinese support, switch to a multilingual model:</p>
<div class="table-wrapper">
<table>
<thead>
<tr><th>Model</th><th>Dimensions</th><th>Languages</th><th>Trade-off</th></tr>
</thead>
<tbody>
<tr><td>BGE-small-en-v1.5</td><td>384</td><td>En + basic multilingual</td><td>Use for both initially</td></tr>
<tr><td>BGE-base-en-v1.5</td><td>768</td><td>Better multilingual</td><td>Higher dimensions</td></tr>
<tr><td>Multilingual-E5</td><td>384</td><td>100+ languages</td><td>May require re-embedding</td></tr>
</tbody>
</table>
</div>
<h4 id="option-c-re-embed-everything"><a class="header" href="#option-c-re-embed-everything">Option C: Re-embed Everything</a></h4>
<p>When ready for Chinese:</p>
<ol>
<li>Choose new multilingual model</li>
<li>Re-embed all existing memories</li>
<li>Single table with new dimensions</li>
</ol>
<h3 id="33-recommendation"><a class="header" href="#33-recommendation">3.3 Recommendation</a></h3>
<p><strong>Phase 1 (English only)</strong>:</p>
<ul>
<li>Use <code>BGE-small-en-v1.5-q</code> (384d)</li>
<li>Single table structure</li>
</ul>
<p><strong>Phase 2 (Add Chinese)</strong>:</p>
<ul>
<li>Option: Use <code>BGE-small-en-v1.5</code> for both (decent Chinese support)</li>
<li>Or create separate <code>_zh</code> tables with <code>BGE-small-zh-v1.5</code> (512d)</li>
<li>Query service merges results from both tables</li>
</ul>
<h2 id="4-implementation-guidelines"><a class="header" href="#4-implementation-guidelines">4. Implementation Guidelines</a></h2>
<h3 id="41-dependencies"><a class="header" href="#41-dependencies">4.1 Dependencies</a></h3>
<pre><code class="language-xml"><!-- pom.xml -->
<dependency>
<groupId>com.networknt</groupId>
<artifactId>bge-small-en-v15-q</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.1</version>
</dependency>
</code></pre>
<h3 id="42-configuration"><a class="header" href="#42-configuration">4.2 Configuration</a></h3>
<pre><code class="language-yaml"># application.yml
memory:
embedding:
model: bge-small-en-v1.5-q
dimensions: 384
query-prefix: "Represent this sentence for searching relevant passages:"
storage:
type: postgresql
url: ${PGVECTOR_URL}
username: ${PGVECTOR_USER}
password: ${PGVECTOR_PASSWORD}
short-term:
ttl-minutes: 60
max-memories: 100
long-term:
min-importance: 0.5
max-results: 10
knowledge:
chunk-size: 512
overlap: 50
</code></pre>
<h3 id="43-key-design-principles"><a class="header" href="#43-key-design-principles">4.3 Key Design Principles</a></h3>
<ol>
<li><strong>Separate Concerns</strong>: Vector DB for semantic search, SQL for structured data</li>
<li><strong>Query Prefixing</strong>: Always use BGE’s recommended prefix for queries</li>
<li><strong>Lifecycle Management</strong>: Short-term expires, long-term persists, both consolidate</li>
<li><strong>Dimension Consistency</strong>: Plan for Chinese support from day one</li>
</ol>
<h2 id="5-references"><a class="header" href="#5-references">5. References</a></h2>
<ul>
<li><a href="https://arxiv.org/abs/2309.07597">BGE Paper</a></li>
<li><a href="https://github.com/pgvector/pgvector">pgvector Documentation</a></li>
<li><a href="https://huggingface.co/BAAI">Hugging Face BGE Models</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="agent-skill-tool-design"><a class="header" href="#agent-skill-tool-design">Agent Skill Tool Design</a></h1>
<h2 id="overview-1"><a class="header" href="#overview-1">Overview</a></h2>
<p>This document outlines the design decisions for agent skills, tools, their relationship (Progressive Disclosure), and the execution architecture for the light-genai-4j agent system.</p>
<h2 id="1-defining-skills-vs-tools"><a class="header" href="#1-defining-skills-vs-tools">1. Defining Skills vs. Tools</a></h2>
<p>In the light-genai-4j agent architecture, we adhere to the <strong>Model Context Protocol (MCP)</strong> separation of concerns:</p>
<ul>
<li><strong>Skills (The “Expertise”)</strong>: Sets of instructions, workflows, or domain knowledge that teach the agent <em>how</em> to think and behave. They are declarative and loaded into the LLM’s prompt.</li>
<li><strong>Tools (The “Hands”)</strong>: Deterministic, executable functions (like APIs, DB queries, or MCP server calls) that take action in the world.</li>
</ul>
<h2 id="2-progressive-disclosure"><a class="header" href="#2-progressive-disclosure">2. Progressive Disclosure</a></h2>
<p>To optimize LLM context window usage and prevent token bloat, we use the <strong>Progressive Disclosure</strong> pattern:</p>
<ol>
<li><strong>Agent -> Skills</strong>: An agent is assigned a set of skills. When the agent starts, it only loads the high-level descriptions of its assigned skills into its system prompt.</li>
<li><strong>Skill -> Tools</strong>: Each skill is mapped to one or more tools. When the LLM decides to use a specific skill based on its description, the system dynamically fetches and registers the associated tool definitions (JSON schemas) into the LLM’s context.</li>
</ol>
<h2 id="3-database-schema"><a class="header" href="#3-database-schema">3. Database Schema</a></h2>
<h3 id="31-skills"><a class="header" href="#31-skills">3.1 Skills</a></h3>
<p>Skills define the instructions and logic.</p>
<pre><code class="language-sql">CREATE TABLE skill_t (
host_id UUID NOT NULL,
skill_id UUID NOT NULL,
parent_skill_id UUID,
name VARCHAR(126) NOT NULL,
description VARCHAR(500), -- High-level description for the initial LLM prompt
content_markdown TEXT NOT NULL, -- The detailed instructions/prompts
description_embedding VECTOR(384), -- For semantic lookup/discovery
version VARCHAR(20) DEFAULT '1.0.0',
aggregate_version BIGINT DEFAULT 1 NOT NULL,
active BOOLEAN DEFAULT true,
update_ts TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
update_user VARCHAR(126) DEFAULT SESSION_USER,
PRIMARY KEY(host_id, skill_id),
FOREIGN KEY(host_id, parent_skill_id) REFERENCES skill_t(host_id, skill_id)
);
CREATE INDEX idx_skill_active ON skill_t(active);
CREATE INDEX idx_skill_name ON skill_t(name);
</code></pre>
<h3 id="32-tools"><a class="header" href="#32-tools">3.2 Tools</a></h3>
<p>Tools define the technical execution metadata.</p>
<pre><code class="language-sql">CREATE TABLE tool_t (
host_id UUID NOT NULL,
tool_id UUID NOT NULL,
name VARCHAR(126) NOT NULL,
description TEXT NOT NULL, -- Instructions for LLM on when/how to use this tool
-- Implementation specifics
implementation_type VARCHAR(50), -- 'java', 'mcp_server', 'rest', 'python', 'javascript'
implementation_class VARCHAR(500), -- FQCN if 'java'
mcp_server_name VARCHAR(126), -- MCP server name if 'mcp_server'
api_endpoint VARCHAR(1024), -- URL if 'rest'
api_method VARCHAR(10), -- HTTP Method if 'rest'
script_content TEXT, -- Source code if 'python'/'javascript'
description_embedding VECTOR(384), -- For semantic lookup/discovery
version VARCHAR(20) DEFAULT '1.0.0',
aggregate_version BIGINT DEFAULT 1 NOT NULL,
active BOOLEAN DEFAULT true,
update_ts TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
update_user VARCHAR(126) DEFAULT SESSION_USER,
PRIMARY KEY(host_id, tool_id)
);
CREATE INDEX idx_tool_active ON tool_t(active);
CREATE INDEX idx_tool_name ON tool_t(name);
</code></pre>
<h3 id="33-tool-parameters"><a class="header" href="#33-tool-parameters">3.3 Tool Parameters</a></h3>
<p>Defines the arguments for each tool, mapping directly to JSON Schema used by LangChain4j.</p>
<pre><code class="language-sql">CREATE TABLE tool_param_t (
host_id UUID NOT NULL,
param_id UUID NOT NULL,
tool_id UUID NOT NULL,
name VARCHAR(255) NOT NULL,
param_type VARCHAR(50) NOT NULL, -- 'string', 'number', 'boolean', 'object', 'array'
required BOOLEAN DEFAULT true,
default_value JSONB,
description TEXT, -- Helps LLM understand what value to extract
validation_schema JSONB, -- JSON Schema for complex validation
order_index INTEGER DEFAULT 0,
aggregate_version BIGINT DEFAULT 1 NOT NULL,
active BOOLEAN DEFAULT true,
update_ts TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
update_user VARCHAR(126) DEFAULT SESSION_USER,
PRIMARY KEY(host_id, param_id),
FOREIGN KEY(host_id, tool_id) REFERENCES tool_t(host_id, tool_id) ON DELETE CASCADE
);
</code></pre>
<h3 id="34-mappings-and-dependencies"><a class="header" href="#34-mappings-and-dependencies">3.4 Mappings and Dependencies</a></h3>
<p><strong>Agent to Skill Mapping (<code>agent_skill_t</code>)</strong>
Defines an agent’s capabilities (which skills it possesses).</p>
<pre><code class="language-sql">CREATE TABLE agent_skill_t (
host_id UUID NOT NULL,
agent_def_id UUID NOT NULL,
skill_id UUID NOT NULL,
config JSONB DEFAULT '{}',
priority INTEGER DEFAULT 0,
sequence_id INTEGER DEFAULT 0,
aggregate_version BIGINT DEFAULT 1 NOT NULL,
active BOOLEAN DEFAULT true,
update_ts TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
update_user VARCHAR(126) DEFAULT SESSION_USER,
PRIMARY KEY(host_id, agent_def_id, skill_id),
FOREIGN KEY(host_id, agent_def_id) REFERENCES agent_definition_t(host_id, agent_def_id) ON DELETE CASCADE,
FOREIGN KEY(host_id, skill_id) REFERENCES skill_t(host_id, skill_id) ON DELETE CASCADE
);
CREATE INDEX idx_agent_skill_agent ON agent_skill_t(agent_def_id);
</code></pre>
<p><strong>Skill to Tool Mapping (<code>skill_tool_t</code>)</strong>
Implements the Progressive Disclosure pattern linking tools needed by specific skills.</p>
<pre><code class="language-sql">CREATE TABLE skill_tool_t (
host_id UUID NOT NULL,
skill_id UUID NOT NULL,
tool_id UUID NOT NULL,
config JSONB DEFAULT '{}',
access_level VARCHAR(20) DEFAULT 'read', -- e.g., 'read', 'write', 'execute'
aggregate_version BIGINT DEFAULT 1 NOT NULL,
active BOOLEAN DEFAULT true,
update_ts TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
update_user VARCHAR(126) DEFAULT SESSION_USER,
PRIMARY KEY(host_id, skill_id, tool_id),
FOREIGN KEY(host_id, skill_id) REFERENCES skill_t(host_id, skill_id) ON DELETE CASCADE,
FOREIGN KEY(host_id, tool_id) REFERENCES tool_t(host_id, tool_id) ON DELETE CASCADE
);
CREATE INDEX idx_skill_tool_skill ON skill_tool_t(skill_id);
</code></pre>
<p><strong>Skill Dependencies (<code>skill_dependency_t</code>)</strong>
Manages hierarchies where one skill requires another.</p>
<pre><code class="language-sql">CREATE TABLE skill_dependency_t (
host_id UUID NOT NULL,
skill_id UUID NOT NULL,
depends_on_skill_id UUID NOT NULL,
required BOOLEAN DEFAULT true,
aggregate_version BIGINT DEFAULT 1 NOT NULL,
active BOOLEAN DEFAULT true,
update_ts TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
update_user VARCHAR(126) DEFAULT SESSION_USER,
PRIMARY KEY (host_id, skill_id, depends_on_skill_id),
FOREIGN KEY(host_id, skill_id) REFERENCES skill_t(host_id, skill_id),
FOREIGN KEY(host_id, depends_on_skill_id) REFERENCES skill_t(host_id, skill_id)
);
</code></pre>
<h2 id="4-implementation-types"><a class="header" href="#4-implementation-types">4. Implementation Types</a></h2>
<p>The <code>tool_t</code> table supports various <code>implementation_type</code> values to determine how a tool is physically executed:</p>
<ul>
<li><strong><code>java</code></strong>: Local Java class execution mapping to <code>@Tool</code> methods (Fastest, Primary).</li>
<li><strong><code>mcp_server</code></strong>: Connect to an external Model Context Protocol server (Standard for 3rd party tools).</li>
<li><strong><code>rest</code></strong>: Direct HTTP/REST API calls.</li>
<li><strong><code>python</code>/<code>javascript</code></strong>: Dynamic script execution.</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="event-driven-agent-architecture"><a class="header" href="#event-driven-agent-architecture">Event-Driven Agent Architecture</a></h1>
<h2 id="overview-2"><a class="header" href="#overview-2">Overview</a></h2>
<p>This document details the <strong>Event-Driven Architecture (EDA)</strong> for the <code>light-genai-4j</code> agent system. This architecture decouples agent invocation from execution, enabling high scalability, resilience, and asynchronous processing suitable for enterprise workloads.</p>
<h2 id="1-core-architecture"><a class="header" href="#1-core-architecture">1. Core Architecture</a></h2>
<p>While SQL defines <em>what</em> a skill is (see <a href="design/light-genai-4j/agent-skill.html">Agent Skill Design</a>), the implementation for enterprise usage leverages an <strong>Event-Driven Architecture (EDA)</strong>. This decouples the agent requesting the skill (the “invoker”) from the agent or service executing the skill (the “worker”).</p>
<h3 id="11-core-components"><a class="header" href="#11-core-components">1.1 Core Components</a></h3>
<ol>
<li><strong>Invoker Agent</strong>: The agent that decides to call a tool/skill.</li>
<li><strong>A2A Service (<code>genai-agentic-kafka</code>)</strong>: The bridge between the synchronous <code>AgentExecutor</code> and the asynchronous message bus.</li>
<li><strong>Topic Topology</strong>:
<ul>
<li><code>agent-commands</code>: Topics where agents publish intent/skill execution requests.</li>
<li><code>agent-events</code>: Topics where agents/workers publish completion events.</li>
</ul>
</li>
</ol>
<h3 id="12-execution-flow"><a class="header" href="#12-execution-flow">1.2 Execution Flow</a></h3>
<ol>
<li><strong>LLM Decision</strong>: The LLM outputs a <code>ToolExecutionRequest</code>.</li>
<li><strong>Interception</strong>: The <code>AgentExecutor</code>’s <code>A2AService</code> implementation intercepts this request.</li>
<li><strong>Command Emission</strong>:
<ul>
<li>Instead of executing a Java method directly, it constructs a <code>SkillInvocationEvent</code> containing:
<ul>
<li><code>correlationId</code>: Unique ID for this interaction.</li>
<li><code>skillName</code>: Name of the skill to execute.</li>
<li><code>arguments</code>: JSON payload of arguments.</li>
<li><code>replyTo</code>: Topic to send the result to.</li>
</ul>
</li>
<li>This event is published to the <code>agent-commands</code> topic.</li>
</ul>
</li>
<li><strong>Async Wait</strong>: The <code>AgentExecutor</code> returns an <code>AsyncResponse</code> (a <code>CompletableFuture</code>) and suspends the agent’s execution thread (virtually, if using Virtual Threads).</li>
<li><strong>Worker Execution</strong>:
<ul>
<li>A subscribed “Skill Worker” (which could be another Generic Agent or a dedicated microservice) picks up the event.</li>
<li>It executes the logic (DB query, API call, calculation).</li>
</ul>
</li>
<li><strong>Response Emission</strong>:
<ul>
<li>The worker publishes a <code>SkillCompletionEvent</code> to the <code>replyTo</code> topic.</li>
<li>Payload includes <code>correlationId</code> and the result/error.</li>
</ul>
</li>
<li><strong>Resumption</strong>:
<ul>
<li>The original <code>A2AService</code> consumes the completion event.</li>
<li>It matches the <code>correlationId</code> and completes the pending <code>CompletableFuture</code>.</li>
<li>The Agent resumes generation with the tool output.</li>
</ul>
</li>
</ol>
<h3 id="13-benefits"><a class="header" href="#13-benefits">1.3 Benefits</a></h3>
<ul>
<li><strong>Scalability</strong>: Heavy skills (e.g., “Generate Report”) don’t block the lightweight Agent Commander.</li>
<li><strong>Resilience</strong>: If the Worker is down, the command persists in Kafka.</li>
<li><strong>Decoupling</strong>: Agents don’t need to know the network location of skills.</li>
</ul>
<h2 id="2-relationship-with-mcp-model-context-protocol"><a class="header" href="#2-relationship-with-mcp-model-context-protocol">2. Relationship with MCP (Model Context Protocol)</a></h2>
<p>With this design, the agent system <strong>does not require</strong> an MCP server architecture. The <code>skills</code> table allows direct invocation of any capability (Java code, REST APIs, GraphQL, scripts) without the overhead or complexity of the MCP protocol.</p>
<h3 id="21-comparison"><a class="header" href="#21-comparison">2.1 Comparison</a></h3>
<div class="table-wrapper">
<table>
<thead>
<tr><th>Feature</th><th>Light GenAI 4j Design</th><th>MCP Server Architecture</th></tr>
</thead>
<tbody>
<tr><td><strong>Execution</strong></td><td>In-process (Java) or <strong>Event-Driven</strong></td><td>Networked JSON-RPC</td></tr>
<tr><td><strong>Latency</strong></td><td>Near-zero (local) / Async (EDA)</td><td>HTTP/Network round-trip</td></tr>
<tr><td><strong>Control</strong></td><td>Full SQL schema & validation</td><td>Remote server definition</td></tr>
<tr><td><strong>Complexity</strong></td><td>Low (Unified DB/Kafka)</td><td>High (Separate servers/processes)</td></tr>
<tr><td><strong>Ecosystem</strong></td><td>Custom integrations</td><td>Community-maintained tools</td></tr>
</tbody>
</table>
</div>
<h2 id="3-implementation-guidelines"><a class="header" href="#3-implementation-guidelines">3. Implementation Guidelines</a></h2>
<h3 id="31-dependencies"><a class="header" href="#31-dependencies">3.1 Dependencies</a></h3>
<pre><code class="language-xml"><!-- pom.xml -->
<dependency>
<groupId>com.networknt</groupId>
<artifactId>genai-agentic-kafka</artifactId> <!-- Future Module -->
<version>${project.version}</version>
</dependency>
</code></pre>
<h3 id="32-design-principles"><a class="header" href="#32-design-principles">3.2 Design Principles</a></h3>
<ol>
<li><strong>Asynchrony</strong>: Default to async/event-driven for any I/O heavy skill.</li>
<li><strong>Correlation</strong>: Use <code>correlationId</code> rigorously to track request/response pairs across the bus.</li>
<li><strong>Idempotency</strong>: Workers should handle duplicate events gracefully.</li>
</ol>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="light-hybrid-4j"><a class="header" href="#light-hybrid-4j">light-hybrid-4j</a></h1>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="json-rpc-20-migration-for-light-hybrid-4j"><a class="header" href="#json-rpc-20-migration-for-light-hybrid-4j">JSON-RPC 2.0 Migration for light-hybrid-4j</a></h1>
<h2 id="1-introduction"><a class="header" href="#1-introduction">1. Introduction</a></h2>
<p>The <code>light-hybrid-4j</code> framework is the backbone of the <code>light-portal</code>, acting as a highly efficient, modularized monolithic architecture. Currently, it relies on a bespoke JSON structure containing a 4-tuple (<code>host</code>, <code>service</code>, <code>action</code>, <code>version</code>) alongside the domain <code>data</code>.</p>
<p>With the introduction of the <strong>Model Context Protocol (MCP)</strong> as a first-class citizen in the <code>light-gateway</code> ecosystem, the need for a standardized RPC format has become critical. MCP relies entirely on <strong>JSON-RPC 2.0</strong>.</p>
<p>This document outlines the architectural design and migration strategy for adapting <code>light-hybrid-4j</code> to natively support the JSON-RPC 2.0 standard.</p>
<h2 id="2-benefits-and-motivations"><a class="header" href="#2-benefits-and-motivations">2. Benefits and Motivations</a></h2>
<h3 id="21-native-mcp-integration"><a class="header" href="#21-native-mcp-integration">2.1 Native MCP Integration</a></h3>
<p>By standardizing <code>light-hybrid-4j</code> to JSON-RPC 2.0, every single command and query service instantly becomes a native MCP tool. The <code>light-gateway</code> can route traffic without requiring any expensive payload translation layer. AI Agents can directly call our backend microservices out-of-the-box.</p>
<h3 id="22-immediate-ecosystem-compatibility"><a class="header" href="#22-immediate-ecosystem-compatibility">2.2 Immediate Ecosystem Compatibility</a></h3>
<p>The custom payload format forces third-party developers (and internal UI components) to format their requests manually. JSON-RPC 2.0 is an industry staple with massive ecosystem support (SDKs, Postman, test runners).</p>
<h3 id="23-batch-processing"><a class="header" href="#23-batch-processing">2.3 Batch Processing</a></h3>
<p>JSON-RPC 2.0 native batch capabilities allow the <code>portal-view</code> UI to aggregate multiple independent queries into a single HTTP request packet, vastly reducing network overhead and HTTP/2 connection pooling complexity.</p>
<h3 id="24-separation-of-concerns"><a class="header" href="#24-separation-of-concerns">2.4 Separation of Concerns</a></h3>
<p>The current payload mixes routing topology (<code>host</code>, <code>service</code>, <code>action</code>, <code>version</code>) and UI metadata (<code>success</code>, <code>failure</code>, <code>title</code>) with actual domain data (<code>data</code>). JSON-RPC forces a clean boundary: routing is handled entirely by the <code>method</code>, while domain data is strictly isolated to the <code>params</code> object.</p>
<h2 id="3-architecture-design"><a class="header" href="#3-architecture-design">3. Architecture Design</a></h2>
<h3 id="31-mapping-to-json-rpc-20"><a class="header" href="#31-mapping-to-json-rpc-20">3.1 Mapping to JSON-RPC 2.0</a></h3>
<p>The legacy <code>light-hybrid-4j</code> request looks like this:</p>
<pre><code class="language-json">{
"host": "lightapi.net",
"service": "service",
"action": "createApiVersion",
"version": "0.1.0",
"title": "Create Api Version",
"success": "/app/success",
"failure": "/app/failure",
"data": {
"apiId": "MCP0001",
"hostId": "01964b05-552a-7c4b-9184-6857e7f3dc5f"
}
}
</code></pre>
<p>This will be mapped to the standard JSON-RPC 2.0 format:</p>
<pre><code class="language-json">{
"jsonrpc": "2.0",
"method": "lightapi.net/service/createApiVersion/0.1.0",
"params": {
"apiId": "MCP0001",
"hostId": "01964b05-552a-7c4b-9184-6857e7f3dc5f"
},
"id": 1
}
</code></pre>
<ul>
<li><strong><code>jsonrpc</code></strong>: Must be exactly <code>"2.0"</code>.</li>
<li><strong><code>method</code></strong>: A string constructed by joining the legacy 4-tuple with forward slashes: <code>{host}/{service}/{action}/{version}</code>. This perfectly maps to the internal handler ID used by <code>RpcStartupHookProvider</code>.</li>
<li><strong><code>params</code></strong>: The exact contents of the legacy <code>data</code> block.</li>
<li><strong><code>id</code></strong>: A unique identifier for the request, enabling accurate matching of asynchronous responses and batch processing.</li>
</ul>
<h3 id="32-server-side-changes-light-hybrid-4j"><a class="header" href="#32-server-side-changes-light-hybrid-4j">3.2 Server-Side Changes (<code>light-hybrid-4j</code>)</a></h3>
<ol>
<li>
<p><strong>Dual-Protocol Router (<code>SchemaHandler</code> & <code>JsonHandler</code>)</strong>:
The router must gracefully support both legacy and JSON-RPC payloads during the transition.</p>
<ul>
<li><strong>Detection</strong>: Inspect the root keys of the incoming JSON. If <code>"jsonrpc": "2.0"</code> is present, invoke the new JSON-RPC 2.0 parser route. Otherwise, fall back to the legacy parser.</li>
<li><strong>Extraction</strong>:
<ul>
<li>Legacy: Extract <code>host</code>, <code>service</code>, <code>action</code>, <code>version</code> to resolve the Handler.</li>
<li>JSON-RPC: Split the string in the <code>method</code> parameter <code>host/service/action/version</code> to resolve the Handler.</li>
</ul>
</li>
</ul>
</li>
<li>
<p><strong>Response Construction</strong>:
If the request included an <code>"id"</code> parameter, the response <em>must</em> also be formatted as a JSON-RPC 2.0 response:</p>
<ul>
<li><strong>Success</strong>:
<pre><code class="language-json">{
"jsonrpc": "2.0",
"result": { ... handler payload ... },
"id": 1
}
</code></pre>
</li>
<li><strong>Error</strong>:
<pre><code class="language-json">{
"jsonrpc": "2.0",
"error": {
"code": -32600,
"message": "Invalid Request",
"data": { ... custom light-4j status object ... }
},
"id": 1
}
</code></pre>
</li>
</ul>
</li>
<li>
<p><strong>Batch Request Handling</strong>:
If the incoming request body is a JSON Array instead of a JSON Object, the gateway must process it as a batch request, iterating over each JSON-RPC object, executing them, and returning a JSON Array of responses.</p>
</li>
</ol>
<h2 id="4-client-side-changes-portal-view-spa"><a class="header" href="#4-client-side-changes-portal-view-spa">4. Client-Side Changes (<code>portal-view</code> SPA)</a></h2>
<p>The <code>portal-view</code> currently utilizes a <code>fetchClient</code> utility built around the legacy structure.</p>
<ol>
<li><strong>Update <code>fetchClient</code></strong>: Modify the core fetch utility to optionally format outbound requests as JSON-RPC 2.0 when an opt-in toggle is set, or permanently switch the underlying transport format.</li>
<li><strong>Schema Forms</strong>: Update <code>react-schema-form</code> components (or the server-side definitions in <code>Forms.json</code>) to stop injecting UI routing metadata (<code>success</code>, <code>failure</code>, <code>title</code>) into the network payload. These should remain strictly client-side configuration properties.</li>
</ol>
<h2 id="5-migration-strategy"><a class="header" href="#5-migration-strategy">5. Migration Strategy</a></h2>
<ol>
<li>
<p><strong>Phase 1: Backend Dual-Support</strong></p>
<ul>
<li>Update <code>light-hybrid-4j</code> router components (<code>SchemaHandler</code>, <code>JsonHandler</code>) to detect and accept BOTH legacy and JSON-RPC 2.0 formats simultaneously.</li>
<li>Deploy the updated framework across all <code>light-portal</code> microservices (Command and Query nodes).</li>
<li><em>Result: Backend is ready, no client changes required yet.</em></li>
</ul>
</li>
<li>
<p><strong>Phase 2: Gateway MCP Routing</strong></p>
<ul>
<li>Implement MCP HTTP transport logic on the <code>light-gateway</code> to expose the backend tools list.</li>
<li>When an MCP client lists tools, the gateway reads the hybrid service schemas and publishes them.</li>
<li>When an MCP client invokes a tool, the gateway proxies the JSON-RPC request transparently to the backend.</li>
</ul>
</li>
<li>
<p><strong>Phase 3: Frontend Migration</strong></p>
<ul>
<li>Update the <code>portal-view</code> UI to use the new JSON-RPC 2.0 wrapper in <code>fetchClient</code>.</li>
<li>Refactor legacy components sending hardcoded <code>host/service/action</code> structures.</li>
</ul>
</li>
<li>
<p><strong>Phase 4: Deprecation (Long Term)</strong></p>
<ul>
<li>Add warnings to the logs when legacy payloads are received.</li>
<li>Eventually phase out the legacy parser code in <code>light-hybrid-4j</code> and rely solely on the JSON-RPC 2.0 standard.</li>
</ul>
</li>
</ol>
<div style="break-before: page; page-break-before: always;"></div>
<h1 id="mcp-router"><a class="header" href="#mcp-router">MCP Router</a></h1>
<p>Implementing an <strong>MCP (Model Context Protocol) Router</strong> inside <strong>light-4j</strong> gateway is a <strong>visionary and highly strategic idea</strong>.</p>
<p>The industry is currently struggling with “Tool Sprawl”—where every microservice needs to be manually taught to an LLM. By placing an MCP Router at the gateway level, we effectively turn our entire microservice ecosystem into a <strong>single, searchable library of capabilities</strong> for AI agents.</p>
<p>Here is a breakdown of why this is a good idea and how to design it for the light-4j ecosystem.</p>
<hr>
<h3 id="1-why-it-is-a-strategic-win"><a class="header" href="#1-why-it-is-a-strategic-win">1. Why it is a Strategic Win</a></h3>
<ul>
<li><strong>Discovery at Scale:</strong> Instead of configuring 50 tools for an agent, the agent connects to our gateway via MCP. The gateway then “advertises” the available tools based on the services it already knows.</li>
<li><strong>Protocol Translation:</strong> Our backend services don’t need to know what MCP is. The gateway handles the conversion from <strong>MCP (JSON-RPC over SSE/HTTP)</strong> to <strong>REST (OpenAPI)</strong> or <strong>GraphQL</strong>.</li>
<li><strong>Security & Governance:</strong> We can apply light-4j’s existing JWT validation, rate limiting, and audit logging to AI interactions. We control which agents have access to which “tools” (APIs).</li>
<li><strong>Schema Re-use:</strong> We already have OpenAPI specs or GraphQL schemas in light-4j. We can dynamically generate the MCP “Tool Definitions” from these existing schemas.</li>
</ul>
<hr>
<h3 id="2-design-considerations"><a class="header" href="#2-design-considerations">2. Design Considerations</a></h3>
<h4 id="a-the-transport-layer"><a class="header" href="#a-the-transport-layer">A. The Transport Layer</a></h4>
<p>MCP supports two primary transports: <strong>Stdio</strong> (for local scripts) and <strong>HTTP with SSE (Server-Sent Events)</strong> (for remote services).</p>
<ul>
<li><strong>Decision:</strong> For a gateway, we <strong>must use the HTTP + SSE transport</strong>.</li>
<li><strong>Implementation:</strong> Light-4j is built on Undertow, which has excellent support for SSE. We will need to implement an MCP endpoint (e.g., <code>/mcp/message</code>) and an SSE endpoint (e.g., <code>/mcp/sse</code>).</li>
</ul>
<h4 id="b-tool-discovery--dynamic-mapping"><a class="header" href="#b-tool-discovery--dynamic-mapping">B. Tool Discovery & Dynamic Mapping</a></h4>
<p>How does the Gateway decide which APIs to expose as MCP Tools?</p>
<ul>
<li><strong>Metadata Driven:</strong> Use light-4j configuration or annotations in the OpenAPI files to mark specific endpoints as “AI-enabled.”</li>
<li><strong>The Mapper:</strong> Create a component that converts an <strong>OpenAPI Operation</strong> into an <strong>MCP Tool Definition</strong>.
<ul>
<li><code>description</code> in OpenAPI becomes the tool’s <code>description</code> (crucial for LLM reasoning).</li>
<li><code>requestBody</code> schema becomes the tool’s <code>inputSchema</code>.</li>
</ul>
</li>
</ul>
<h4 id="c-authentication--context-pass-through"><a class="header" href="#c-authentication--context-pass-through">C. Authentication & Context Pass-through</a></h4>
<p>This is the hardest part.</p>
<ul>
<li><strong>The Problem:</strong> The LLM agent connects to the Gateway, but the Backend Microservice needs a user-specific JWT.</li>
<li><strong>The Solution:</strong> The MCP Router must be able to take the identity from the MCP connection (initial handshake) and either pass it through or exchange it for a backend token (OAuth2 Token Exchange).</li>
</ul>
<h4 id="d-statefulness-vs-statelessness"><a class="header" href="#d-statefulness-vs-statelessness">D. Statefulness vs. Statelessness</a></h4>
<p>MCP is often stateful (sessions).</p>
<ul>
<li><strong>Implementation:</strong> Since light-4j is designed for high performance and statelessness, we may need light-session-4j a small <strong>Session Manager</strong> (potentially backed by Redis or PostgresQL) to keep track of which MCP Client is mapped to which internal context during the SSE connection.</li>
</ul>
<hr>
<h3 id="3-implementation-plan-for-light-4j"><a class="header" href="#3-implementation-plan-for-light-4j">3. Implementation Plan for light-4j</a></h3>
<h4 id="step-1-create-the-mcphandler"><a class="header" href="#step-1-create-the-mcphandler">Step 1: Create the <code>McpHandler</code></a></h4>
<p>Create a new middleware handler in light-4j that intercepts calls to <code>/mcp</code>.</p>
<ul>
<li>This handler must implement the MCP lifecycle: <code>initialize</code> -> <code>list_tools</code> -> <code>call_tool</code>.</li>
</ul>
<h4 id="step-2-tool-registry"><a class="header" href="#step-2-tool-registry">Step 2: Tool Registry</a></h4>
<p>Implement a registry that scans our gateway’s internal routing table.</p>
<ul>
<li><strong>REST:</strong> For every path (e.g., <code>GET /customers/{id}</code>), generate an MCP tool named <code>get_customers_by_id</code>.</li>
<li><strong>GraphQL:</strong> For every Query/Mutation, generate a corresponding MCP tool.</li>
</ul>
<h4 id="step-3-json-rpc-over-sse"><a class="header" href="#step-3-json-rpc-over-sse">Step 3: JSON-RPC over SSE</a></h4>
<p>MCP uses JSON-RPC 2.0. We will need a simple parser that:</p>
<ol>
<li>Receives an MCP <code>call_tool</code> request.</li>