forked from DaveParr/starpilot-presentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpresentation.qmd
1655 lines (1411 loc) · 48.8 KB
/
presentation.qmd
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
---
title: "`starpilot`"
subtitle: "A tool to suggest GitHub repos from your users stars"
format:
revealjs:
theme: "solarized"
mermaid:
format: "png"
theme: "neutral"
editor:
markdown:
wrap: 72
---
```{r label = "setup"}
if (!require(ggplot2)) {
install.packages("ggplot2")
}
```
# Introduction
::: notes
- Hi, I'm Dave, and thanks for coming to see me talk about a recent sideproject.
:::
## Goals for the talk
- Share an AI project I've been working on
- Share some of the design decisions I made to build it
- Share some of the experience I had building it
- Share some of the code I wrote to build it
::: notes
Before we start I'd like to understand more about all of you, as we have a mixture of folks potentially from AIWales and from PyData Cardiff.
:::
## Level Set {auto-animate="true"}
🙌 🙌🏻 🙌🏼 🙌🏽 🙌🏾 🙌🏿 🙌🏿
::: {.incremental data-id="level-set"}
- Retrieval Augmented Generation
- Vector Embedding
- Vector Store
- Vector Similarity
:::
::: notes
- I'm going to assume you know the meaning of terms like 'AI', 'LLM',
'GPT'
- If you don't, hello, welcome, you are in a great place to learn, but
I won't go over them now. Feel free to make a neighbor into friend
and ask them, or get Joe to explain it in his session.
- Can you define these terms?
- I'm not going to put anyone on the spot here, but I'd love to have
people raise their hands if they feel they can define these terms
- This will help me understand the level of knowledge in the room and hopefully
tune the rest of the talk
:::
## Level Set {auto-animate="true"}
::: {data-id="level-set"}
- Retrieval Augmented Generation
- Using a language model supported by a vector store
- Vector Embedding
- Converting text into a list of numbers to represent semantic
meaning
- Vector Store
- Database optimized for storing embedding vectors
- Vector Similarity
- Quantifying the similarity between embedding vectors
:::
::: notes
- So here are the definitions of the terms, keep the hands up if you
got most of them right
- If you knew these terms already, great! This talk is largely about
applying these concepts in code.
- If you didn't, that's also great, because you're in the right place
to learn about them.
:::
## Level Set {auto-animate="true"}
🙌 🙌🏻 🙌🏼 🙌🏽 🙌🏾 🙌🏿 🙌🏿
> Who is comfortable reading `python`?
# The Project
## Goals for an AI project
::: incremental
- As a Data Scientist
- I want to build something novel with AI
- So that I can learn and experiment with the technology
- And maybe make something useful for other people
:::
::: notes
- Apply Retrieval Augmented Generation to a goal I have (and maybe
other people)
- Understand how LangChain (and friends) works through building
something novel
- Experiment in a way that leans into what LLMs + AI are good at
- Semantic meaning
:::
## The Project is `starpilot`
> A tool to suggest GitHub repos from your users stars based on semantic similarity
![](images/563000_The github octocat riding a spaceship through a st_xl-1024-v1-0.png){fig-align="center" height=400}
::: notes
- The project is called `starpilot`
- It's a tool that suggests GitHub repos based on semantic similarity
- The idea is that you can give it a query, and it will return the
most semantically similar repos to that query that your GitHub user has starred
:::
## Demo 1
```{=html}
<script src="https://asciinema.org/a/661841.js" id="asciicast-661841" async="true"></script>
```
::: notes
- So here is a smash cut to the most basic demo.
- I call starpilot to execute the 'shoot' command with the query
"machine learning"
- Starpilot returns 10 repos that are all semantically similar to the
query, and all exist, no hallucinations here
- Most interestingly the repo `DeepLearningExamples` is returned,
which is depending on your level of pedanticness, not a 'machine
learning' repo, but a 'deep learning' repo
- However, `DeepLearningExamples` never states the term machine
learning. It's a deep learning, and that is semantically similar to
machine learning. This is exactly the kind of result I was hoping
for. The tool is looking at the search *intention* not the search
*terms*
:::
## Why is 'semantic similarity' important?
- Keyword search tests "how close a string is to another string"
- Exact Match: `cool cats != chill felines`
- Partial Match: `cool cat` partially fits `cooler cats`
- Semantic search tests "how similar in *meaning* is the phrase to
another phrase"
- `cool cats` is equivalent in meaning to `chill felines`, also
`groovy kittys`, `suave main coon` and `sphinx with style`
::: notes
- I think applying AI, LLM and RAG to a problem like might be a good
fit
- This is because the problem is about semantic similarity
- I'm looking for a library that does "DataFrames". Will I also be
interested in libraries that do "Data Tables"? Probably.
- I'm looking for a 'Front end' framework, will I also be interested
in 'UI' frameworks? Probably.
:::
## Why is this data suitable for 'semantic' but not 'keyword' search?
- GitHub stars are public and common across
languages/stacks/specialisms
- GitHub repos are text rich data
- GitHub repos are a 'weak standard'
- Topics are free text
- Descriptions are free text
::: notes
- Without access to suitable data, this project can't get off the
ground, but luckily GitHub is a treasure trove of easily acciessble
data for this use case
- The data is text rich, and the text is 'rich' in meaning
- However, the data is also 'varied' in structure, quality and context
- Repos vary subjectively by community, project requirements, and
developer style
- There is no 'repo police' saying a repo must have a certain
structure, or a certain set of tags
- This is where the AI comes in
:::
# An Intuitive Example
## Polars vs Pandas {auto-animate="true"}
::: columns
::: {.column width="50%" data-id="pandas"}
- data-analysis
- flexible
- alignment
- python
- data-science
:::
::: {.column width="50%" data-id="polars"}
- dataframe-library
- dataframe
- dataframes
- arrow
- python
- out-of-core
:::
:::
::: notes
- To illustrate this point, let's look at a few tags from GitHub
- This is the topic list for the `Polars` and `Pandas` repos
- They are functionally extremely close. They are both Python
libraries for data manipulation
- While there may be some subjective views about when to use which
they both solve practically identical problems and fit practically
identical use-cases
- If we were to search for 'DataFrames for Python' we would want to
return both of these repos
- However, keyword search would only return one of them because none
of the topics are shared
:::
## Polars vs Pandas {auto-animate="true"}
::: columns
::: {.column width="50%" data-id="pandas"}
> Flexible and powerful data analysis / manipulation library for Python,
> providing labeled data structures similar to R data.frame objects,
> statistical functions, and much more
:::
::: {.column width="50%" data-id="polars"}
> Dataframes powered by a multithreaded, vectorized query engine,
> written in Rust
:::
:::
::: notes
- Here are the descriptions for the `Polars` and `Pandas` repos
- Again very similar, but keyword search would not return both of
these repos
- I'd suggest unless you knew already what the difference between
these two libraries was, you'd be hard pressed to know which one has
been which in the last 2 slides
:::
## Polars vs Pandas {auto-animate="true"}
::: columns
::: {.column width="50%" data-id="pandas"}
![](images/panda4.png)
:::
::: {.column width="50%" data-id="polars"}
![](images/polars3.png)
:::
:::
::: notes
- If you managed to guess correctly, congratulations, you've won a
smug sense of self-satisfaction
- Even if you didn't, that's fine, because the point is that these two
libraries are very similar in meaning, but very different in the way
they are described
- Also, I didn't set this up, but I lobe the way that the panda was
generated with 2 laptops for some reason, and the polar bear is sort
of almost a pandas
- It's like the polar bear is all "Look, I'm Pandas too!" and the
Panda is furiously dual wielding laptops to attempt to prove it's
multi-threaded
:::
# Embedding Example
- "pandas package"
- "polars module"
- "panda breeding"
- "polar environment"
::: notes
To create an embedding, the source data is converted into a list of
numbers through a process called 'embedding' The numbers represent the
semantic meaning of the text You can imagine each number as a 'relevance
score' for a given topic I'm deliberately simplifying this, but it's a
good enough mental model for now Suppose we have the following 4 pieces
of text we want to embed separately
:::
## Embedding Example {auto-animate="true"}
```{mermaid label="embedding diagram"}
flowchart LR
subgraph strings
pp("pandas package")
pm("polars module")
pb("panda breeding")
pe("polar environment")
end
subgraph embedder
embed([function])
pp --> embed
pm --> embed
pb --> embed
pe --> embed
end
subgraph vector
ppv("0.37, 0.88")
pmv("0.49, 0.66")
pbv("0.83, 0.24")
pev("0.70, 0.12")
embed --> ppv
embed --> pmv
embed --> pbv
embed --> pev
end
```
::: notes
The embedding process takes the text and converts it into a list of
numbers In our silly example, the numbers are 2D, but in reality, they
are billions of dimensions
:::
## Embedding Example {auto-animate="true"}
```{r label="intuition example"}
library(ggplot2)
df <- data.frame(
query = c("pandas package", "polars module", "panda breeding", "polar environment"),
relevance_to_zoologists = c(0.37, 0.49, 0.83, 0.70),
relevance_to_data_scientists = c(0.88, 0.66, 0.24, 0.12),
stringsAsFactors = FALSE
)
ggplot(df, aes(x=relevance_to_zoologists, y=relevance_to_data_scientists)) +
geom_point() +
geom_text(aes(label=query), hjust=0.5, vjust=-0.5, check_overlap = TRUE) +
scale_x_continuous(limits = c(0, 1)) +
scale_y_continuous(limits = c(0, 1)) +
xlab("Relevance to Zoologists") +
ylab("Relevance to Data Scientists") +
coord_fixed(ratio = 1)
```
::: notes
Here's a plot of the 4 pieces of text in 2D space - The x-axis
represents the relevance to zoologists - The y-axis represents the
relevance to data scientists - The points are the 4 pieces of text
converted into an embedding
:::
## Embedding Example {auto-animate="true"}
```{r label="intuition example with query"}
# Add the 'data frames' query
reference_vector <- c(0.1, 0.6)
df <- rbind(df, data.frame(query = "data frames", relevance_to_zoologists = reference_vector[1], relevance_to_data_scientists = reference_vector[2]))
# Function to calculate cosine similarity
cos_sim <- function(x, reference_vector) {
dot_product <- sum(x * reference_vector)
magn_x <- sqrt(sum(x^2))
magn_reference <- sqrt(sum(reference_vector^2))
similarity <- dot_product / (magn_x * magn_reference)
return(similarity)
}
# Apply function to calculate cosine similarities
df$cosine_similarity <- apply(
df[, c("relevance_to_zoologists", "relevance_to_data_scientists")],
1,
function(x) {cos_sim(x, reference_vector)}
)
# Remove query similarity to self
df$cosine_similarity[end(df$cosine_similarity)[1]] = NA
# Plot
p <- ggplot(df, aes(x=relevance_to_zoologists, y=relevance_to_data_scientists)) +
geom_point() +
geom_text(aes(label=query), hjust=0.5, vjust=-0.5, check_overlap = TRUE) +
geom_segment(aes(
x = 0, y = 0, xend = relevance_to_zoologists, yend = relevance_to_data_scientists
),
arrow = arrow(length = unit(0.03, "npc")), size = 1, color = "black"
) +
scale_x_continuous(limits = c(0, 1)) +
scale_y_continuous(limits = c(0, 1)) +
xlab("Relevance to Zoologists") +
ylab("Relevance to Data Scientists") +
coord_fixed(ratio = 1)
# Loop to draw arcs and label
arc_cols = c("blue", "red", "green", "purple")
for(i in 1:nrow(df)) {
seg_pos <- 4 / (4 + i)
curve_data <- df[i, ]
curve_data$xpos <- seg_pos * reference_vector[1]
curve_data$ypos <- seg_pos * reference_vector[2]
p <- p + geom_curve(
data = curve_data,
aes(
x = xpos, y = ypos,
xend = relevance_to_zoologists / 2, yend = relevance_to_data_scientists / 2),
curvature = -0.4, color = arc_cols[i], linetype = "dashed", size = 1.2
) +
geom_text(
data = curve_data, aes(
x = relevance_to_zoologists / 2, y = relevance_to_data_scientists / 2,
label = round(cosine_similarity, 2)), check_overlap = TRUE, color = "black",
vjust = -2.5, hjust=0.7
)
}
p
```
::: notes
So now lets invent a query to put in the embedding space: "data frames"
When we embed this query, it will be placed in the embedding space
From this known point we then compute the cosine similarity to the other points
This is a simple mathematical operation that measures the similarity between two vectors, based on the angle between them
The closer the angle is to 0, the more similar the vectors are, and the higher the cosine similarity
This is shown in 2-dimensions, but in practice, the embeddings are in 100s of dimensions, and the cosine similarity is calculated in the same way
:::
# First Experiment
## Solution Requirements
::: notes
- A method to extract the data from GitHub
- A connection to an llm
- A framework to parse 100s (1000s?) of 'similarly' structured data
- A data store for processed data
- An interactive interface for the developer to access the data
:::
## Solution Architecture
:::{}
![](images/github.png){.fragment width=400}
![](images/langchain.png){.fragment width=400}
![](images/chroma.svg){.fragment width=400}
![](images/typer.svg){.fragment width=400}
:::
::: notes
- So to build this I need a few tools, libraries and datasources
- GitHub User Stars
- Rest API then GraphQL API
- I'll mention more about the change between those in a moment
- JSON files
- Langchain
- LLM Rest API Access
- Document parsing tools
- Vector store prompt query framework
- Chroma
- On disk vector store
- Typer
- 'FastAPI' style CLI framework
:::
## Similarity Search
```{mermaid label="minimum viable solution", .smaller}
flowchart LR
subgraph 0 Resources
GH([GitHub Repo])
DB[(Chroma)]
LLM([LLM])
end
subgraph 1 ETL
raw(JSON)
docs_in(Docs)
vec(Embedding)
GH--->raw
raw-->docs_in
docs_in-->LLM
LLM-->vec
vec-->DB
end
subgraph 2 Execution
cli([cli])
q(query)
LLM([LLM])
q_vec(Query Vector)
docs_out(Document)
a(suggestions)
cli-->q
q -->LLM
LLM -->q_vec
q_vec -->DB
DB-->docs_out
docs_out-->a
end
```
## Outcome {auto-animate="true"}
- IT'S ALIVE
- Data gets read
- Read data gets embedded
- Embedded data gets stored
- Embedded data gets queried
## Outcome {auto-animate="true"}
- IT STINKS
- Reading data is punishingly long
- 200 stars in 30 minutes
- Querying data is basic
- Semantic search works, but is broad
- 'DataFrames for Python' returns Pandas, and Tidyverse in R,
and DataTables in JavaScript
# Refinement
## Refined Version
```{mermaid label = "self query solution"}
flowchart LR
LLM([LLM])
GH([GitHub Repo])
raw(raw_GH/*.json)
prepped(enhanced_GH/*.json)
style prepped fill:red
docs_in(Documents)
vec_doc(Vector Document)
DB[(Chroma)]
self_query(Self Query)
vec_q(Vector Embedding)
db_filter(Filter Value)
cli([cli])
q(query)
docs_out(Document)
a(suggestions)
subgraph 0 Resources
GH
DB
LLM
end
subgraph 1 ETL
GH--->raw
raw-->prepped
prepped-->docs_in
docs_in-->LLM
LLM-->vec_doc
vec_doc-->DB
end
subgraph 2 Execution
LLM-->self_query
self_query-->db_filter
style self_query fill:red
self_query-->vec_q
db_filter-->DB
style db_filter fill:red
vec_q --> DB
cli-->q
q -->LLM
DB-->docs_out
docs_out-->a
end
```
## What this gets us
- Faster Data reads from GitHub
- 20x
- Enhanced data preprocessing
- Tags, Stars, Primary Language
- Selective data load
- 'Popular' repos
- Self Querying
- Language specific results
::: notes
- Faster data read with `GraphQL`
- Reduces network overhead of a per repo call
- Returns are now paginated `json` files
- 20x speed up
- Enhanced data preprocessing
- Extracts more data from the repo
- Repo tags
- Stars
- Primary Language
- More selective on data load
- Only load 'popular' repos
- Only load 'relevant' repos
- Enhanced data preprocessing + Self Querying
- Enables more nuanced queries like "Dataframes for Python" -\>
"Pandas"
- So lets look at some key parts of the code now
:::
# Example Data
## Example JSON in
``` json
{
"name": "langchain",
"nameWithOwner": "langchain-ai/langchain",
"url": "https://github.com/langchain-ai/langchain",
"homepageUrl": "https://python.langchain.com",
"description": "\ud83e\udd9c\ud83d\udd17 Build context-aware reasoning applications",
"stargazerCount": 77908,
"primaryLanguage": "Python",
"languages": [
"Python",
"Makefile",
"HTML",
"Dockerfile",
"TeX",
"JavaScript",
"Shell",
"XSLT",
"Jupyter Notebook",
"MDX"
],
"owner": "langchain-ai",
"content": "langchain \ud83e\udd9c\ud83d\udd17 Build context-aware reasoning applications Python"
}
```
::: notes
- This is an example of the json file that is written to disk
- It contains the metadata and content of a repo
- Content is created by starpilot by appending the `description` and
`name` fields
- At this stage I have one json per starred repo, and these now need
to be processed and loaded into the vector store
- To do this there is a `prepare_documents` function in Starpilot
:::
# The `prepare_documents` function
## `prepare_documents` {auto-animate="true"}
- The `prepare_documents` function is responsible for reading in the
json files and creating `Document` objects
``` {.python .python}
def prepare_documents(
repo_contents_dir: str = "./repo_content",
) -> List[Document]:
"""
Prepare the documents for ingestion into the vectorstore
"""
...
return documents
```
::: notes
- Here's the function signature
- It takes a directory of json files as input
- It returns a list of `Document` objects
- A `Document` is a class defined in the `LangChain` library
- The `Document` object contains the content *and* metadata for a
given repo
:::
## `prepare_documents` {auto-animate="true"}
Get the file paths for each `json` file for each repo
``` {.python code-line-numbers="7-10"}
def prepare_documents(
repo_contents_dir: str = "./repo_content",
) -> List[Document]:
"""
Prepare the documents for ingestion into the vectorstore
"""
file_paths = []
for file in os.listdir(repo_contents_dir):
file_paths.append(os.path.join(repo_contents_dir, file))
...
return documents
```
::: notes
- `prepare_documents` first creates a list of file paths to the json
files
- Each item in this list is the direct path to a specific json file,
each of which is the content of a specific repo read through
`GraphQL`
:::
## `prepare_documents` {auto-animate="true"}
Load the `Document` objects from the json files
``` {.python code-line-numbers="5-16"}
def prepare_documents(
repo_contents_dir: str = "./repo_content",
) -> List[Document]:
...
documents = []
for file_path in track(file_paths, description="Loading documents..."):
logger.debug("Loading document", file=file_path)
loader = JSONLoader(
file_path,
jq_schema=".",
content_key="content",
metadata_func=_metadata_func,
text_content=False,
)
if (loaded_document := loader.load())[0].page_content != "":
documents.extend(loaded_document)
...
return documents
```
::: notes
- The function reads in the json files written per repo into memory
- The `JSONLoader` class is used to load the json files
- The `Document` objects are then returned as a list
- `jq_schema` defines the "root" of the json file
- `content_key` defines the key in the json file that contains the
content
- `metadata_func` is a function that extracts metadata from the json
file
- Finally if the `Document` object has content it is added to the list
of `Document` objects
:::
## `prepare_documents` {auto-animate="true"}
The `metadata_func` function is used to extract metadata from the json
file
``` {.python code-line-numbers="12"}
def prepare_documents(
repo_contents_dir: str = "./repo_content",
) -> List[Document]:
...
documents = []
for file_path in track(file_paths, description="Loading documents..."):
logger.debug("Loading document", file=file_path)
loader = JSONLoader(
file_path,
jq_schema=".",
content_key="content",
metadata_func=_metadata_func,
text_content=False,
)
if (loaded_document := loader.load())[0].page_content != "":
documents.extend(loaded_document)
...
return documents
```
::: notes
- However, what's the `_metadata_func` function?
:::
## `prepare_documents` {auto-animate="true"}
The `_metadata_func` function is used to extract metadata from the json
file
``` {.python code-line-numbers="5-18"}
def prepare_documents(
repo_contents_dir: str = "./repo_content",
) -> List[Document]:
def _metadata_func(record: dict, metadata: dict) -> dict:
metadata["url"] = record.get("url")
metadata["name"] = record.get("name")
metadata["stargazerCount"] = record["stargazerCount"]
if (primary_language := record.get("primaryLanguage")) is not None:
metadata["primaryLanguage"] = primary_language
if (description := record.get("description")) is not None:
metadata["description"] = description
if (topics := record.get("topics")) is not None:
metadata["topics"] = " ".join(topics)
if (languages := record.get("languages")) is not None:
metadata["languages"] = " ".join(languages)
return metadata
...
return documents
```
::: notes
- `_metadata_func` is a function that extracts metadata for the repo
and processes it to be included as the metadata of the `Document`
object
- It extracts the `url`, `name`, `stargazerCount`, `primaryLanguage`,
`description`, `topics` and `languages` fields from the json file as
long as they exist
- The items that are extracted are then added to the `metadata`
dictionary
- The `metadata` dictionary is then returned as part of the `Document`
object
:::
## Using the `prepare_documents` function {auto-animate="true"}
`prepare_documents` is used to load the `Document` objects into \`Chroma
``` {.python code-line-numbers="5"}
from langchain_community.vectorstores import Chroma
from langchain_openai.embeddings import OpenAIEmbeddings
Chroma.from_documents(
documents=utils.prepare_documents(),
embedding=OpenAIEmbeddings(model="text-embedding-3-large"),
persist_directory="./vectorstore-chroma",
)
```
::: notes
- To use this list of `Documents` , we need to pass it to the `Chroma`
class using the `from_documents` method.
:::
## Using the `prepare_documents` function {auto-animate="true"}
`Chroma.from_documents` also needs an `embedding` object and a
`persist_directory`
``` {.python code-line-numbers="6-7"}
from langchain_community.vectorstores import Chroma
from langchain_openai.embeddings import OpenAIEmbeddings
Chroma.from_documents(
documents=utils.prepare_documents(),
embedding=OpenAIEmbeddings(model="text-embedding-3-large"),
persist_directory="./vectorstore-chroma",
)
```
::: notes
- The `Chroma` class is a class that is part of the `LangChain`
library
- We also need to pass an `embedding` object to the `Chroma` class
- On call, this method will create a vector store from the `Document`
objects and then for each `Document` object, it will embed the
content of the `Document` object using the `OpenAIEmbeddings` class
and store the embeddings in the vector store
- The metadata of the `Document` object is also stored in the vector
store, but not embedded. We'll see why this is important later
:::
# Accessing the Vector Store
## Semantic similarity search {auto-animate="true"}
Semantic search accepts a query string and returns the most relevant
`Document` objects
``` {.python code-line-numbers="5"}
def shoot(
vectorstore_path: str,
k: int,
method: SearchMethods = SearchMethods.similarity,
query: str,
) -> List[Document]:
"""
Create a retriever from a vectorstore and query it
"""
```
::: notes
- This is the function signature for the `create_retriever` function
in starpilot
:::
## Semantic similarity search {auto-animate="true"}
Create a `retriever` object from the vector store and query it
``` {.python code-line-numbers="9-21"}
def shoot(
vectorstore_path: str,
k: int,
method: SearchMethods = SearchMethods.similarity,
query: str,
) -> List[Document]:
"""
Create a retriever from a vectorstore and query it
"""
retriever = Chroma(
persist_directory=vectorstore_path,
embedding_function=OpenAIEmbeddings(
model="text-embedding-3-large"
),
).as_retriever(
search_type=method,
search_kwargs={
"k": k,
},
)
return retriever.get_relevant_documents(query)
```
::: notes
- This is the `shoot` function in starpilot, which is used to perform
a semantic search on the vector store
- First, we need to create a retriever object from the vector store
Class
- We need to specify the embedding function that was used to embed the
content of the `Document` object
- We also need to specify the search method that we want to use, which
is effectively the algorithm to compute the similarity between the
query vector and the vectors in the vector store
- Finally, we need to pass the query string to the
`get_relevant_documents` method of the retriever object, and it will
return the most relevant `Document` objects
:::
# Self Querying
## Self Querying {auto-animate="true"}
Self-querying is a way to pre-filter the results of a semantic search by
metadata fields
```` {.python code-line-numbers="1-16"}
def astrologer(
query: str,
k: Optional[int] = typer.Option(
4, help="Number of results to fetch from the vectorstore"
),
) -> List[Document]:
"""
A self-query of the vectorstore that allows the user to search for a repo while filtering by attributes
Example:
```
starpilot astrologer "What can I use to build a web app with Python?"
starpilot astrologer "Suggest some Rust machine learning crates"
```
"""
metadata_field_info = [
AttributeInfo(
name="languages",
description="the programming languages of a repo. Example: ['python', 'R', 'Rust']",
type="string",
),
AttributeInfo(
name="name",
description="the name of a repository. Example: 'langchain'",
type="string",
),
AttributeInfo(
name="topics",
description="the topics a repository is tagged with. Example: ['data-science', 'machine-learning', 'web-development', 'tidyverse']",
type="string",
),
AttributeInfo(
name="url",
description="the url of a repository on GitHub",
type="string",
),
AttributeInfo(
name="stargazerCount",
description="the number of stars a repository has on GitHub",
type="number",
),
]
document_content_description = "content describing a repository on GitHub"
prompt = get_query_constructor_prompt(
document_content_description,
metadata_field_info,
examples=[
(
"Python machine learning repos",
{
"query": "machine learning",
"filter": 'eq("primaryLanguage", "Python")',
},