-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkb_agent_workflow.py
More file actions
executable file
·2043 lines (1693 loc) · 83.6 KB
/
kb_agent_workflow.py
File metadata and controls
executable file
·2043 lines (1693 loc) · 83.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
#!/usr/bin/env python3
"""
KB Agent Workflow Demo
This script demonstrates a multi-agent workflow that integrates:
- Polymorphic prompts
- Knowledge bases
- Facts database
- Multiple specialized agents
The workflow performs a research and analysis task across domains.
"""
import os
import sys
import json
import time
import argparse
import sqlite3
import logging
from typing import Dict, List, Any, Tuple, Optional, Union
import yaml
import numpy as np
from dataclasses import dataclass, field, asdict
from datetime import datetime
from uuid import uuid4
import traceback
# Import our custom modules
from embedding_service import EmbeddingServiceClient, compute_embedding
from advanced_polymorphic_prompts import AdvancedPromptManager, Prompt, PromptChain
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s')
logger = logging.getLogger("kb-agent-workflow")
# Check for the holographic_memory module for vector database operations
try:
from holographic_memory import HolographicMemoryDB
has_holographic = True
except ImportError:
has_holographic = False
logger.warning("Warning: HolographicMemoryDB not available. Using simplified vector storage.")
class EmbeddingDBStorage:
"""SQLite-based embedding storage with vector search capability"""
def __init__(self, db_path: str):
"""Initialize the embedding database storage"""
self.db_path = db_path
os.makedirs(os.path.dirname(db_path), exist_ok=True)
self._initialize_db()
self.embedding_client = EmbeddingServiceClient()
def _initialize_db(self):
"""Initialize the SQLite database with necessary tables"""
try:
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
# Create knowledge_items table
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS knowledge_items (
id TEXT PRIMARY KEY,
title TEXT,
content TEXT NOT NULL,
source TEXT,
domain TEXT,
created_at REAL,
access_count INTEGER DEFAULT 0
)
''')
# Create embeddings table
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS embeddings (
id TEXT PRIMARY KEY,
knowledge_id TEXT NOT NULL,
vector BLOB NOT NULL,
FOREIGN KEY (knowledge_id) REFERENCES knowledge_items(id)
)
''')
# Create tags table
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL
)
''')
# Create knowledge_tags table (many-to-many)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS knowledge_tags (
knowledge_id TEXT NOT NULL,
tag_id INTEGER NOT NULL,
PRIMARY KEY (knowledge_id, tag_id),
FOREIGN KEY (knowledge_id) REFERENCES knowledge_items(id),
FOREIGN KEY (tag_id) REFERENCES tags(id)
)
''')
# Add index for faster vector search
self.cursor.execute('CREATE INDEX IF NOT EXISTS idx_knowledge_domain ON knowledge_items(domain)')
self.cursor.execute('CREATE INDEX IF NOT EXISTS idx_embeddings_knowledge ON embeddings(knowledge_id)')
self.conn.commit()
logger.info(f"Database initialized at {self.db_path}")
except Exception as e:
logger.error(f"Database initialization error: {e}")
if hasattr(self, 'conn') and self.conn:
self.conn.close()
raise
def add_knowledge(self, title: str, content: str, metadata: Dict = None, tags: List[str] = None):
"""Add knowledge to the database with embedding"""
metadata = metadata or {}
tags = tags or []
try:
# Generate a unique ID
knowledge_id = str(uuid4())
# Extract metadata fields
source = metadata.get('source', 'unknown')
domain = metadata.get('domain', 'general')
# Insert knowledge item
self.cursor.execute(
'INSERT INTO knowledge_items (id, title, content, source, domain, created_at) '
'VALUES (?, ?, ?, ?, ?, ?)',
(knowledge_id, title, content, source, domain, time.time())
)
# Generate and store embedding
try:
embedding = self.embedding_client.embed_text(content)
embedding_id = str(uuid4())
# Convert embedding to bytes for storage
embedding_bytes = np.array(embedding, dtype=np.float32).tobytes()
# Store embedding
self.cursor.execute(
'INSERT INTO embeddings (id, knowledge_id, vector) VALUES (?, ?, ?)',
(embedding_id, knowledge_id, embedding_bytes)
)
except Exception as e:
logger.warning(f"Error generating embedding: {e}")
# Process tags
for tag in tags:
# Insert tag if not exists
self.cursor.execute(
'INSERT OR IGNORE INTO tags (name) VALUES (?)',
(tag,)
)
# Get tag ID
self.cursor.execute('SELECT id FROM tags WHERE name = ?', (tag,))
tag_id = self.cursor.fetchone()[0]
# Link knowledge to tag
self.cursor.execute(
'INSERT INTO knowledge_tags (knowledge_id, tag_id) VALUES (?, ?)',
(knowledge_id, tag_id)
)
self.conn.commit()
return knowledge_id
except Exception as e:
self.conn.rollback()
logger.error(f"Error adding knowledge: {e}")
return None
def batch_add_knowledge(self, items: List[Dict]):
"""Add multiple knowledge items in batch with optimized embedding generation"""
if not items:
return []
try:
# Extract titles and contents for batch embedding
titles = [item.get('title', f"Item_{i}") for i, item in enumerate(items)]
contents = [item['content'] for item in items if 'content' in item]
# Generate embeddings in batch
try:
results = self.embedding_client.embed_batch(contents)
embeddings = results
except Exception as e:
logger.warning(f"Error in batch embedding: {e}")
embeddings = [None] * len(contents)
# Begin transaction
self.conn.execute("BEGIN TRANSACTION")
knowledge_ids = []
# Insert each knowledge item
for i, item in enumerate(items):
if 'content' not in item:
logger.warning(f"Skipping item without content: {item}")
continue
# Generate a unique ID
knowledge_id = str(uuid4())
knowledge_ids.append(knowledge_id)
# Extract fields
content = item['content']
title = item.get('title', f"Item_{i}")
metadata = item.get('metadata', {})
tags = item.get('tags', [])
source = metadata.get('source', 'unknown')
domain = metadata.get('domain', 'general')
# Insert knowledge item
self.cursor.execute(
'INSERT INTO knowledge_items (id, title, content, source, domain, created_at) '
'VALUES (?, ?, ?, ?, ?, ?)',
(knowledge_id, title, content, source, domain, time.time())
)
# Store embedding if available
if i < len(embeddings) and embeddings[i] is not None:
embedding = embeddings[i]
embedding_id = str(uuid4())
# Convert embedding to bytes for storage
embedding_bytes = np.array(embedding, dtype=np.float32).tobytes()
# Store embedding
self.cursor.execute(
'INSERT INTO embeddings (id, knowledge_id, vector) VALUES (?, ?, ?)',
(embedding_id, knowledge_id, embedding_bytes)
)
# Process tags
for tag in tags:
# Insert tag if not exists
self.cursor.execute(
'INSERT OR IGNORE INTO tags (name) VALUES (?)',
(tag,)
)
# Get tag ID
self.cursor.execute('SELECT id FROM tags WHERE name = ?', (tag,))
tag_id = self.cursor.fetchone()[0]
# Link knowledge to tag
self.cursor.execute(
'INSERT INTO knowledge_tags (knowledge_id, tag_id) VALUES (?, ?)',
(knowledge_id, tag_id)
)
self.conn.commit()
return knowledge_ids
except Exception as e:
self.conn.rollback()
logger.error(f"Error in batch adding knowledge: {e}")
return []
def search(self, query: str, top_k: int = 5, domain: str = None, tags: List[str] = None):
"""Search knowledge using vector similarity"""
try:
# Generate embedding for query
query_embedding = np.array(self.embedding_client.embed_text(query), dtype=np.float32)
# Build a dynamic SQL query based on filters
sql_filters = []
sql_params = []
join_clause = ""
# Filter by domain if specified
if domain:
sql_filters.append("k.domain = ?")
sql_params.append(domain)
# Filter by tags if specified
if tags and len(tags) > 0:
placeholders = ", ".join(["?"] * len(tags))
join_clause = """
JOIN knowledge_tags kt ON k.id = kt.knowledge_id
JOIN tags t ON kt.tag_id = t.id
"""
sql_filters.append(f"t.name IN ({placeholders})")
sql_params.extend(tags)
# Build where clause
where_clause = ""
if sql_filters:
where_clause = "WHERE " + " AND ".join(sql_filters)
# Get all embeddings with their knowledge items
query = f"""
SELECT
e.vector,
k.id,
k.title,
k.content,
k.source,
k.domain,
k.created_at,
k.access_count
FROM embeddings e
JOIN knowledge_items k ON e.knowledge_id = k.id
{join_clause}
{where_clause}
GROUP BY k.id
"""
self.cursor.execute(query, sql_params)
rows = self.cursor.fetchall()
# Calculate similarities
results = []
for row in rows:
vector_bytes = row[0]
knowledge_id = row[1]
title = row[2]
content = row[3]
source = row[4]
domain = row[5]
created_at = row[6]
access_count = row[7]
# Convert bytes to vector
vector = np.frombuffer(vector_bytes, dtype=np.float32)
# Calculate cosine similarity
similarity = self._cosine_similarity(query_embedding, vector)
# Get tags for this knowledge item
self.cursor.execute("""
SELECT t.name FROM tags t
JOIN knowledge_tags kt ON t.id = kt.tag_id
WHERE kt.knowledge_id = ?
""", (knowledge_id,))
item_tags = [tag[0] for tag in self.cursor.fetchall()]
# Add to results
results.append({
"id": knowledge_id,
"title": title,
"content": content,
"similarity": float(similarity),
"source": source,
"domain": domain,
"created_at": created_at,
"access_count": access_count,
"tags": item_tags
})
# Sort by similarity (highest first)
results.sort(key=lambda x: x["similarity"], reverse=True)
# Update access counts for returned items
for result in results[:top_k]:
self.cursor.execute(
'UPDATE knowledge_items SET access_count = access_count + 1 WHERE id = ?',
(result["id"],)
)
result["access_count"] += 1
self.conn.commit()
# Return top results
return results[:top_k]
except Exception as e:
logger.error(f"Error searching knowledge: {e}")
# Fallback to basic keyword search if vector search fails
return self._keyword_search(query, top_k, domain, tags)
def _keyword_search(self, query: str, top_k: int = 5, domain: str = None, tags: List[str] = None):
"""Fallback keyword-based search"""
try:
# Split query into terms
query_terms = query.lower().split()
# Build SQL query with filters
sql_filters = []
sql_params = []
join_clause = ""
# Always add LIKE conditions for each term
for term in query_terms:
sql_filters.append("(LOWER(k.title) LIKE ? OR LOWER(k.content) LIKE ?)")
sql_params.extend([f"%{term}%", f"%{term}%"])
# Filter by domain if specified
if domain:
sql_filters.append("k.domain = ?")
sql_params.append(domain)
# Filter by tags if specified
if tags and len(tags) > 0:
placeholders = ", ".join(["?"] * len(tags))
join_clause = """
JOIN knowledge_tags kt ON k.id = kt.knowledge_id
JOIN tags t ON kt.tag_id = t.id
"""
sql_filters.append(f"t.name IN ({placeholders})")
sql_params.extend(tags)
# Build where clause
where_clause = "WHERE " + " AND ".join(sql_filters)
# Get knowledge items matching the query terms
query = f"""
SELECT
k.id,
k.title,
k.content,
k.source,
k.domain,
k.created_at,
k.access_count
FROM knowledge_items k
{join_clause}
{where_clause}
GROUP BY k.id
"""
self.cursor.execute(query, sql_params)
rows = self.cursor.fetchall()
# Calculate relevance scores and build results
results = []
for row in rows:
knowledge_id = row[0]
title = row[1]
content = row[2]
source = row[3]
domain = row[4]
created_at = row[5]
access_count = row[6]
# Calculate relevance score based on term frequency
title_lower = title.lower()
content_lower = content.lower()
score = sum(title_lower.count(term) * 3 + content_lower.count(term) for term in query_terms)
# Get tags for this knowledge item
self.cursor.execute("""
SELECT t.name FROM tags t
JOIN knowledge_tags kt ON t.id = kt.tag_id
WHERE kt.knowledge_id = ?
""", (knowledge_id,))
item_tags = [tag[0] for tag in self.cursor.fetchall()]
# Add to results
results.append({
"id": knowledge_id,
"title": title,
"content": content,
"similarity": score / (10 * len(query_terms)), # Normalize to approximate similarity score
"source": source,
"domain": domain,
"created_at": created_at,
"access_count": access_count,
"tags": item_tags
})
# Sort by score (highest first)
results.sort(key=lambda x: x["similarity"], reverse=True)
# Update access counts for returned items
for result in results[:top_k]:
self.cursor.execute(
'UPDATE knowledge_items SET access_count = access_count + 1 WHERE id = ?',
(result["id"],)
)
result["access_count"] += 1
self.conn.commit()
# Return top results
return results[:top_k]
except Exception as e:
logger.error(f"Error in keyword search: {e}")
return []
def _cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
"""Calculate cosine similarity between two vectors"""
dot_product = np.dot(vec1, vec2)
norm1 = np.linalg.norm(vec1)
norm2 = np.linalg.norm(vec2)
if norm1 == 0 or norm2 == 0:
return 0.0
return dot_product / (norm1 * norm2)
def load_from_directory(self, directory: str, chunk_size: int = 1000, batch_size: int = 10):
"""Load knowledge from a directory of JSON files with batch processing"""
if not os.path.exists(directory):
logger.error(f"Directory {directory} does not exist")
return 0
count = 0
batch = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.json'):
file_path = os.path.join(root, file)
try:
with open(file_path, 'r') as f:
content = json.load(f)
title = content.get('title', os.path.splitext(file)[0])
text = json.dumps(content, ensure_ascii=False)
# Determine domain from path or content
domain_parts = file_path.split(os.sep)[-2:] # Use last two directory components
domain = domain_parts[0] if len(domain_parts) > 1 else "general"
# Add to batch
if len(text) > chunk_size:
# Split into chunks if needed
chunks = self._chunk_text(text, chunk_size)
for i, chunk in enumerate(chunks):
batch.append({
'title': f"{title}_chunk_{i+1}",
'content': chunk,
'metadata': {'source': file_path, 'domain': domain},
'tags': [domain, 'chunked']
})
else:
batch.append({
'title': title,
'content': text,
'metadata': {'source': file_path, 'domain': domain},
'tags': [domain]
})
# Process batch if it reaches the batch size
if len(batch) >= batch_size:
self.batch_add_knowledge(batch)
count += len(batch)
logger.info(f"Processed {count} items...")
batch = []
except Exception as e:
logger.error(f"Error processing {file_path}: {e}")
# Process any remaining items
if batch:
self.batch_add_knowledge(batch)
count += len(batch)
logger.info(f"Finished loading {count} knowledge items from {directory}")
return count
def _chunk_text(self, text: str, chunk_size: int) -> List[str]:
"""Split text into chunks of approximately chunk_size characters"""
words = text.split()
chunks = []
current_chunk = []
current_length = 0
for word in words:
word_length = len(word) + 1 # +1 for the space
if current_length + word_length > chunk_size and current_chunk:
chunks.append(" ".join(current_chunk))
current_chunk = [word]
current_length = word_length
else:
current_chunk.append(word)
current_length += word_length
if current_chunk:
chunks.append(" ".join(current_chunk))
return chunks
def get_stats(self):
"""Get statistics about the knowledge base"""
try:
# Get count of knowledge items
self.cursor.execute("SELECT COUNT(*) FROM knowledge_items")
knowledge_count = self.cursor.fetchone()[0]
# Get count of embeddings
self.cursor.execute("SELECT COUNT(*) FROM embeddings")
embedding_count = self.cursor.fetchone()[0]
# Get count of tags
self.cursor.execute("SELECT COUNT(*) FROM tags")
tag_count = self.cursor.fetchone()[0]
# Get domains and their counts
self.cursor.execute("""
SELECT domain, COUNT(*) as count
FROM knowledge_items
GROUP BY domain
ORDER BY count DESC
""")
domains = dict(self.cursor.fetchall())
# Get popular tags
self.cursor.execute("""
SELECT t.name, COUNT(kt.knowledge_id) as count
FROM tags t
JOIN knowledge_tags kt ON t.id = kt.tag_id
GROUP BY t.name
ORDER BY count DESC
LIMIT 10
""")
popular_tags = dict(self.cursor.fetchall())
return {
"knowledge_count": knowledge_count,
"embedding_count": embedding_count,
"tag_count": tag_count,
"domains": domains,
"popular_tags": popular_tags
}
except Exception as e:
logger.error(f"Error getting stats: {e}")
return {
"knowledge_count": 0,
"embedding_count": 0,
"tag_count": 0,
"domains": {},
"popular_tags": {}
}
def close(self):
"""Close the database connection"""
if hasattr(self, 'conn') and self.conn:
self.conn.close()
class KnowledgeConnector:
"""Connector for knowledge bases using vector search"""
def __init__(self, kb_type: str, connection_params: Dict[str, Any]):
self.kb_type = kb_type
self.connection_params = connection_params
self.embedding_client = EmbeddingServiceClient()
if kb_type == "vector":
db_path = connection_params.get("path", "./kb_vector.db")
self.db = EmbeddingDBStorage(db_path)
else:
raise ValueError(f"Unsupported KB type: {kb_type}")
def initialize_from_directory(self, directory: str, chunk_size: int = 1000):
"""Initialize the knowledge base from a directory of JSON files"""
logger.info(f"Initializing knowledge base from {directory}")
if not os.path.exists(directory):
logger.error(f"Directory {directory} does not exist")
return
# Use batch loading
count = self.db.load_from_directory(directory, chunk_size=chunk_size, batch_size=20)
logger.info(f"Finished initializing knowledge base with {count} items")
def add_knowledge(self, key: str, text: str, metadata: Dict = None):
"""Add knowledge to the vector database with embeddings"""
try:
# Extract domain from metadata
domain = metadata.get('domain', 'general') if metadata else 'general'
source = metadata.get('source', 'user') if metadata else 'user'
# Extract tags if any
tags = metadata.get('tags', []) if metadata else []
if domain and domain not in tags:
tags.append(domain)
# Add to database
self.db.add_knowledge(
title=key,
content=text,
metadata={'source': source, 'domain': domain},
tags=tags
)
return True
except Exception as e:
logger.error(f"Error adding knowledge: {e}")
return False
def query(self, query: str, top_k: int = 5, domain: str = None, tags: List[str] = None):
"""Query the knowledge base for relevant information"""
try:
# Search the database
results = self.db.search(
query=query,
top_k=top_k,
domain=domain,
tags=tags
)
# Format results
formatted_results = []
for result in results:
formatted_results.append({
"id": result["id"],
"title": result["title"],
"similarity": result["similarity"],
"text": result["content"],
"metadata": {
"source": result["source"],
"domain": result["domain"],
"tags": result["tags"],
"created_at": result["created_at"],
"access_count": result["access_count"]
}
})
return formatted_results
except Exception as e:
logger.error(f"Error querying knowledge base: {e}")
return []
def get_stats(self):
"""Get statistics about the knowledge base"""
return self.db.get_stats()
def close(self):
"""Close the knowledge base connection"""
if hasattr(self, 'db') and hasattr(self.db, 'close'):
self.db.close()
class SimplifiedVectorDB:
"""Simple vector database when holographic_memory is not available"""
def __init__(self, db_path: str):
self.db_path = db_path
self.vectors = {}
self.load()
def load(self):
try:
if os.path.exists(self.db_path):
with open(self.db_path, 'r') as f:
self.vectors = json.load(f)
except Exception as e:
logger.error(f"Error loading vector DB: {e}")
self.vectors = {}
def save(self):
try:
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
with open(self.db_path, 'w') as f:
json.dump(self.vectors, f)
except Exception as e:
logger.error(f"Error saving vector DB: {e}")
def add_vector(self, key: str, vector: List[float], metadata: Dict = None):
self.vectors[key] = {
"vector": vector,
"metadata": metadata or {}
}
self.save()
def search(self, query_vector: List[float], top_k: int = 5) -> List[Tuple[str, float, Dict]]:
if not self.vectors:
return []
results = []
for key, data in self.vectors.items():
similarity = self._cosine_similarity(query_vector, data["vector"])
results.append((key, similarity, data["metadata"]))
# Sort by similarity (descending)
results.sort(key=lambda x: x[1], reverse=True)
return results[:top_k]
def _cosine_similarity(self, vec1: List[float], vec2: List[float]) -> float:
"""Calculate cosine similarity between two vectors"""
vec1_array = np.array(vec1)
vec2_array = np.array(vec2)
dot_product = np.dot(vec1_array, vec2_array)
norm1 = np.linalg.norm(vec1_array)
norm2 = np.linalg.norm(vec2_array)
if norm1 == 0 or norm2 == 0:
return 0.0
return dot_product / (norm1 * norm2)
@dataclass
class Fact:
"""A fact with metadata and confidence"""
id: str = field(default_factory=lambda: str(uuid4()))
content: str = ""
source: str = ""
confidence: float = 0.5
domain: str = ""
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
supporting_facts: List[str] = field(default_factory=list)
contradicting_facts: List[str] = field(default_factory=list)
def to_dict(self):
return asdict(self)
class FactsDatabase:
"""Database for storing and retrieving facts"""
def __init__(self, db_path: str):
self.db_path = db_path
self.facts = {}
self.embedding_client = EmbeddingServiceClient()
self.vector_db = SimplifiedVectorDB(f"{os.path.splitext(db_path)[0]}_vectors.json")
self.load()
def load(self):
"""Load facts from database file"""
try:
if os.path.exists(self.db_path):
with open(self.db_path, 'r') as f:
facts_data = json.load(f)
self.facts = {}
for fact_id, fact_data in facts_data.items():
# Convert dict to Fact
self.facts[fact_id] = Fact(**fact_data)
else:
self.facts = {}
except Exception as e:
logger.error(f"Error loading facts DB: {e}")
self.facts = {}
def save(self):
"""Save facts to database file"""
try:
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
facts_data = {}
for fact_id, fact in self.facts.items():
facts_data[fact_id] = fact.to_dict()
with open(self.db_path, 'w') as f:
json.dump(facts_data, f, indent=2)
except Exception as e:
logger.error(f"Error saving facts DB: {e}")
def add_fact(self, content: str, source: str, confidence: float = 0.5, domain: str = None) -> Fact:
"""Add a new fact to the database"""
# Check for duplicate or contradicting facts
existing_fact = self.find_similar_fact(content)
if existing_fact:
# If existing fact has higher confidence, keep it
if existing_fact.confidence >= confidence:
return existing_fact
# Update existing fact with higher confidence
existing_fact.confidence = confidence
existing_fact.source = source
existing_fact.timestamp = datetime.now().isoformat()
if domain:
existing_fact.domain = domain
# Update vector DB
self._update_fact_embedding(existing_fact)
self.save()
return existing_fact
# Create new fact
fact = Fact(
content=content,
source=source,
confidence=confidence,
domain=domain or ""
)
# Add to database
self.facts[fact.id] = fact
# Add to vector DB
self._update_fact_embedding(fact)
self.save()
return fact
def find_similar_fact(self, content: str, threshold: float = 0.9) -> Optional[Fact]:
"""Find a fact that's similar to the given content"""
try:
# Generate embedding for content
content_embedding = self.embedding_client.embed_text(content)
# Search for similar facts
results = self.vector_db.search(content_embedding, top_k=1)
if results and results[0][1] >= threshold:
fact_id = results[0][0]
return self.facts.get(fact_id)
return None
except Exception as e:
logger.error(f"Error finding similar fact: {e}")
return None
def query_facts(self, query: str, confidence_threshold: float = 0.5, top_k: int = 5) -> List[Fact]:
"""Query facts database for facts relevant to the query"""
try:
# Generate embedding for query
query_embedding = self.embedding_client.embed_text(query)
# Search for relevant facts
results = self.vector_db.search(query_embedding, top_k=top_k*2) # Get extra to filter by confidence
# Filter by confidence and get fact objects
facts = []
for fact_id, similarity, _ in results:
fact = self.facts.get(fact_id)
if fact and fact.confidence >= confidence_threshold:
facts.append(fact)
return facts[:top_k]
except Exception as e:
logger.error(f"Error querying facts: {e}")
return []
def get_facts_by_domain(self, domain: str) -> List[Fact]:
"""Get all facts for a specific domain"""
return [fact for fact in self.facts.values() if fact.domain == domain]
def _update_fact_embedding(self, fact: Fact):
"""Update or add the embedding for a fact"""
try:
embedding = self.embedding_client.embed_text(fact.content)
self.vector_db.add_vector(fact.id, embedding, {"fact_id": fact.id})
except Exception as e:
logger.error(f"Error updating fact embedding: {e}")
class KBAgent:
"""Agent that uses knowledge bases and prompts to perform tasks"""
def __init__(self, agent_id: str, kb_connector: KnowledgeConnector, prompt_manager: AdvancedPromptManager, facts_db: FactsDatabase = None):
self.agent_id = agent_id
self.kb = kb_connector
self.prompt_manager = prompt_manager
self.facts_db = facts_db
self.state = {}
def process(self, task: str, input_data: Dict = None) -> Dict:
"""Process a task using knowledge bases and prompts"""
logger.info(f"Agent {self.agent_id} processing task: {task}")
input_data = input_data or {}
self.state.update(input_data)
# Different tasks require different handling
if task == "gather_facts":
return self._gather_facts(input_data.get("query", ""))
elif task == "analyze":
return self._analyze_facts(input_data.get("facts", []))
elif task == "synthesize":
return self._synthesize_data(input_data)
else:
return {"error": f"Unknown task: {task}"}
def _gather_facts(self, query: str) -> Dict:
"""Gather facts from knowledge base"""
# Find an appropriate prompt
prompt = self._find_best_prompt("research")
if not prompt:
return {"error": "No suitable prompt found for research task"}
# Query knowledge base
kb_results = self.kb.query(query, top_k=5)
# Extract facts
facts = []
for result in kb_results:
# Create a fact from each knowledge item
if self.facts_db:
fact = self.facts_db.add_fact(
content=result["text"][:500], # Limit length
source=result.get("metadata", {}).get("source", "knowledge_base"),
confidence=result["similarity"],
domain=self.agent_id
)
facts.append(fact.to_dict())
else:
# If no facts DB, just store the raw data
facts.append({
"id": result["id"],
"content": result["text"][:500],
"source": result.get("metadata", {}).get("source", "knowledge_base"),
"confidence": result["similarity"],
"domain": self.agent_id
})
return {
"facts": facts,