-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
1474 lines (1255 loc) · 51.2 KB
/
index.html
File metadata and controls
1474 lines (1255 loc) · 51.2 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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Building Personalised Local Agents with LangGraph & Ollama</title>
<style>
:root {
/* Light Mode (Premium Apple-style) */
--bg-color: #ffffff;
--text-color: #1d1d1f;
--secondary-bg: #f5f5f7;
--border-color: #d2d2d7;
--accent-color: #51247A;
/* UQ Purple */
--accent-hover: #3f1b5e;
--accent-gradient: linear-gradient(135deg, #51247A 0%, #9650d6 100%);
--code-bg: #f5f5f7;
--code-text: #1d1d1f;
--card-bg: rgba(255, 255, 255, 0.8);
--shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
--glass-border: 1px solid rgba(255, 255, 255, 0.3);
}
[data-theme="dark"] {
/* Dark Mode (Deep & Elegant) */
--bg-color: #000000;
--text-color: #f5f5f7;
--secondary-bg: #1c1c1e;
--border-color: #3a3a3c;
--accent-color: #9650d6;
/* Light Purple */
--accent-hover: #b074e6;
--accent-gradient: linear-gradient(135deg, #6a359c 0%, #b074e6 100%);
--code-bg: #1c1c1e;
--code-text: #f5f5f7;
--card-bg: rgba(28, 28, 30, 0.6);
--shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
--glass-border: 1px solid rgba(255, 255, 255, 0.1);
}
* {
box-sizing: border-box;
scroll-behavior: smooth;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
margin: 0;
padding: 0;
line-height: 1.6;
transition: background-color 0.4s, color 0.4s;
overflow-x: hidden;
}
/* Particles / Hero Section */
#hero {
position: relative;
height: 65vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
overflow: hidden;
background: radial-gradient(circle at 50% 50%, rgba(81, 36, 122, 0.1), transparent 70%);
}
#particles-js {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: -1;
}
.hero-content {
z-index: 10;
padding: 2rem;
max-width: 800px;
animation: fadeInUp 1s ease-out;
}
h1 {
font-weight: 800;
font-size: 3.5rem;
letter-spacing: -0.02em;
margin-bottom: 1rem;
background: var(--accent-gradient);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
line-height: 1.1;
}
.hero-subtitle {
font-size: 1.5rem;
color: var(--text-color);
opacity: 0.8;
font-weight: 400;
margin-bottom: 2rem;
}
.scroll-down {
position: absolute;
bottom: 40px;
left: 50%;
transform: translateX(-50%);
animation: bounce 2s infinite;
cursor: pointer;
opacity: 0.7;
transition: opacity 0.3s;
}
.scroll-down:hover {
opacity: 1;
}
.scroll-down svg {
width: 30px;
height: 30px;
fill: var(--text-color);
}
/* Glassmorphic Header */
header {
position: fixed;
top: 0;
width: 100%;
padding: 1rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
z-index: 1000;
background: rgba(255, 255, 255, 0.05);
/* Very subtle tint */
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
border-bottom: var(--glass-border);
transition: background 0.3s;
}
[data-theme="dark"] header {
background: rgba(0, 0, 0, 0.2);
}
.logo {
font-weight: 700;
font-size: 1.2rem;
color: var(--text-color);
display: flex;
align-items: center;
gap: 10px;
}
/* Sections */
.container {
max-width: 900px;
margin: 0 auto;
padding: 4rem 1.5rem;
}
section {
margin-bottom: 6rem;
opacity: 0;
transform: translateY(30px);
transition: opacity 0.8s ease-out, transform 0.8s ease-out;
}
section.visible {
opacity: 1;
transform: translateY(0);
}
h2 {
font-size: 2.2rem;
font-weight: 700;
margin-bottom: 1.5rem;
letter-spacing: -0.01em;
}
h3 {
font-size: 1.5rem;
font-weight: 600;
margin-top: 2.5rem;
margin-bottom: 1rem;
display: flex;
align-items: center;
gap: 10px;
}
p,
li {
font-size: 1.1rem;
color: var(--text-color);
opacity: 0.9;
margin-bottom: 1.2rem;
}
/* Cards & Info Blocks */
.info-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
margin: 2rem 0;
}
@media (max-width: 768px) {
.info-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 900px) {
.resources-grid {
grid-template-columns: repeat(2, 1fr) !important;
}
}
@media (max-width: 480px) {
.resources-grid {
grid-template-columns: 1fr !important;
}
}
.resources-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1.5rem;
margin: 3rem auto;
/* Add more vertical spacing */
max-width: 1000px;
/* Force it narrower */
padding: 0 1rem;
}
.resources-grid a {
display: block;
height: 100%;
}
.card {
background: var(--card-bg);
border-radius: 18px;
padding: 2rem;
box-shadow: var(--shadow);
border: var(--glass-border);
backdrop-filter: blur(10px);
transition: transform 0.3s;
}
.card:hover {
transform: translateY(-5px);
}
.card-icon {
font-size: 2rem;
margin-bottom: 1rem;
display: block;
}
/* Tabs (Apple Style) */
.tabs-container {
background: var(--secondary-bg);
border-radius: 12px;
padding: 4px;
display: inline-flex;
margin-bottom: 2rem;
border: 1px solid var(--border-color);
}
.tab {
padding: 8px 24px;
border-radius: 9px;
border: none;
background: transparent;
cursor: pointer;
font-size: 0.95rem;
font-weight: 500;
color: var(--text-color);
opacity: 0.7;
transition: all 0.2s;
display: flex;
align-items: center;
gap: 8px;
}
.tab svg {
width: 16px;
height: 16px;
fill: currentColor;
}
.tab.active {
background: var(--bg-color);
color: var(--text-color);
opacity: 1;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.tab-content {
display: none;
margin-top: 1rem;
}
.tab-content.active {
display: block;
animation: fadeIn 0.3s;
}
/* Code Blocks */
pre {
background: var(--code-bg);
padding: 1.5rem;
border-radius: 14px;
overflow-x: auto;
border: 1px solid var(--border-color);
position: relative;
margin: 1.5rem 0;
}
code {
font-family: "SF Mono", Monaco, Consolas, monospace;
font-size: 0.9rem;
color: var(--code-text);
}
.copy-btn {
position: absolute;
top: 12px;
right: 12px;
background: var(--bg-color);
border: 1px solid var(--border-color);
color: var(--text-color);
padding: 6px 12px;
border-radius: 8px;
font-size: 0.75rem;
cursor: pointer;
opacity: 0.7;
transition: all 0.2s;
}
.copy-btn:hover {
opacity: 1;
background: var(--secondary-bg);
}
/* Terminals */
.terminal {
background: #1e1e1e;
color: #d4d4d4;
padding: 1.5rem;
border-radius: 10px;
font-family: "SF Mono", monospace;
margin: 1rem 0;
border: 1px solid #333;
position: relative;
}
.terminal code {
color: #f5f5f7;
}
.terminal-header {
display: flex;
gap: 6px;
margin-bottom: 12px;
}
.dot {
width: 10px;
height: 10px;
border-radius: 50%;
}
.red {
background: #ff5f56;
}
.yellow {
background: #ffbd2e;
}
.green {
background: #27c93f;
}
/* Theme Toggle */
.theme-toggle {
background: var(--secondary-bg);
border: none;
cursor: pointer;
padding: 10px;
border-radius: 50%;
font-size: 1.2rem;
transition: transform 0.3s;
display: flex;
align-items: center;
justify-content: center;
}
.theme-toggle:hover {
transform: rotate(15deg);
}
/* Animations */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(40px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes bounce {
0%,
20%,
50%,
80%,
100% {
transform: translate(-50%, 0);
}
40% {
transform: translate(-50%, -10px);
}
60% {
transform: translate(-50%, -5px);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* Full Code Toggle */
details {
margin-top: 4rem;
background: var(--card-bg);
border: var(--glass-border);
border-radius: 16px;
padding: 0;
overflow: hidden;
box-shadow: var(--shadow);
transition: all 0.3s;
}
summary {
padding: 1.5rem;
cursor: pointer;
font-weight: 600;
list-style: none;
display: flex;
justify-content: space-between;
align-items: center;
background: rgba(81, 36, 122, 0.05);
transition: background 0.2s;
}
summary:hover {
background: rgba(81, 36, 122, 0.1);
}
summary::-webkit-details-marker {
display: none;
}
summary:after {
content: '+';
font-size: 1.5rem;
font-weight: 300;
transition: transform 0.3s;
}
details[open] summary:after {
transform: rotate(45deg);
}
.code-wrapper {
padding: 0 1.5rem 1.5rem;
max-height: 500px;
overflow-y: auto;
transition: max-height 0.5s ease;
}
details[open] .code-wrapper {
max-height: 800px;
}
@media (max-width: 768px) {
#hero {
padding-top: 80px;
height: auto;
min-height: 65vh;
justify-content: flex-start;
}
h1 {
font-size: 2.5rem;
}
}
</style>
<!-- FontAwesome for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Particles.js -->
<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
</head>
<body>
<header>
<div class="logo">
<i class="fa-solid fa-robot" style="color: var(--accent-color);"></i>
<span>INFS4205/7205</span>
</div>
<button class="theme-toggle" id="theme-toggle" aria-label="Toggle Dark Mode">
<i class="fa-solid fa-moon"></i>
</button>
</header>
<div id="hero">
<div id="particles-js"></div>
<div class="hero-content">
<h1>Personalised Intelligent Agents on Your Machine</h1>
<p class="hero-subtitle">Build your own personalised local agent with LangGraph & Ollama.</p>
<a href="#setup" class="scroll-down" aria-label="Scroll Down">
<svg viewBox="0 0 24 24">
<path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z" />
</svg>
</a>
</div>
</div>
<div class="container">
<section id="concepts">
<h2>Tech Stack</h2>
<div class="info-grid">
<div class="card">
<span class="card-icon">🕸️</span>
<h3><a href="https://langchain-ai.github.io/langgraph/" target="_blank"
style="text-decoration: none; color: inherit;">LangGraph</a> <i
class="fa-solid fa-arrow-up-right-from-square"
style="font-size: 0.8rem; opacity: 0.5; margin-left: 5px;"></i></h3>
<p>A library for building stateful, multi-actor applications with LLMs. Unlike simple chains,
LangGraph allows for <strong>cycles</strong>, enabling agents to loop, reason, and correct
themselves until a task is complete.</p>
</div>
<div class="card">
<span class="card-icon">🦙</span>
<h3><a href="https://ollama.com/" target="_blank"
style="text-decoration: none; color: inherit;">Ollama</a> <i
class="fa-solid fa-arrow-up-right-from-square"
style="font-size: 0.8rem; opacity: 0.5; margin-left: 5px;"></i></h3>
<p>The easiest way to get up and running with large language models locally. It bundles model
weights, configuration, and data into a single package, defined by a Modelfile.</p>
</div>
</div>
</section>
<section id="setup">
<h2>Environment & Model Setup</h2>
<h3>1. Project Environment</h3>
<p>Open your terminal and run the following commands. We recommend using <code>uv</code> for lightning-fast
Python package management. Otherwise, you can
download <a href="https://www.python.org/downloads/" target="_blank"
style="color: var(--accent-color);">Python</a> manually install the required packages.</p>
<div class="tabs-container">
<button class="tab active" data-group="env" onclick="openTab('mac')"><i class="fab fa-apple"></i> macOS
/ Linux</button>
<button class="tab" data-group="env" onclick="openTab('win')"><i class="fab fa-windows"></i>
Windows</button>
</div>
<div id="mac" class="tab-content active" data-group="env">
<div class="terminal">
<div class="terminal-header">
<div class="dot red"></div>
<div class="dot yellow"></div>
<div class="dot green"></div>
</div>
<code>
# Install uv<br>
curl -LsSf https://astral.sh/uv/install.sh | sh<br><br>
# (Optional) If pip is available:<br>
# pip install uv
<br><br>
# Create & activate environment<br>
uv venv<br>
source .venv/bin/activate<br><br>
# Install dependencies<br>
uv pip install langchain-ollama langgraph langchain-core chromadb sentence-transformers pillow
</code>
<button class="copy-btn" onclick="copyCode(this)">Copy</button>
</div>
</div>
<div id="win" class="tab-content" data-group="env">
<div class="terminal">
<div class="terminal-header">
<div class="dot red"></div>
<div class="dot yellow"></div>
<div class="dot green"></div>
</div>
<code>
# Install uv (PowerShell)<br>
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"<br><br>
# (Optional) If pip is available:<br>
# pip install uv
<br><br>
# Create & activate environment<br>
uv venv<br>
.venv\Scripts\activate<br><br>
# Install dependencies<br>
uv pip install langchain-ollama langgraph langchain-core chromadb sentence-transformers pillow
</code>
<button class="copy-btn" onclick="copyCode(this)">Copy</button>
</div>
</div>
<h3>2. Get Ollama Ready</h3>
<p>First, download Ollama from <a href="https://ollama.com/download" target="_blank"
style="color: var(--accent-color);">ollama.com</a>. Once installed, open a <strong>new
terminal</strong> to pull the
model we'll use (<a href="https://ollama.com/library/qwen3/tags" target="_blank"
style="color: var(--accent-color);">Qwen3 0.6B</a> for speed). More models can be found at <a
href="https://ollama.com/search" target="_blank" style="color: var(--accent-color);">ollama
models</a>.
</p>
<div class="terminal">
<div class="terminal-header">
<div class="dot red"></div>
<div class="dot yellow"></div>
<div class="dot green"></div>
</div>
<code>
# Pull a small, capable model<br>
ollama pull qwen3:0.6b-q4_K_M<br><br>
# Start the server (if not running)<br>
ollama serve
</code>
<button class="copy-btn" onclick="copyCode(this)">Copy</button>
</div>
</section>
<section id="walkthrough">
<h2>Building the Agent - Minimal Demo</h2>
<p>We will construct a minimal agent using LangGraph and a local Ollama model (Qwen3 0.6B) that can answer
questions using an external course dataset, solve simple
arithmetic problems with the help of a calculator function, and save notes to your disk. In the
following sections, we will break down the core logic of the agent step by step.</p>
<h3>1. Basic Tools</h3>
<p>Before giving the agent a brain, we give it hands. Tools are simple Python functions decorated with
<code>@tool</code>. The docstring is crucial, it tells the LLM <em>when</em> and <em>how</em> to use the
tool.
</p>
<pre><code class="language-python">@tool
def calc(expression: str) -> str:
"""Evaluate a simple arithmetic expression."""
# ... logic to eval safely ...
result = eval(expression, {"__builtins__": {}}, {})
return str(result)
@tool
def write_text(path: str, content: str) -> str:
"""Write text content to a local file."""
# ... logic to write file ...
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return f"Saved to {path}"</code><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button></pre>
<h3>2. Knowledge Retrieval (RAG)</h3>
<p>For domain-specific questions (like university courses), the agent needs to search some external data.
For demonstration, we load a dummy CSV file as follow, and create a search tool invokes by the agent
based on keywords.</p>
<details id="courses-csv-details" style="margin-top: 1rem; margin-bottom: 2rem;">
<summary>courses.csv</summary>
<div class="code-wrapper">
<pre><code class="language-csv">code,title,description,level
CS101,Introduction to Programming,Learn basic programming concepts using Python,Undergraduate
CS204,Data Structures,Study arrays lists trees and graphs,Undergraduate
CS305,Machine Learning,Supervised and unsupervised learning methods,Undergraduate
CS705,Advanced AI Agents,Design and evaluation of autonomous AI agents,Postgraduate
CS710,Research Methods in AI,Experimental design and evaluation for AI research,Postgraduate</code><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button></pre>
</div>
</details>
<pre><code class="language-python"># Load data once
COURSES = load_courses("courses.csv")
@tool
def search_courses(query: str) -> str:
"""A simple search of the course dataset for relevant entries."""
# ... calculates relevance score for each course ...
# ... returns top matches as a formatted string ...
return results</code><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button></pre>
<h3>3. The Brain (LLM & State)</h3>
<p>At the core of our agent is the <strong>Brain</strong>—a combination of the LLM (Ollama), the System
Prompt (instructions), and the State (memory).</p>
<div style="text-align: center; margin: 2rem 0;">
<img src="agent_flow_diagram.png" alt="Agent Flow Diagram"
style="max-width: 100%; border-radius: 10px; box-shadow: var(--shadow);">
<p style="font-size: 0.9rem; margin-top: 0.5rem; opacity: 0.8;">The cyclic flow of the LangGraph agent.
</p>
</div>
<h4>The System Prompt</h4>
<p>This is where we give the agent its personality and rules. We explicitly tell it which tools to use and
how to behave. This reduces hallucinations and ensures it follows our constraints. An example prompt can
be: </p>
<pre><code class="language-python">SYSTEM_PROMPT = SystemMessage(
content=(
"You are a helpful assistant with access to tools.\n"
"Guidelines:\n"
"- Use search_courses for queries about the curriculum.\n"
"- Use calc for any math.\n"
"- Use write_text to save files."
)
)</code><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button></pre>
<h4>The State</h4>
<p>The <code>AgentState</code> acts as the short-term memory. It stores a list of <code>messages</code> that
grows as the conversation progresses. This allows the model to "remember" previous turns.</p>
<pre><code class="language-python">class AgentState(TypedDict):
messages: List[BaseMessage] # Stores user inputs, agent replies, and tool results
# Bind tools so the model knows they exist
TOOLS = [search_courses, calc, write_text]
llm = ChatOllama(model="qwen3:0.6b-q4_K_M", temperature=0).bind_tools(TOOLS)</code><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button></pre>
<h3>4. The Graph Logic</h3>
<p>We use <strong>LangGraph</strong> to define the workflow. Instead of a linear script, we build a graph
with nodes (actions) and edges (transitions).</p>
<ul>
<li><strong>Agent Node</strong>: The decision maker. It looks at the state and prompts the LLM. The LLM
decides whether to reply directly or call a tool.</li>
<li><strong>Tools Node</strong>: The executor. If the Agent requests a tool call, this node runs the
Python function and returns the output.</li>
<li><strong>Conditional Edge</strong>: The traffic controller. It checks the Agent's output:
<ul>
<li>If <code>tool_calls</code> exist → Go to <strong>Tools</strong>.</li>
<li>If just text → <strong>End</strong> (respond to user).</li>
</ul>
</li>
</ul>
<pre><code class="language-python">graph = StateGraph(AgentState)
graph.add_node("agent", agent_node)
graph.add_node("tools", tool_node)
graph.set_entry_point("agent")
# The Cycle: Agent -> (decides) -> Tools -> (returns) -> Agent
graph.add_conditional_edges(
"agent",
route_after_agent,
{"tools": "tools", END: END}
)
graph.add_edge("tools", "agent") # Important: Loop back to Agent!
app = graph.compile()</code><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button></pre>
<h3>5. Visual Capabilities (CLIP + ChromaDB)</h3>
<p>To give the agent "sight," we use <strong>CLIP</strong> to embed images and <strong>ChromaDB</strong> to
store and search them efficiently. This allows the agent to find images based on their content.</p>
<pre><code class="language-python"># 1. Setup Chroma & CLIP
class ImageIndex:
def __init__(self):
self.client = chromadb.PersistentClient(path="./chroma_db")
self.collection = self.client.get_or_create_collection("local_images")
self.model = SentenceTransformer('clip-ViT-B-32')
# ... embeds images & stores in Chroma ...
# 2. Expose as a Tool
@tool
def search_images(query: str) -> str:
"""Search for images/memes/photos locally using a description."""
# ... queries Chroma collection ...
return results</code><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button></pre>
</section>
<p>The complete code is provided as a reference:</p>
<details id="local-agent-py-details">
<summary>View Complete Source Code: local_agent.py</summary>
<div class="code-wrapper">
<pre><button class="copy-btn" onclick="copyToClipboard(this)">Copy</button><code class="language-python">from typing import TypedDict, List
import csv
import os
import chromadb
from chromadb.config import Settings
from PIL import Image
from sentence_transformers import SentenceTransformer
import uuid
from langchain_ollama import ChatOllama
from langchain.tools import tool
from langchain_core.messages import (
BaseMessage,
HumanMessage,
SystemMessage,
)
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
# =========================
# Agent State
# =========================
class AgentState(TypedDict):
messages: List[BaseMessage]
# =========================
# Dataset
# =========================
def load_courses(path: str = "courses.csv"):
with open(path, newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
COURSES = load_courses()
# =========================
# Tools
# =========================
@tool
def search_courses(query: str) -> str:
"""Search the course dataset for relevant entries."""
query_tokens = query.lower().split()
scored = []
for course in COURSES:
text = " ".join(course.values()).lower()
score = sum(token in text for token in query_tokens)
if score > 0:
scored.append((score, course))
if not scored:
return "No relevant courses found in the dataset."
scored.sort(key=lambda x: x[0], reverse=True)
return "\n".join(
f"{c['code']}: {c['title']} ({c['level']}) - {c['description']}"
for _, c in scored
)
@tool
def calc(expression: str) -> str:
"""Evaluate a simple arithmetic expression."""
allowed = set("0123456789+-*/(). %")
if any(ch not in allowed for ch in expression):
return "Error: invalid characters"
try:
return str(eval(expression, {"__builtins__": {}}, {}))
except Exception as e:
return f"Error: {e}"
@tool
def write_text(path: str, content: str) -> str:
"""Write text content to a local file."""
try:
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return f"Saved {len(content)} characters to {path}"
except Exception as e:
return f"Error: {e}"
# =========================
# Image Indexing (CLIP + ChromaDB)
# =========================
class ImageIndex:
def __init__(self, image_dir: str = "images"):
self.image_dir = image_dir
# Initialize ChromaDB (persistent)
self.client = chromadb.PersistentClient(path="./chroma_db")
self.collection = self.client.get_or_create_collection(
name="local_images",
metadata={"hnsw:space": "cosine"}
)
# Load CLIP model
print("Loading CLIP model...")
self.model = SentenceTransformer('clip-ViT-B-32')
self._index_images()
def _index_images(self):
if not os.path.exists(self.image_dir):
os.makedirs(self.image_dir)
# Get list of images on disk
valid_exts = {".jpg", ".jpeg", ".png", ".webp"}
image_files = [
f for f in os.listdir(self.image_dir)
if os.path.splitext(f)[1].lower() in valid_exts
]
if not image_files:
print(f"No images found in {self.image_dir}")
return
# Check what's already indexed to avoid re-embedding
existing_ids = set(self.collection.get()["ids"])
new_images = []
new_ids = []
new_metadatas = []
print("Checking for new images to index...")
for f in image_files:
file_id = f"img_{f}" # Simple ID scheme
if file_id not in existing_ids:
try:
# Open and validate image
img_path = os.path.join(self.image_dir, f)
image = Image.open(img_path)
new_images.append(image)
new_ids.append(file_id)
new_metadatas.append({"filename": f})
except Exception as e:
print(f"Skipping {f}: {e}")
if new_images:
print(f"Embedding and indexing {len(new_images)} new images...")
embeddings = self.model.encode(new_images, normalize_embeddings=True)
self.collection.add(
embeddings=embeddings.tolist(),
ids=new_ids,
metadatas=new_metadatas
)
print("Indexing complete.")
else:
print("Index is up to date.")
def search(self, query: str, k: int = 3):
# Embed query
query_emb = self.model.encode([query], normalize_embeddings=True)
# Query Chroma
results = self.collection.query(
query_embeddings=query_emb,
n_results=k
)
# Parse results
parsed = []
if results and results['metadatas']:
metas = results['metadatas'][0]
dists = results['distances'][0] # Chroma returns distances by default
for i, meta in enumerate(metas):
parsed.append((meta['filename'], dists[i]))
return parsed
# Initialize global index
image_index = ImageIndex()
@tool
def search_images(query: str) -> str:
"""Search for images/memes/photos locally using a description."""
results = image_index.search(query)
if not results:
return "No relevant images found."
return "\n".join(
f"Top K = 3 Images Found: {filename} (distance: {dist:.2f})"
for filename, dist in results
)
TOOLS = [search_courses, calc, write_text, search_images]