-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_vector_database_tutorial.qmd
More file actions
1776 lines (1450 loc) · 59.6 KB
/
01_vector_database_tutorial.qmd
File metadata and controls
1776 lines (1450 loc) · 59.6 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
---
title: "Vector Database Document Ingestion with PostgreSQL pgvector, Google Embeddings, and Claude Analysis in R"
format: html
execute:
eval: false
echo: true
editor:
markdown:
wrap: 72
---
## Table of Contents
1. [Introduction to Vector Databases](#introduction)
2. [Prerequisites and Setup](#prerequisites)
3. [Understanding the Workflow](#workflow)
4. [Database Schema Design](#schema)
5. [Document Processing Pipeline](#processing)
6. [Embedding Generation](#embeddings)
7. [Data Insertion](#insertion)
8. [Semantic Search](#search)
9. [Complete Code Examples](#examples)
10. [Best Practices](#best-practices)
11. [Troubleshooting](#troubleshooting)
## Introduction to Vector Databases for Retrieval Augmented Generation (RAG) {#introduction}
Think of traditional database search like looking up words in a
dictionary—you need to know the exact term you're searching for. Vector
databases work more like how your brain associates ideas: they
understand that "car" and "automobile" are related concepts, even though
the words are completely different. This tutorial will show you how to
build that kind of intelligent search system using PostgreSQL's pgvector
extension.
Vector databases enable semantic search by storing high-dimensional
vector representations (embeddings) of unstructured data like text
documents. Unlike traditional keyword-based search, vector databases can
find conceptually similar content even when exact words don't match.
This makes them perfect for building systems that need to understand
meaning, not just match keywords—like chatbots that answer questions
about your documentation, or recommendation engines that find similar
content.
### Key Concepts:
- **Embeddings**: Dense numerical representations of text that capture
semantic meaning
- **Vector Similarity**: Mathematical measures (cosine, euclidean) to
find related content
- **pgvector**: PostgreSQL extension that adds vector data types and
operations
- **Semantic Search**: Finding content based on meaning rather than
exact keywords
### Use Cases:
- Document similarity search
- Recommendation systems
- Question-answering systems
- Content discovery
- Duplicate detection
## Prerequisites and Setup {#prerequisites}
### Required R Packages:
```{r}
packages <- c(
# Database connectivity
"DBI",
"RPostgreSQL",
"duckdb",
# API interactions and JSON handling
"httr",
"jsonlite",
# Data manipulation
"dplyr",
"readr",
"stringr",
# Optional: Local embeddings
"text"
)
installed <- packages %in% rownames(installed.packages())
if (any(!installed)) install.packages(packages[!installed])
invisible(lapply(packages, function(pkg) library(pkg, character.only = TRUE)))
```
### Data
#### Knowledge Base documents and patterns
This tutorial uses two types of knowledge base files in the
`knowledge_base/` directory that demonstrate different aspects of RAG
systems:
**Documents** <br /> `knowledge_base/docs/geographic_descriptions.md`:
This markdown file contains documentation about FIPS codes, RIN
communities, and geographic boundaries—the kind of unstructured text
that's perfect for semantic search. When you ask "What are RIN
communities?" the vector database will find relevant chunks from this
document based on conceptual similarity, not keyword matching. This is
the classic RAG use case: turning prose documentation into searchable
knowledge.
**Patterns** <br /> `knowledge_base/patterns/query_patterns.json`: This
JSON file maps natural language questions to structured database
queries. It shows how Homer (the CORI AI agent) needs to recognize
patterns like "Show me counties in Arizona" and translate them into SQL
filters. In a production RAG system, you'd embed both the user's
question AND these query patterns to find the best matching query
strategy. Think of it as teaching the system how to "think" about data
queries by providing examples.
Together, these files represent the two knowledge types Homer needs:
domain knowledge (what things mean) and procedural knowledge (how to
query for things). The structured data section below shows how to
execute those query patterns against actual county-level data.
#### Structured Data
The `query_patterns.json` file above isn't just documentation—it's
training data for a RAG system. In production, you'd embed those user
queries (like "Show me RIN communities in Arizona") into vectors, then
use semantic search to match new user questions to the closest pattern.
Once you find the matching pattern, you execute its associated query:
``` sql
SELECT *
FROM rin_service_areas
WHERE statefp = '04'
AND rin_community IS NOT NULL
```
This code demonstrates what happens when you actually execute those four
query patterns against real county-level data from
`rin_service_areas.parquet`. We're using DuckDB here because it can read
Parquet files directly without loading them into R memory first. The
examples below include a critical pattern: RIN community lookup by name
using case-insensitive partial matching (`LIKE '%Dalles%'` in DuckDB,
which is case-insensitive by default). This allows "The Dalles", "the
dalles", or just "Dalles" to all match the same community.
```{r}
#| eval: false
# Load required packages
library(DBI)
library(duckdb)
library(dplyr)
# Create a DuckDB connection
con_duckdb <- dbConnect(duckdb::duckdb(), dbdir = ":memory:")
# Read the parquet file directly into DuckDB
# DuckDB has native parquet support - no need to load into R first
parquet_path <- "data/rin_service_areas.parquet"
# Register the parquet file as a queryable table
dbExecute(con_duckdb, sprintf(
"CREATE VIEW rin_service_areas AS SELECT * FROM read_parquet('%s')",
parquet_path
))
# Verify table structure
dbGetQuery(con_duckdb, "DESCRIBE rin_service_areas")
# 1. Execute Query Pattern 1: RIN Community Lookup by Name
# User query: "What is the approximate location of the RIN community known as the Dalles?"
# Filter: rin_community LIKE '%Dalles%' (case-insensitive partial match)
# Note: In production, strip "the/a/an" from user input first
cat("\n=== Query 1: RIN Community Lookup (The Dalles) ===\n")
query1_result <- dbGetQuery(con_duckdb, "
SELECT *
FROM rin_service_areas
WHERE rin_community LIKE '%Dalles%'
")
print(query1_result |> dplyr::select(-c(`centroid`, `geometry`)))
if (nrow(query1_result) > 0) {
cat(sprintf("\nFound RIN community: %s (FIPS: %s)\n",
query1_result$rin_community[1],
query1_result$geoid_co[1]))
cat(sprintf("Location: %s, Lat/Lon: (%.4f, %.4f)\n",
query1_result$namelsad[1],
query1_result$lat[1],
query1_result$lon[1]))
}
# 2. Execute Query Pattern 2: County Lookup
# User query: "What data do you have for Hood River County?"
# Filter: geoid_co == '41027'
cat("\n=== Query 2: County Lookup (Hood River County, FIPS 41027) ===\n")
query2_result <- dbGetQuery(con_duckdb, "
SELECT *
FROM rin_service_areas
WHERE geoid_co = '41027'
")
print(query2_result |> dplyr::select(-c(`centroid`, `geometry`)))
# 3. Execute Query Pattern 3: State Filter with RIN Communities
# User query: "Show me RIN communities in Arizona"
# Filter: statefp == '04' AND rin_community.notna()
cat("\n=== Query 3: RIN Communities in Arizona (statefp 04) ===\n")
query3_result <- dbGetQuery(con_duckdb, "
SELECT *
FROM rin_service_areas
WHERE statefp = '04'
AND rin_community IS NOT NULL
")
print(query3_result |> dplyr::select(-c(`centroid`, `geometry`)))
# Display summary
cat(sprintf("\nFound %d RIN communities in Arizona\n", nrow(query3_result)))
# 4. Execute Query Pattern 4: Ranking by Land Area
# User query: "What are the largest counties by land area?"
# Sort: aland DESC
cat("\n=== Query 4: Top 10 Largest Counties by Land Area ===\n")
query4_result <- dbGetQuery(con_duckdb, "
SELECT
geoid_co,
namelsad as county_name,
statefp,
aland,
ROUND(aland / 1000000, 2) as land_area_sq_km
FROM rin_service_areas
ORDER BY aland DESC
LIMIT 10
")
print(query4_result)
# Optional: Clean up connection when done
dbDisconnect(con_duckdb, shutdown = TRUE)
```
### PostgreSQL Setup:
1. Install PostgreSQL (version 11+)
2. Install pgvector extension:
```{sql}
#| eval: false
-- Connect as superuser
CREATE EXTENSION vector;
```
### API Keys (Choose One):
- **Google AI/Vertex AI API**: For high-quality embeddings via
Google's embedding models
- **Local Models**: Using Hugging Face transformers via R's `text`
package
### Google AI Setup:
1. Create a Google Cloud Project or use Google AI Studio
2. Enable the Vertex AI API (for production) or use Google AI Studio
(for development)
3. Set up authentication:
- **Google AI Studio**: Get API key from
https://makersuite.google.com/app/apikey
- **Vertex AI**: Set up service account credentials
4. Set environment variable: `GOOGLE_API_KEY` or
`GOOGLE_APPLICATION_CREDENTIALS`
## Understanding the Workflow {#workflow}
The document ingestion pipeline follows these steps:
```
Raw Documents → Text Processing → Chunking → Embedding Generation → Vector Storage → Indexing
```
### 1. Document Preprocessing
- Extract text from various formats (TXT, PDF, CSV, etc.)
- Clean and normalize text
- Handle encoding issues
### 2. Text Chunking
- Split large documents into manageable pieces
- Maintain context with overlapping chunks
- Optimize chunk size for embedding models
### 3. Embedding Generation
- Convert text chunks to numerical vectors
- Use pre-trained models (OpenAI, sentence-transformers)
- Maintain consistent dimensionality
### 4. Database Storage
- Store original text alongside vectors
- Create efficient vector indexes
- Maintain metadata relationships
### 5. Search Interface
- Generate query embeddings
- Perform similarity calculations
- Return ranked results with scores
## Database Schema Design {#schema}
The schema below stores three types of information: the original text
content (so you can show it to users), metadata about where it came from
(file paths, document types, timestamps), and the vector embeddings
themselves. The `embedding vector(768)` column is the magic—that's where
pgvector stores the 768-dimensional numerical representation of each
text chunk.
Why 768 dimensions? That's what Google's text-embedding-004 model
produces. Different embedding models create different dimensional
vectors (OpenAI's models use 1536, for example), so your schema needs to
match whatever model you're using. The dimensions are like coordinates
in a very high-dimensional space—documents with similar meanings end up
near each other in that space, which is how semantic search works.
### Core Documents Table:
```{sql}
#| eval: false
CREATE TABLE documents (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
source_file TEXT,
document_type VARCHAR(50),
chunk_index INTEGER DEFAULT 0,
metadata JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
embedding vector(768) -- Google text-embedding-004 dimensions
);
```
### Vector Index for Performance:
```{sql}
#| eval: false
-- IVFFlat index for approximate nearest neighbor search
CREATE INDEX documents_embedding_idx
ON documents USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
-- HNSW index (alternative, better for high-dimensional data)
-- CREATE INDEX documents_embedding_hnsw_idx
-- ON documents USING hnsw (embedding vector_cosine_ops);
```
### examine embedding values
```{r}
con <- cori.db::connect_to_db(schema = 'public', dbname = 'pgvector-tutorial')
documents <- cori.db::read_db(con, 'documents')
DBI::dbDisconnect(con)
```
### Supporting Tables:
```{sql}
#| eval: false
-- Track document sources
CREATE TABLE document_sources (
id SERIAL PRIMARY KEY,
source_path TEXT UNIQUE,
file_hash VARCHAR(64),
processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Store embedding model metadata
CREATE TABLE embedding_models (
id SERIAL PRIMARY KEY,
model_name VARCHAR(100),
dimensions INTEGER,
provider VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
## Document Processing Pipeline {#processing}
Before we can create embeddings, we need to get text out of whatever
format it's stored in. This extraction function handles the most common
document types you'll encounter: plain text files, CSVs (which we
convert to text representations), and PDFs (if you have the `pdftools`
package installed). The goal is simple: turn any supported file into a
single string of text that we can then chunk and embed.
Think of this as the "loading dock" of your RAG system. You might need
to extend this function to handle Word documents, web pages scraped from
URLs, or database records—whatever sources contain the knowledge you
want to search. The key principle is that by the time you're done with
this step, everything should be plain text, ready for the next stage of
processing.
### Query Preprocessing for RIN Community Names
Before text extraction, let's add a helper function for preprocessing
user queries about RIN communities. When users ask about "The Dalles" or
"the Hood River area," we need to strip leading articles before
matching. This is critical for the partial matching pattern
(`LIKE '%keyword%'`) to work reliably.
```{r}
strip_leading_articles <- function(text) {
# Remove common leading articles (the, a, an) - case insensitive
# Preserves articles in the middle of the string
cleaned <- stringr::str_replace(text, "^(?i)(the|a|an)\\s+", "")
return(cleaned)
}
# Examples:
# strip_leading_articles("The Dalles") → "Dalles"
# strip_leading_articles("the Hood River area") → "Hood River area"
# strip_leading_articles("A New Beginning") → "New Beginning"
# strip_leading_articles("Northern Colorado") → "Northern Colorado" (no article)
```
This function is used before generating embeddings for queries or before
constructing SQL filters. For example, when matching "What data do you
have for The Dalles?", we'd extract "The Dalles", strip it to "Dalles",
then search with `rin_community ILIKE '%Dalles%'`.
### Text Extraction Function:
```{r}
extract_text <- function(file_path) {
# Detect file type and extract accordingly
file_ext <- tools::file_ext(tolower(file_path))
switch(file_ext,
"csv" = {
df <- readr::read_csv(file_path)
# Convert structured data to searchable text
paste(capture.output(print(df)), collapse = "\n")
},
"md" = readr::read_file(file_path),
"txt" = readr::read_file(file_path),
"pdf" = {
# Requires pdftools package
if (requireNamespace("pdftools", quietly = TRUE)) {
pdftools::pdf_text(file_path) %>% paste(collapse = "\n")
} else {
stop("pdftools package required for PDF processing")
}
},
stop("Unsupported file type: ", file_ext)
)
}
```
### Intelligent Text Chunking
Here's where we solve one of the core challenges in RAG systems: how do
you turn a 50-page document into searchable pieces? Embedding models
have token limits (typically 512-8192 tokens), but even when they
support longer sequences, smaller chunks work better for retrieval.
Think of it this way—if your entire document becomes a single vector,
how do you find the specific paragraph that answers a user's question?
The trick is splitting text at natural boundaries (like sentences) while
maintaining some overlap between chunks. That overlap is crucial: if an
important concept spans the chunk boundary, the overlap ensures both
neighboring chunks contain the full idea. This function uses a
1000-character default chunk size with 200 characters of overlap,
meaning the last few sentences of one chunk reappear at the start of the
next. You'll want to tune these parameters based on your
content—technical documentation might work better with smaller chunks
(300-500 chars), while narrative content can handle larger ones
(1500-2000 chars).
### Intelligent Text Chunking:
```{r}
chunk_text <- function(text, chunk_size = 500, chunk_overlap = 100) {
# Split on sentences to maintain context
sentences <- stringr::str_split(text, "(?<=[.!?])\\s+")[[1]]
chunks <- list()
current_chunk <- ""
current_length <- 0
for (sentence in sentences) {
sentence_length <- nchar(sentence)
if (current_length + sentence_length > chunk_size && current_length > 0) {
# Save current chunk
chunks <- append(chunks, current_chunk)
# Start new chunk with overlap (last chunk_overlap characters)
if (chunk_overlap > 0 && nchar(current_chunk) > chunk_overlap) {
overlap_text <- substr(current_chunk, nchar(current_chunk) - chunk_overlap + 1, nchar(current_chunk))
current_chunk <- paste(overlap_text, sentence)
} else {
current_chunk <- sentence
}
current_length <- nchar(current_chunk)
} else {
# Add sentence to current chunk
if (nchar(current_chunk) > 0) {
current_chunk <- paste(current_chunk, sentence)
} else {
current_chunk <- sentence
}
current_length <- nchar(current_chunk)
}
}
# Add final chunk
if (nchar(current_chunk) > 0) {
chunks <- append(chunks, current_chunk)
}
return(unlist(chunks))
}
```
## Embedding Generation {#embeddings}
This is where the real magic happens. An embedding is a dense numerical
vector that captures the semantic meaning of text—think of it as
translating words into a coordinate system where similar concepts
cluster together in space. When you embed "vehicle" and "automobile,"
they end up very close to each other in this high-dimensional space,
even though they share no letters. When you embed "vehicle" and
"broccoli," they're far apart. That's how semantic search works.
The function below uses Google's text-embedding-004 model, which
produces 768-dimensional vectors. It handles batching (processing 100
texts at a time to respect API rate limits), includes fallback logic if
the API fails, and validates that each embedding has the expected 768
dimensions. The `Sys.sleep(0.1)` call prevents you from hitting rate
limits—you can adjust this based on your API tier. In production, you
might cache embeddings so you don't need to regenerate them every time
you restart your application.
### Google Gemini API for Embeddings Generation
```{r}
# General-purpose Gemini API call function
gemini_api_call <- function(prompt,
model = "gemini-2.5-flash",
#model = "gemini-2.5-pro",
max_tokens = 1000,
google_api_key = Sys.getenv("GOOGLE_API_KEY")) {
# Validate API key
if (google_api_key == "") {
stop("GOOGLE_API_KEY environment variable not set")
}
# Build the API URL with the API key as query parameter
url <- sprintf(
"https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s",
model,
google_api_key
)
response <- httr::POST(
url = url,
httr::add_headers("Content-Type" = "application/json"),
body = jsonlite::toJSON(list(
contents = list(list(
parts = list(list(
text = prompt
))
)),
generationConfig = list(
maxOutputTokens = max_tokens
)
), auto_unbox = TRUE)
)
if (httr::status_code(response) == 200) {
result <- jsonlite::fromJSON(httr::content(response, "text"))
message("Gemini API request successful")
if (!is.null(result$candidates) && length(result$candidates) > 0 && !is.null(result$candidates[[1]])) {
# Extract text from Gemini response structure
content <- result$candidates[[1]]
if (!is.null(content$parts) && !is.null(content$parts[[1]]) && !is.null(content$parts[[1]]$text)) {
return(content$parts[[1]]$text)
}
} else {
# Fallback if structure is unexpected
warning("Unexpected Gemini API response structure")
return(result)
}
} else {
status_code <- httr::status_code(response)
error_content <- httr::content(response, "text")
warning(paste("Gemini API error - Status:", status_code, "Response:", error_content))
# Check specific error cases
if (status_code == 401 || status_code == 403) {
warning("Authentication failed - check your GOOGLE_API_KEY")
} else if (status_code == 400) {
warning("Bad request - check API request format")
} else if (status_code == 429) {
warning("Rate limit exceeded - too many requests")
} else if (status_code == 500) {
warning("Internal server error - try again later")
}
stop("API call failed - see warnings above")
}
}
generate_google_embeddings <- function(texts, api_key = Sys.getenv("GOOGLE_API_KEY")) {
embeddings <- list()
batch_size <- 100 # API rate limiting
# Check if API key is available
if (api_key == "" || is.na(api_key)) {
warning("Google API key not found, using fallback random embeddings")
# Generate random embeddings for testing (768 dimensions for text-embedding-004)
return(lapply(texts, function(x) runif(768, -1, 1)))
}
for (i in seq(1, length(texts), batch_size)) {
batch_end <- min(i + batch_size - 1, length(texts))
batch_texts <- texts[i:batch_end]
message(paste("Processing embedding batch", ceiling(i/batch_size), "with", length(batch_texts), "texts"))
# Prepare requests for batch processing
requests <- lapply(batch_texts, function(text) {
list(
model = "models/text-embedding-004",
content = list(parts = list(list(text = text)))
)
})
response <- httr::POST(
url = paste0("https://generativelanguage.googleapis.com/v1beta/models/text-embedding-004:batchEmbedContents?key=", api_key),
httr::add_headers("Content-Type" = "application/json"),
body = jsonlite::toJSON(list(requests = requests), auto_unbox = TRUE),
encode = "raw"
)
if (httr::status_code(response) == 200) {
# Parse with simplifyVector = FALSE to preserve list structure
result <- jsonlite::fromJSON(httr::content(response, "text"), simplifyVector = FALSE)
message(paste("Successfully got embeddings for", length(result$embeddings), "texts"))
# Validate and extract embeddings
batch_embeddings <- lapply(result$embeddings, function(x) {
if (is.null(x$values) || length(x$values) == 0) {
warning("Empty embedding received, using fallback")
return(runif(768, -1, 1)) # Fallback random embedding
}
# Convert list of numbers to numeric vector
values <- unlist(x$values)
if (length(values) != 768) {
warning(paste("Unexpected embedding dimension:", length(values), "- using fallback"))
return(runif(768, -1, 1))
}
return(values)
})
embeddings <- c(embeddings, batch_embeddings)
} else {
error_msg <- httr::content(response, "text")
warning(paste("Google API Error:", error_msg, "- Using fallback embeddings"))
# Generate fallback random embeddings for this batch
batch_embeddings <- lapply(batch_texts, function(x) runif(768, -1, 1))
embeddings <- c(embeddings, batch_embeddings)
}
Sys.sleep(0.1) # Rate limiting
}
message(paste("Generated", length(embeddings), "total embeddings"))
return(embeddings)
}
# Alternative: Vertex AI approach (for production use)
generate_vertex_embeddings <- function(texts, project_id = Sys.getenv("GOOGLE_CLOUD_PROJECT")) {
# Requires googleCloudVertexAIR package or REST API calls
# This is a simplified example - you'd need proper authentication setup
embeddings <- list()
for (text in texts) {
# Vertex AI REST API call would go here
# Using text-embedding-004 model through Vertex AI
# Returns 768-dimensional vectors
}
return(embeddings)
}
```
### Local Embedding Models:
```{r}
generate_local_embeddings <- function(texts) {
# Using sentence-transformers via text package
# Requires Python environment with sentence-transformers
# Initialize model (first run downloads model)
embeddings <- text::textEmbed(
texts = texts,
model = "sentence-transformers/all-MiniLM-L6-v2",
device = "cpu" # Use "cuda" for GPU acceleration
)
# Extract embedding vectors
return(embeddings$texts$texts)
}
```
### Claude API Integration for Document Analysis:
```{r}
# General-purpose Anthropic API call function
claude_api_call <- function(prompt,
model = "claude-sonnet-4-20250514",
max_tokens = 1000,
claude_api_key = Sys.getenv("ANTHROPIC_API_KEY")) {
# Validate API key
if (claude_api_key == "") {
stop("ANTHROPIC_API_KEY environment variable not set")
}
response <- httr::POST(
url = "https://api.anthropic.com/v1/messages",
httr::add_headers(
"x-api-key" = claude_api_key,
"Content-Type" = "application/json",
"anthropic-version" = "2023-06-01"
),
body = jsonlite::toJSON(list(
model = model,
max_tokens = max_tokens,
messages = list(list(
role = "user",
content = prompt
))
), auto_unbox = TRUE)
)
if (httr::status_code(response) == 200) {
result <- jsonlite::fromJSON(httr::content(response, "text"))
message("Claude API request successful")
# Handle the data.frame structure of content
if (is.data.frame(result$content)) {
return(result$content$text[1])
} else {
# Fallback for old API structure
return(result$content[[1]]$text)
}
} else {
status_code <- httr::status_code(response)
error_content <- httr::content(response, "text")
warning(paste("Claude API error - Status:", status_code, "Response:", error_content))
# Check specific error cases
if (status_code == 401) {
warning("Authentication failed - check your ANTHROPIC_API_KEY")
} else if (status_code == 400) {
warning("Bad request - check API request format")
} else if (status_code == 429) {
warning("Rate limit exceeded - too many requests")
} else if (status_code == 500) {
warning("Internal server error - try again later")
}
stop("API call failed - see warnings above")
}
}
# Enhanced document processing with Claude for intelligent analysis
enhance_document_with_claude <- function(text, claude_api_key = Sys.getenv("ANTHROPIC_API_KEY")) {
# Use Claude for document analysis and enhancement
prompt <- paste(
"Analyze this document and provide:",
"1. A concise summary (2-3 sentences)",
"2. Key topics and themes",
"3. Important entities (people, places, organizations)",
"4. Suggested metadata tags",
"Document text:", text,
sep = "\n"
)
response <- httr::POST(
url = "https://api.anthropic.com/v1/messages",
httr::add_headers(
"x-api-key" = claude_api_key,
"Content-Type" = "application/json",
"anthropic-version" = "2023-06-01"
),
body = jsonlite::toJSON(list(
model = "claude-sonnet-4-20250514",
max_tokens = 1000,
messages = list(list(
role = "user",
content = prompt
))
), auto_unbox = TRUE)
)
if (httr::status_code(response) == 200) {
result <- jsonlite::fromJSON(httr::content(response, "text"))
message("Claude API request successful")
# Handle the data.frame structure of content
if (is.data.frame(result$content)) {
return(result$content$text[1])
} else {
# Fallback for old API structure
return(result$content[[1]]$text)
}
} else {
status_code <- httr::status_code(response)
error_content <- httr::content(response, "text")
warning(paste("Claude API error - Status:", status_code, "Response:", error_content))
# Check specific error cases
if (status_code == 401) {
warning("Authentication failed - check your ANTHROPIC_API_KEY")
} else if (status_code == 400) {
warning("Bad request - check API request format")
} else if (status_code == 429) {
warning("Rate limit exceeded - too many requests")
}
return("Analysis unavailable - API connection failed")
}
}
```
### Embedding Quality Considerations:
- **Model Selection**: Google's text-embedding-004 is general-purpose
and high-quality
- **Dimensionality**: 768 dimensions provide excellent
precision-performance balance
- **Consistency**: Always use same model for indexing and querying
- **Normalization**: Google embeddings are pre-normalized for cosine
similarity
- **Multilingual**: Use textembedding-gecko-multilingual for
non-English content
- **Claude Enhancement**: Use Claude for intelligent document
preprocessing and metadata extraction
## Data Insertion {#insertion}
Now we need to get all those embeddings into PostgreSQL efficiently.
Inserting one row at a time would be painfully slow—imagine inserting
10,000 document chunks with 10,000 separate database round trips. Batch
insertion solves this by grouping multiple inserts into a single SQL
statement, dramatically reducing network overhead and transaction costs.
The function below processes documents in batches of 100, converting
each embedding vector to PostgreSQL's vector format (a string like
`[0.123, -0.456, 0.789, ...]`). The parameterized query approach (`$1`,
`$2`, etc.) prevents SQL injection and handles special characters in
your text content. If an embedding somehow ends up empty or malformed,
the fallback logic generates a random vector so the insertion doesn't
fail—you'd want better error handling in production, but this keeps your
pipeline running during development.
**Metadata handling**: The function automatically detects if your data
frame includes a `metadata` column and inserts it as JSONB if present.
This is essential for Example 2 (Query Pattern Matching) where we store
SQL filters and sorting logic in metadata for later retrieval.
### Batch Insertion Strategy:
```{r}
# Clear existing documents (useful during development/testing)
clear_documents <- function(con) {
DBI::dbExecute(con, "DELETE FROM documents")
message("Cleared all documents from database")
}
insert_documents_batch <- function(documents_df, embeddings_list, con, batch_size = 100) {
# Prepare batch insertion for better performance
for (i in seq(1, nrow(documents_df), batch_size)) {
batch_end <- min(i + batch_size - 1, nrow(documents_df))
batch_docs <- documents_df[i:batch_end, ]
batch_embeddings <- embeddings_list[i:batch_end]
# Check if metadata column exists (once per batch)
has_metadata <- "metadata" %in% names(batch_docs)
# Build VALUES clause for batch insert
values_parts <- c()
params <- list()
param_idx <- 1
for (j in 1:nrow(batch_docs)) {
# Validate embedding before converting
embedding <- batch_embeddings[[j]]
if (is.null(embedding) || length(embedding) == 0) {
warning(paste("Empty embedding for row", j, "using fallback"))
embedding <- runif(768, -1, 1) # Fallback random embedding
}
# Convert embedding to PostgreSQL vector format
embedding_str <- paste0("[", paste(embedding, collapse = ","), "]")
# Additional validation for vector string
if (embedding_str == "[]") {
warning(paste("Still empty vector for row", j, "after fallback"))
embedding_str <- paste0("[", paste(runif(768, -1, 1), collapse = ","), "]")
}
if (has_metadata) {
values_parts <- c(values_parts, sprintf("($%d, $%d, $%d, $%d::jsonb, $%d::vector)",
param_idx, param_idx+1, param_idx+2, param_idx+3, param_idx+4))
params <- c(params, list(
batch_docs$title[j],
batch_docs$content[j],
batch_docs$source_file[j],
batch_docs$metadata[j],
embedding_str
))
param_idx <- param_idx + 5
} else {
values_parts <- c(values_parts, sprintf("($%d, $%d, $%d, $%d::vector)",
param_idx, param_idx+1, param_idx+2, param_idx+3))
params <- c(params, list(
batch_docs$title[j],
batch_docs$content[j],
batch_docs$source_file[j],
embedding_str
))
param_idx <- param_idx + 4
}
}
# Build INSERT statement based on whether metadata is present
if (has_metadata) {
insert_sql <- sprintf(
"INSERT INTO documents (title, content, source_file, metadata, embedding) VALUES %s",
paste(values_parts, collapse = ", ")
)
} else {
insert_sql <- sprintf(
"INSERT INTO documents (title, content, source_file, embedding) VALUES %s",
paste(values_parts, collapse = ", ")
)
}
DBI::dbExecute(con, insert_sql, params)
cat("Inserted batch", ceiling(i/batch_size), "of", ceiling(nrow(documents_df)/batch_size))
if (has_metadata) cat(" (with metadata)")
cat("\n")
}
}
```
## Semantic Search {#search}
Finally, we get to use all that infrastructure we've built! Semantic
search works by converting your query into an embedding (using the same
model you used for indexing), then finding documents whose embeddings
are closest to it in vector space. The `<=>` operator is pgvector's
cosine distance operator—it measures the angle between two vectors,
where 0 means identical and 2 means completely opposite. We convert this
to a similarity score with `1 - (embedding <=> query)` so higher scores
mean better matches.