-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrdfPoweredChatbot.py
More file actions
909 lines (740 loc) Β· 37.4 KB
/
rdfPoweredChatbot.py
File metadata and controls
909 lines (740 loc) Β· 37.4 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
"""
RDF-Powered Vector Chatbot with Duplicate Detection
PURPOSE:
This is a complete end-to-end system that transforms RDF knowledge graphs into a
vector-powered chatbot with built-in duplicate detection and debugging capabilities.
It extracts chunks from RDF graphs, creates vector embeddings, stores them in Oracle
database, and provides an intelligent chatbot interface with comprehensive duplicate
monitoring throughout the entire pipeline.
WHAT IT DOES:
1. RDF Processing - Extracts chunks and metadata from knowledge graphs via SPARQL
2. Vector Generation - Creates embeddings using HuggingFace sentence transformers
3. Database Storage - Stores vectors with rich metadata in Oracle 23ai vector tables
4. Duplicate Detection - Real-time identification and reporting of duplicate content
5. Chatbot Creation - Builds LLM-powered assistant with semantic relationship awareness
6. Debug Monitoring - Comprehensive logging of retrieval process and content quality
KEY FEATURES:
- Semantic relationship preservation from RDF graphs
- Robust LOB handling for Oracle database compatibility
- Real-time duplicate detection during vector retrieval
- Detailed debug output showing exactly what content is sent to LLM
- Fallback retrieval methods for maximum reliability
- Rich metadata integration for context-aware responses
HOW TO USE:
1. Ensure you have a clean RDF graph file (.nt format)
2. Configure database connection parameters for your Oracle instance
3. Run process_rdf_documents() to build the complete system
4. Use the returned chain for interactive question-answering
5. Monitor debug output to verify no duplicates in retrieval results
OUTPUT:
- Fully functional vector-powered chatbot
- Comprehensive duplicate detection reports during retrieval
- Detailed logs showing content processing and LLM interaction
- Performance statistics and system health indicators
TYPICAL WORKFLOW:
generate clean RDF β process_rdf_documents() β interactive chatbot + monitoring
This system is production-ready and includes all necessary safeguards for handling
duplicate content, LOB issues, and providing transparent debugging information.
Perfect for deploying RDF knowledge graphs as intelligent chatbot applications.
"""
import array
import oracledb
import os
import json
import numpy as np
from rdflib import Graph
from langchain.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores.oraclevs import OracleVS
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
from langchain_nomic import NomicEmbeddings
from langchain.schema import Document
# RDF Graph Configuration
RDF_FILE = "vectorsearchcleanedchunked.nt"
CHUNK_SIZE = 1000 # This matches your RDF chunking
CHUNK_OVERLAP = 20 # Not used since RDF chunks are pre-made
VECTOR_TABLE = "rdf_vector_chunks"
### EMBEDDING MODELS
### HUGGINGFACE
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
VECTOR_DIMENSION = 384
### NOMIC
#EMBEDDING_MODEL = "nomic-embed-text-v1.5"
#VECTOR_DIMENSION = 768
def l2_normalize(vec):
norm = np.linalg.norm(vec)
if norm == 0:
return vec
return vec / norm
def extract_chunks_from_rdf(rdf_file):
"""Extract chunks and their metadata from RDF graph"""
print(f"π Loading RDF graph from {rdf_file}")
# Load the RDF graph
g = Graph()
g.parse(rdf_file, format="nt")
print(f"β Loaded RDF graph with {len(g)} triples")
# SPARQL query to get all chunks with their metadata
chunks_query = """
PREFIX ex: <https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/ai-vector-search-users-guide.pdf#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?chunk_uri ?chunk_text ?chunk_index ?chunk_size ?section_title ?section_content ?word_count
WHERE {
?section_uri dc:title ?section_title .
?section_uri ex:hasWordCount ?word_count .
?section_uri ex:hasContent ?section_content .
?section_uri ex:hasChunk ?chunk_uri .
?chunk_uri ex:hasText ?chunk_text .
?chunk_uri ex:hasChunkIndex ?chunk_index .
?chunk_uri ex:hasChunkSize ?chunk_size .
}
ORDER BY ?section_title ?chunk_index
"""
# Get relationships for each section
relationships_query = """
PREFIX ex: <https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/ai-vector-search-users-guide.pdf#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?section1_title ?relationship ?section2_title
WHERE {
?section1_uri dc:title ?section1_title .
?section2_uri dc:title ?section2_title .
?section1_uri ?relationship ?section2_uri .
FILTER(STRSTARTS(STR(?relationship), STR(ex:)))
FILTER(?relationship != ex:hasHeader && ?relationship != ex:hasChunk &&
?relationship != ex:hasContent && ?relationship != ex:hasText &&
?relationship != ex:hasWordCount && ?relationship != ex:hasCharCount &&
?relationship != ex:hasSummary && ?relationship != ex:hasChunkIndex &&
?relationship != ex:hasChunkSize && ?relationship != ex:belongsToSection)
}
"""
print("π Extracting chunks and metadata...")
# Execute queries
chunk_results = list(g.query(chunks_query))
relationship_results = list(g.query(relationships_query))
# Build relationships map
relationships_map = {}
for row in relationship_results:
section1 = str(row[0])
relationship = str(row[1]).split('#')[-1]
section2 = str(row[2])
if section1 not in relationships_map:
relationships_map[section1] = {}
if relationship not in relationships_map[section1]:
relationships_map[section1][relationship] = []
relationships_map[section1][relationship].append(section2)
# Process chunks
chunks_data = []
for row in chunk_results:
chunk_uri = str(row[0])
chunk_text = str(row[1])
chunk_index = int(row[2])
chunk_size = int(row[3])
section_title = str(row[4])
section_content = str(row[5])
word_count = int(row[6])
# Get relationships for this section
section_relationships = relationships_map.get(section_title, {})
# Create rich metadata
metadata = {
"chunk_uri": chunk_uri,
"chunk_index": chunk_index,
"chunk_size": chunk_size,
"section_title": section_title,
"section_word_count": word_count,
"section_summary": section_content[:200] + "..." if len(section_content) > 200 else section_content,
"relationships": section_relationships,
"source": "Oracle AI Vector Search User Guide",
"document_type": "technical_documentation"
}
# Create Document object (compatible with LangChain)
document = Document(
page_content=chunk_text,
metadata=metadata
)
chunks_data.append(document)
print(f"β
Extracted {len(chunks_data)} chunks from RDF graph")
print(f"π Relationships found: {sum(len(rels) for rels in relationships_map.values())}")
# Show sample chunk
if chunks_data:
sample = chunks_data[0]
print(f"\nπ Sample chunk:")
print(f" Section: {sample.metadata['section_title']}")
print(f" Content: {sample.page_content[:100]}...")
print(f" Relationships: {len(sample.metadata['relationships'])} types")
return chunks_data
def create_enhanced_vector_table(connection, table_name):
"""Create enhanced table with RDF metadata support (OracleVS compatible)"""
print(f"ποΈ Creating enhanced vector table: {table_name}")
with connection.cursor() as cursor:
# First, drop table if it exists to ensure clean state
try:
cursor.execute(f"DROP TABLE {table_name}")
print(f"β Dropped existing table {table_name}")
except:
print(f"π Table {table_name} didn't exist (this is normal for first run)")
# Create the table with exact OracleVS expected schema
cursor.execute(f"""
CREATE TABLE {table_name} (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
embedding VECTOR({VECTOR_DIMENSION}),
text CLOB,
metadata CLOB,
chunk_uri VARCHAR2(500),
chunk_index NUMBER,
chunk_size NUMBER,
section_title VARCHAR2(500),
section_word_count NUMBER,
section_summary CLOB,
relationships CLOB,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT {table_name}_pk PRIMARY KEY (id)
)
""")
print(f"β
Created table {table_name}")
# Verify the table structure
cursor.execute(f"""
SELECT column_name, data_type
FROM user_tab_columns
WHERE table_name = UPPER('{table_name}')
ORDER BY column_id
""")
columns = cursor.fetchall()
print(f"π Table structure verification:")
for col_name, col_type in columns:
print(f" - {col_name}: {col_type}")
# Verify TEXT column exists
text_column_exists = any(col[0] == 'TEXT' for col in columns)
if not text_column_exists:
raise Exception("ERROR: TEXT column was not created properly!")
else:
print(f"β
TEXT column verified")
# Create indexes for better search performance
try:
cursor.execute(f"CREATE INDEX {table_name}_section_idx ON {table_name} (section_title)")
cursor.execute(f"CREATE INDEX {table_name}_chunk_idx ON {table_name} (chunk_index)")
print("β Created performance indexes")
except Exception as e:
print(f"π Index creation note: {e}")
connection.commit()
def insert_rdf_chunks_with_vectors(connection, chunks_data, embeddings_model, table_name):
"""Insert RDF chunks with embeddings and rich metadata"""
print(f"π Processing {len(chunks_data)} chunks for vector insertion...")
# First, verify the table structure before inserting
with connection.cursor() as cursor:
cursor.execute(f"""
SELECT column_name
FROM user_tab_columns
WHERE table_name = UPPER('{table_name}')
AND column_name IN ('TEXT', 'METADATA', 'EMBEDDING')
""")
required_columns = [row[0] for row in cursor.fetchall()]
print(f"π Required columns found: {required_columns}")
if 'TEXT' not in required_columns:
raise Exception(f"CRITICAL: TEXT column missing from {table_name}!")
if 'METADATA' not in required_columns:
raise Exception(f"CRITICAL: METADATA column missing from {table_name}!")
if 'EMBEDDING' not in required_columns:
raise Exception(f"CRITICAL: EMBEDDING column missing from {table_name}!")
# Extract texts for embedding
texts = [chunk.page_content for chunk in chunks_data]
# Generate embeddings
print("π§ Generating embeddings...")
embeddings = embeddings_model.embed_documents(texts)
embeddings = [np.asarray(emb, dtype=np.float32) for emb in embeddings]
# Optionally apply L2 normalization
# embeddings = [l2_normalize(emb) for emb in embeddings]
print(f"β Generated embeddings: {len(embeddings)} x {len(embeddings[0])}")
# Prepare data for insertion
oracle_vectors = [array.array('f', emb) for emb in embeddings]
insert_data = []
for i, (chunk, vector) in enumerate(zip(chunks_data, oracle_vectors)):
metadata = chunk.metadata
# Create enhanced metadata JSON with all RDF information
enhanced_metadata = {
"chunk_uri": metadata['chunk_uri'],
"chunk_index": metadata['chunk_index'],
"chunk_size": metadata['chunk_size'],
"section_title": metadata['section_title'],
"section_word_count": metadata['section_word_count'],
"section_summary": metadata['section_summary'],
"relationships": metadata['relationships'],
"source": metadata.get('source', 'Oracle AI Vector Search User Guide'),
"document_type": metadata.get('document_type', 'technical_documentation')
}
insert_data.append((
vector, # embedding
chunk.page_content, # text (OracleVS expects this column name)
json.dumps(enhanced_metadata), # metadata (JSON string for OracleVS)
metadata['chunk_uri'], # chunk_uri
metadata['chunk_index'], # chunk_index
metadata['chunk_size'], # chunk_size
metadata['section_title'], # section_title
metadata['section_word_count'], # section_word_count
metadata['section_summary'], # section_summary
json.dumps(metadata['relationships']) # relationships (JSON string)
))
# Insert in batches (smaller batches for large datasets)
print("πΎ Inserting chunks into database...")
batch_size = 100 # Process in smaller batches
total_inserted = 0
with connection.cursor() as cursor:
for i in range(0, len(insert_data), batch_size):
batch = insert_data[i:i + batch_size]
try:
cursor.executemany(f"""
INSERT INTO {table_name} (
embedding, text, metadata, chunk_uri, chunk_index, chunk_size,
section_title, section_word_count, section_summary, relationships
) VALUES (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10)
""", batch)
connection.commit()
total_inserted += len(batch)
print(f" β Inserted batch {i//batch_size + 1}: {total_inserted}/{len(insert_data)} chunks")
except Exception as e:
print(f" β Error in batch {i//batch_size + 1}: {e}")
# Try to show the exact SQL being executed
print(f" π Sample data types: {[type(x) for x in batch[0]]}")
raise
print(f"β
Successfully inserted {total_inserted} chunks with vectors")
def create_enhanced_retriever(connection, embeddings_model, table_name):
"""Create enhanced retriever with RDF metadata support and LOB handling"""
print("π Setting up enhanced vector retriever...")
# Create a fresh connection for the vector store to avoid LOB issues
# Connect to ADB
# fresh_connection = oracledb.connect(
# user="admin",
# password="Password",
# dsn="mydb_high",
# config_dir="/Users/dev/Wallets/Wallet_mydb",
# wallet_location="/Users/dev/Wallets/Wallet_mydb",
# wallet_password="Password"
# )
# Connect to local Container
fresh_connection = oracledb.connect(
user="testuser",
password="Password",
dsn="localhost:1521/FREEPDB1"
)
# Custom vector store with metadata support
vector_store = OracleVS(
client=fresh_connection,
embedding_function=embeddings_model,
table_name=table_name,
distance_strategy=DistanceStrategy.COSINE
)
# Enhanced retriever with more results for reranking
retriever = vector_store.as_retriever(search_kwargs={"k": 15})
return retriever, fresh_connection
def create_enhanced_chat_chain(retriever):
"""Create enhanced chat chain with standard retriever"""
print("π€ Setting up enhanced chat chain with standard retrieval...")
llm = ChatOllama(model="llama3.1:latest")
# Enhanced prompt that uses RDF relationships
prompt = ChatPromptTemplate.from_template("""
You are an expert Oracle AI Vector Search assistant. Use the provided context to answer questions accurately and comprehensively.
CONTEXT FROM ORACLE VECTOR SEARCH DOCUMENTATION:
{context}
INSTRUCTIONS:
1. Answer based primarily on the provided context
2. If you see related sections mentioned, reference them naturally
3. Provide practical, actionable information
4. If the context mentions prerequisites or related topics, include those recommendations
5. Use technical terms accurately as they appear in Oracle documentation
QUESTION: {question}
ANSWER:""")
def format_context_with_relationships(docs):
"""Format retrieved documents with relationship information and detect duplicates"""
print(f"\nπ FORMATTING CONTEXT FROM {len(docs)} DOCUMENTS:")
print("=" * 60)
# Duplicate detection
seen_content = {}
unique_docs = []
duplicates_found = 0
for i, doc in enumerate(docs):
content = doc.page_content
content_hash = hash(content[:200]) # Hash first 200 chars for comparison
if content_hash in seen_content:
duplicates_found += 1
original_idx = seen_content[content_hash]
print(f"\nπ DUPLICATE DETECTED:")
print(f" Document {i+1} is duplicate of Document {original_idx+1}")
print(f" Content preview: {content[:100]}...")
continue
else:
seen_content[content_hash] = i
unique_docs.append(doc)
if duplicates_found > 0:
print(f"\nβ οΈ FOUND {duplicates_found} DUPLICATES - Using {len(unique_docs)} unique documents")
else:
print(f"\nβ
NO DUPLICATES FOUND - All {len(docs)} documents are unique")
formatted_context = []
for i, doc in enumerate(unique_docs, 1):
content = doc.page_content
# Extract metadata from the document
try:
if hasattr(doc, 'metadata') and doc.metadata:
metadata = doc.metadata
else:
metadata = {}
except:
metadata = {}
# Add section context
section_title = metadata.get('section_title', 'Unknown Section')
chunk_index = metadata.get('chunk_index', 'Unknown')
chunk_uri = metadata.get('chunk_uri', 'Unknown')
distance = metadata.get('distance', 'Unknown')
print(f"\nπ UNIQUE DOCUMENT {i}:")
print(f" Section: {section_title}")
print(f" Chunk Index: {chunk_index}")
print(f" Chunk URI: {chunk_uri}")
print(f" Similarity Distance: {distance}")
print(f" Content Length: {len(content)} characters")
print(f" Content Preview: {content[:100]}...")
context_part = f"[Section: {section_title}]\n{content}"
# Add relationship hints if available
relationships = metadata.get('relationships', {})
if relationships and isinstance(relationships, dict):
rel_hints = []
for rel_type, related_sections in relationships.items():
if related_sections and isinstance(related_sections, list):
rel_hints.append(f"{rel_type}: {', '.join(related_sections[:2])}")
if rel_hints:
context_part += f"\n[Related: {'; '.join(rel_hints)}]"
print(f" Relationships: {'; '.join(rel_hints)}")
formatted_context.append(context_part)
final_context = "\n\n".join(formatted_context)
print(f"\nπ FINAL CONTEXT STATS:")
print(f" Original documents: {len(docs)}")
print(f" Unique documents: {len(unique_docs)}")
print(f" Duplicates removed: {duplicates_found}")
print(f" Final context length: {len(final_context)} characters")
print("=" * 60)
return final_context
# Build chain with standard retrieval
class StandardChain:
def __init__(self, retriever, prompt, llm, formatter):
self.retriever = retriever
self.prompt = prompt
self.llm = llm
self.formatter = formatter
def invoke(self, input_dict):
question = input_dict["question"]
print(f"\nπ PROCESSING QUESTION: {question}")
print("-" * 60)
docs = self.retriever.invoke(question)
# Check if we actually retrieved any documents
if not docs:
print("β NO DOCUMENTS RETRIEVED - CANNOT ANSWER")
return "β I couldn't find any relevant information in the Oracle Vector Search documentation to answer your question. This might be due to technical issues with data retrieval. Please try rephrasing your question or check the system logs."
print(f"β
RETRIEVED {len(docs)} DOCUMENTS FOR CONTEXT")
context = self.formatter(docs)
# Add a note about how many documents were used
context_header = f"[Found {len(docs)} relevant sections from Oracle Vector Search documentation]\n\n"
full_context = context_header + context
print(f"\nπ€ SENDING TO LLM:")
print(f" Question: {question}")
print(f" Context Length: {len(full_context)} characters")
print(f" Context Preview (first 300 chars):")
print(f" {full_context[:300]}...")
print("-" * 60)
prompt_value = self.prompt.format(context=full_context, question=question)
print(f"\nπ€ FULL PROMPT BEING SENT TO LLM:")
print("=" * 80)
print(prompt_value)
print("=" * 80)
response = self.llm.invoke(prompt_value)
final_answer = response.content if hasattr(response, 'content') else str(response)
print(f"\nβ
LLM RESPONSE RECEIVED:")
print(f" Response Length: {len(final_answer)} characters")
print(f" Response Preview: {final_answer[:200]}...")
return final_answer
return StandardChain(retriever, prompt, llm, format_context_with_relationships)
def create_robust_retriever(connection, embeddings_model, table_name):
"""Create a more robust retriever that handles LOB issues"""
print("π Setting up robust vector retriever...")
def robust_similarity_search(query, k=10):
"""Custom similarity search that avoids LOB issues entirely"""
try:
# Generate query embedding
query_embedding = embeddings_model.embed_query(query)
query_vector = array.array('f', np.asarray(query_embedding, dtype=np.float32))
# Two-step approach to avoid LOB issues:
# Step 1: Get IDs and distances only
with connection.cursor() as cursor:
cursor.execute(f"""
SELECT
id,
section_title,
VECTOR_DISTANCE(embedding, :embedding, COSINE) as distance
FROM {table_name}
ORDER BY VECTOR_DISTANCE(embedding, :embedding, COSINE)
FETCH FIRST :k ROWS ONLY
""", {
'embedding': query_vector,
'k': k
})
id_distance_pairs = cursor.fetchall()
print(f"β Found {len(id_distance_pairs)} similar chunks")
# Step 2: Get text content for each ID separately
results = []
for doc_id, section_title, distance in id_distance_pairs:
try:
with connection.cursor() as text_cursor:
# Read CLOB content properly to avoid LOB object issues
text_cursor.execute(f"""
SELECT
DBMS_LOB.SUBSTR(text, 4000, 1) as text_content,
chunk_uri,
chunk_index,
chunk_size,
section_word_count
FROM {table_name}
WHERE id = :doc_id
""", {'doc_id': doc_id})
text_row = text_cursor.fetchone()
if text_row:
text_content, chunk_uri, chunk_index, chunk_size, section_word_count = text_row
# Create simplified metadata (avoid JSON parsing of LOB)
metadata = {
'section_title': section_title,
'chunk_uri': chunk_uri or f"chunk_{doc_id}",
'chunk_index': chunk_index or 0,
'chunk_size': chunk_size or len(text_content),
'section_word_count': section_word_count or 0,
'distance': float(distance),
'relationships': {} # Empty for now to avoid LOB issues
}
# Create Document object
doc = Document(
page_content=text_content,
metadata=metadata
)
results.append(doc)
except Exception as e:
print(f"β οΈ Skipped chunk {doc_id}: {e}")
continue
print(f"β Successfully retrieved {len(results)} documents for query: '{query[:50]}...'")
return results
except Exception as e:
print(f"β Error in similarity search: {e}")
# Return empty list instead of failing completely
return []
return robust_similarity_search
def create_enhanced_chat_chain_robust(retriever_func):
"""Create enhanced chat chain with robust retriever function"""
print("π€ Setting up enhanced chat chain with robust retrieval...")
llm = ChatOllama(model="llama3.1:latest")
# Enhanced prompt that uses RDF relationships
prompt = ChatPromptTemplate.from_template("""
You are an expert Oracle AI Vector Search assistant. Use the provided context to answer questions accurately and comprehensively.
CONTEXT FROM ORACLE VECTOR SEARCH DOCUMENTATION:
{context}
INSTRUCTIONS:
1. Answer based primarily on the provided context
2. If you see related sections mentioned, reference them naturally
3. Provide practical, actionable information
4. If the context mentions prerequisites or related topics, include those recommendations
5. Use technical terms accurately as they appear in Oracle documentation
QUESTION: {question}
ANSWER:""")
def format_context_with_relationships(docs):
"""Format retrieved documents with relationship information and detect duplicates"""
print(f"\nπ FORMATTING CONTEXT FROM {len(docs)} DOCUMENTS:")
print("=" * 60)
# Duplicate detection
seen_content = {}
unique_docs = []
duplicates_found = 0
for i, doc in enumerate(docs):
content = doc.page_content
content_hash = hash(content[:200]) # Hash first 200 chars for comparison
if content_hash in seen_content:
duplicates_found += 1
original_idx = seen_content[content_hash]
print(f"\nπ DUPLICATE DETECTED:")
print(f" Document {i+1} is duplicate of Document {original_idx+1}")
print(f" Content preview: {content[:100]}...")
continue
else:
seen_content[content_hash] = i
unique_docs.append(doc)
if duplicates_found > 0:
print(f"\nβ οΈ FOUND {duplicates_found} DUPLICATES - Using {len(unique_docs)} unique documents")
else:
print(f"\nβ
NO DUPLICATES FOUND - All {len(docs)} documents are unique")
formatted_context = []
for i, doc in enumerate(unique_docs, 1):
content = doc.page_content
# Extract metadata from the document
try:
if hasattr(doc, 'metadata') and doc.metadata:
metadata = doc.metadata
else:
metadata = {}
except:
metadata = {}
# Add section context
section_title = metadata.get('section_title', 'Unknown Section')
chunk_index = metadata.get('chunk_index', 'Unknown')
chunk_uri = metadata.get('chunk_uri', 'Unknown')
distance = metadata.get('distance', 'Unknown')
print(f"\nπ UNIQUE DOCUMENT {i}:")
print(f" Section: {section_title}")
print(f" Chunk Index: {chunk_index}")
print(f" Chunk URI: {chunk_uri}")
print(f" Similarity Distance: {distance}")
print(f" Content Length: {len(content)} characters")
print(f" Content Preview: {content[:100]}...")
context_part = f"[Section: {section_title}]\n{content}"
# Add relationship hints if available
relationships = metadata.get('relationships', {})
if relationships and isinstance(relationships, dict):
rel_hints = []
for rel_type, related_sections in relationships.items():
if related_sections and isinstance(related_sections, list):
rel_hints.append(f"{rel_type}: {', '.join(related_sections[:2])}")
if rel_hints:
context_part += f"\n[Related: {'; '.join(rel_hints)}]"
print(f" Relationships: {'; '.join(rel_hints)}")
formatted_context.append(context_part)
final_context = "\n\n".join(formatted_context)
print(f"\nπ FINAL CONTEXT STATS:")
print(f" Original documents: {len(docs)}")
print(f" Unique documents: {len(unique_docs)}")
print(f" Duplicates removed: {duplicates_found}")
print(f" Final context length: {len(final_context)} characters")
print("=" * 60)
return final_context
# Build chain with robust retrieval
class RobustChain:
def __init__(self, retriever_func, prompt, llm, formatter):
self.retriever_func = retriever_func
self.prompt = prompt
self.llm = llm
self.formatter = formatter
def invoke(self, input_dict):
question = input_dict["question"]
print(f"\nπ PROCESSING QUESTION: {question}")
print("-" * 60)
docs = self.retriever_func(question, k=10)
# Check if we actually retrieved any documents
if not docs:
print("β NO DOCUMENTS RETRIEVED - CANNOT ANSWER")
return "β I couldn't find any relevant information in the Oracle Vector Search documentation to answer your question. This might be due to technical issues with data retrieval. Please try rephrasing your question or check the system logs."
print(f"β
RETRIEVED {len(docs)} DOCUMENTS FOR CONTEXT")
context = self.formatter(docs)
# Add a note about how many documents were used
context_header = f"[Found {len(docs)} relevant sections from Oracle Vector Search documentation]\n\n"
full_context = context_header + context
print(f"\nπ€ SENDING TO LLM:")
print(f" Question: {question}")
print(f" Context Length: {len(full_context)} characters")
print(f" Context Preview (first 300 chars):")
print(f" {full_context[:300]}...")
print("-" * 60)
prompt_value = self.prompt.format(context=full_context, question=question)
print(f"\nπ€ FULL PROMPT BEING SENT TO LLM:")
print("=" * 80)
print(prompt_value)
print("=" * 80)
response = self.llm.invoke(prompt_value)
final_answer = response.content if hasattr(response, 'content') else str(response)
print(f"\nβ
LLM RESPONSE RECEIVED:")
print(f" Response Length: {len(final_answer)} characters")
print(f" Response Preview: {final_answer[:200]}...")
return final_answer
return RobustChain(retriever_func, prompt, llm, format_context_with_relationships)
# Add this alternative method to the main function
def process_rdf_documents():
"""Main function to process RDF graph and create vector chatbot"""
print("π STARTING RDF-POWERED VECTOR CHATBOT SETUP")
print("=" * 60)
# Connect to Oracle
print("π Connecting to Oracle Database...")
# Connect to ADB
# connection = oracledb.connect(
# user="admin",
# password="Password",
# dsn="mydb_high",
# config_dir="/Users/dev/Wallets/Wallet_mydb",
# wallet_location="/Users/dev/Wallets/Wallet_mydb",
# wallet_password="Password"
# )
# Connect to local Container
connection = oracledb.connect(
user="testuser",
password="Password",
dsn="localhost:1521/FREEPDB1"
)
print("β
Connected to Oracle Database")
try:
# Extract chunks from RDF
chunks_data = extract_chunks_from_rdf(RDF_FILE)
# Set up embedding model
print("π§ Initializing embedding model...")
embeddings_model = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
print(f"β
Using {EMBEDDING_MODEL}")
# Create enhanced table
create_enhanced_vector_table(connection, VECTOR_TABLE)
# Insert chunks with vectors and metadata
insert_rdf_chunks_with_vectors(connection, chunks_data, embeddings_model, VECTOR_TABLE)
# Try both retrieval methods
print("\nπ Setting up retrieval methods...")
# Method 1: Try OracleVS (might have LOB issues)
try:
retriever, retriever_connection = create_enhanced_retriever(connection, embeddings_model, VECTOR_TABLE)
chain = create_enhanced_chat_chain(retriever)
print("β
OracleVS retriever created successfully")
use_robust = False
except Exception as e:
print(f"β οΈ OracleVS retriever failed: {e}")
use_robust = True
# Method 2: Robust custom retriever (handles LOB issues)
if use_robust:
print("π Using robust custom retriever...")
robust_retriever = create_robust_retriever(connection, embeddings_model, VECTOR_TABLE)
chain = create_enhanced_chat_chain_robust(robust_retriever)
retriever_connection = connection
# Test the system
print("\n" + "=" * 60)
print("π§ͺ TESTING RDF-POWERED CHATBOT")
print("=" * 60)
# test_questions = [
# "What are Vector Indexes?",
# "How do I create vector embeddings?",
# "What is the relationship between vectors and similarity search?",
# "What are the performance considerations for vector indexes?"
# ]
test_questions = [
"What are Vector Indexes?",
"What are the different index types I can use?",
"What is a Vector embedding?"
]
for i, question in enumerate(test_questions):
print(f"\nβ QUESTION {i+1}: {question}")
print("-" * 50)
try:
answer = chain.invoke({"question": question})
print(f"π€ ANSWER: {answer}")
except Exception as e:
print(f"β Error answering question: {e}")
print("π This might be a temporary issue, trying to continue...")
print("-" * 50)
print(f"\nπ SUCCESS! RDF-powered vector chatbot is ready!")
print(f"π Database table: {VECTOR_TABLE}")
print(f"π Total chunks processed: {len(chunks_data)}")
print(f"π§ Using robust retriever: {use_robust}")
# Return both connections
return chain, connection, retriever_connection
except Exception as e:
print(f"β Error: {e}")
connection.close()
raise
if __name__ == "__main__":
chain, connection, retriever_connection = process_rdf_documents()
print(f"\nπ‘ Interactive Mode:")
print(f"Use: answer = chain.invoke({{'question': 'your question here'}})")
print(f"Main connection available as 'connection' variable")
print(f"Retriever connection available as 'retriever_connection' variable")
print(f"\nβ οΈ Note: If you get LOB errors, the system will try to continue with other questions.")