-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.txt
2305 lines (1931 loc) · 83.1 KB
/
app.txt
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
File Name: api\app.py
========================================
from fastapi import FastAPI
from app.api.routers import download_router, chromadb_router, chromaindexer_router, chromaagent_router
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
app.include_router(download_router.router)
app.include_router(chromadb_router.router)
app.include_router(chromaindexer_router.router)
app.include_router(chromaagent_router.router)
@app.get("/")
def root():
return {"message": "Welcome to AIIP AI Agents"}
========================================
File Name: api\__init__.py
========================================
========================================
File Name: api\routers\chromaagent_router.py
========================================
from fastapi import APIRouter, HTTPException, Body, Query
from fastapi.responses import StreamingResponse
from app.core.agents.langgraph.simple_agent.agent import LangSimpleRAG
from app.core.agents.langgraph.complex_agent.agent import LangComplexRAG
from app.core.config.schemas import AgentConfig
from app.core.config.default_config import DEFAULT_AGENT_CONFIG
from typing import Optional
import json
import logging
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/agent", tags=["Agents"])
@router.post(
"/simple",
summary="Query the simple RAG agent",
description="""
Sends a question to the simple RAG agent.
- Can return a single response or stream updates
- Can be configured with custom agent parameters
- Returns retrieved documents and generated answer
""",
response_description="The agent's answer or a stream of updates"
)
async def simple_rag_agent(
question: str = Query(..., description="The question to ask the agent"),
stream: bool = Query(
default=False,
description="Whether to stream the response or return a single answer"
),
config: Optional[AgentConfig] = Body(
default=None,
description="Optional agent configuration. If not provided, uses default settings.",
example={
"llm": {
"name": "gpt-4o-mini",
"type": "openai",
"parameters": {
"temperature": 0.7
}
},
"retriever": {
"collection_name": "default_collection",
"search_type": "similarity",
"k": 4,
"search_parameters": {}
},
"agent_parameters": {}
}
)
):
"""Query the simple RAG agent with optional streaming and configuration"""
try:
# Initialize agent
agent = LangSimpleRAG(config)
if stream:
def event_generator():
try:
for output in agent.stream(question):
if isinstance(output, dict) and "error" in output:
yield f"data: {json.dumps({'error': output['error']})}\n\n"
break
yield f"data: {json.dumps(output)}\n\n"
except Exception as e:
logger.error(f"Error in stream generation: {str(e)}")
yield f"data: {json.dumps({'error': str(e)})}\n\n"
return StreamingResponse(
event_generator(),
media_type="text/event-stream"
)
else:
result = agent.run(question)
if isinstance(result, str) and result.startswith("Error:"):
raise HTTPException(status_code=500, detail=result)
return {"answer": result}
except Exception as e:
logger.error(f"Error in simple RAG agent: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.post(
"/complex",
summary="Query the complex RAG agent",
description="""
Sends a question to the complex RAG agent.
- Can return a single response or stream updates
- Can be configured with custom agent parameters
- Supports multiple retrieval strategies and self-correction
- Returns retrieved documents, feedback, and generated answer
""",
response_description="The agent's answer or a stream of updates"
)
async def complex_rag_agent(
question: str = Query(..., description="The question to ask the agent"),
stream: bool = Query(
default=False,
description="Whether to stream the response or return a single answer"
),
config: Optional[AgentConfig] = Body(
default=None,
description="Optional agent configuration. If not provided, uses default settings.",
example={
"llm": {
"name": "gpt-4o-mini",
"type": "openai",
"parameters": {
"temperature": 0.7
}
},
"retriever": {
"collection_name": "default_collection",
"search_type": "similarity",
"k": 4,
"search_parameters": {}
},
"agent_parameters": {
"max_retrievals": 3,
"max_generations": 3
}
}
)
):
"""Query the complex RAG agent with optional streaming and configuration"""
try:
# Initialize agent
agent = LangComplexRAG(config)
if stream:
def event_generator():
try:
for output in agent.stream(question):
if isinstance(output, dict) and "error" in output:
yield f"data: {json.dumps({'error': output['error']})}\n\n"
break
yield f"data: {json.dumps(output)}\n\n"
except Exception as e:
logger.error(f"Error in stream generation: {str(e)}")
yield f"data: {json.dumps({'error': str(e)})}\n\n"
return StreamingResponse(
event_generator(),
media_type="text/event-stream"
)
else:
result = agent.run(question)
if isinstance(result, str) and result.startswith("Error:"):
raise HTTPException(status_code=500, detail=result)
return {"answer": result}
except Exception as e:
logger.error(f"Error in complex RAG agent: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
========================================
File Name: api\routers\chromadb_router.py
========================================
from fastapi import APIRouter, HTTPException, Body
from typing import Optional
from app.core.config.schemas import DatabaseConfig
from app.core.config.default_config import AVAILABLE_EMBEDDINGS, DEFAULT_DATABASE
from app.core.indexers.chroma_indexer import chroma_db
import logging
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/chromadb", tags=["Database Operations"])
@router.post("/create", summary="Initialize or reconfigure ChromaDB")
async def create_database(
config: Optional[DatabaseConfig] = Body(
default=None,
description="Database configuration. If not provided, default settings will be used.",
example={
"database_type": "ChromaDB",
"collection_name": "default_collection",
"embedding": {
"name": "text-embedding-3-small", # Changed from model_name
"type": "openai", # Changed from model_type
"parameters": {}
},
"parameters": {
"collection_metadata": {"hnsw:space": "cosine"}
}
}
)
):
"""
Initialize or reconfigure ChromaDB with optional configuration.
- If no config is provided, uses default settings
- The persist_directory is fixed to './app/databases/chroma_db'
- Supports different embedding models and collection metadata
- This will affect all subsequent database operations
"""
try:
if config:
# Ensure persist_directory is fixed
config.parameters["persist_directory"] = DEFAULT_DATABASE.parameters["persist_directory"]
# Reconfigure the global instance
chroma_db.reconfigure(config)
return {"message": "Database configured successfully", "config": config or DEFAULT_DATABASE}
except Exception as e:
logger.error(f"Error configuring database: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/collections/{collection_name}", summary="Create a new collection")
async def create_collection(collection_name: str):
"""Create a new collection using the current database configuration."""
try:
chroma_db.create_collection(collection_name)
return {"message": f"Collection '{collection_name}' created successfully"}
except Exception as e:
logger.error(f"Error creating collection: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/collections", summary="List all collections")
async def list_collections():
"""List all available collections in the database."""
try:
collections = chroma_db.list_collections()
return {"collections": collections}
except Exception as e:
logger.error(f"Error listing collections: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.delete("/collections/{collection_name}", summary="Delete a collection")
async def delete_collection(collection_name: str):
"""Delete a collection by name."""
try:
chroma_db.delete_collection(collection_name)
return {"message": f"Collection '{collection_name}' deleted successfully"}
except Exception as e:
logger.error(f"Error deleting collection: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/embeddings", summary="List available embedding models")
async def list_embeddings():
"""Get a list of all available embedding models and their configurations."""
return {"embeddings": AVAILABLE_EMBEDDINGS}
========================================
File Name: api\routers\chromaindexer_router.py
========================================
from fastapi import APIRouter, HTTPException, Body, File, UploadFile, Query
from pydantic import BaseModel
from typing import List, Optional
from app.core.config.schemas import RetrieverConfig
from app.core.indexers.chroma_indexer import ChromaIndexer
from app.core.pipes.simple_index_pipeline import SimpleIndexChromaPipeline
from langchain_core.documents import Document
import tempfile
import os
import logging
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/chroma", tags=["Index Operations"])
@router.post("/{collection_name}/add_documents", summary="Add documents to collection")
async def add_documents(
collection_name: str,
documents: List[dict] = Body(
...,
description="List of documents with page_content and metadata"
)
):
"""
Add documents to a collection.
- Documents should include page_content and optional metadata
- Uses the current database configuration
"""
try:
config = RetrieverConfig(collection_name=collection_name)
indexer = ChromaIndexer(config)
docs = [Document(**doc) for doc in documents]
indexer.add_documents(docs)
return {"message": f"{len(docs)} documents added to collection '{collection_name}'"}
except Exception as e:
logger.error(f"Error adding documents: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{collection_name}/search", summary="Search documents in collection")
async def search_documents(
collection_name: str,
query: str = Body(..., embed=True, description="Search query"),
retriever_config: Optional[RetrieverConfig] = Body(
default=None,
description="""Optional retriever configuration.
Available search types: similarity, mmr, similarity_score_threshold.
MMR parameters: fetch_k, lambda_mult.
Similarity threshold parameters: score_threshold.""",
example={
"search_type": "similarity",
"k": 4,
"search_parameters": {}
}
)
):
"""
Search documents in a collection.
- Supports different search types: similarity, mmr, similarity_score_threshold
- MMR (Maximal Marginal Relevance) helps with result diversity
- Similarity threshold allows filtering by minimum score
"""
try:
config = retriever_config or RetrieverConfig(collection_name=collection_name)
config.collection_name = collection_name # Ensure collection name matches path
indexer = ChromaIndexer(config)
results = indexer.similarity_search(query, config)
return {"results": [doc.dict() for doc in results]}
except Exception as e:
logger.error(f"Error searching documents: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.delete("/{collection_name}/documents/{document_id}", summary="Delete a document")
async def delete_document(collection_name: str, document_id: str):
"""Delete a document from the collection by ID."""
try:
config = RetrieverConfig(collection_name=collection_name)
indexer = ChromaIndexer(config)
indexer.delete_document(document_id)
return {"message": f"Document '{document_id}' deleted from collection '{collection_name}'"}
except Exception as e:
logger.error(f"Error deleting document: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.put("/{collection_name}/documents/{document_id}", summary="Update a document")
async def update_document(
collection_name: str,
document_id: str,
document: dict = Body(..., description="Document with page_content and metadata")
):
"""Update a document in the collection by ID."""
try:
config = RetrieverConfig(collection_name=collection_name)
indexer = ChromaIndexer(config)
doc = Document(**document)
indexer.update_document(document_id, doc)
return {"message": f"Document '{document_id}' updated in collection '{collection_name}'"}
except Exception as e:
logger.error(f"Error updating document: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/{collection_name}/count", summary="Count documents in collection")
async def count_documents(collection_name: str):
"""Get the total number of documents in a collection."""
try:
config = RetrieverConfig(collection_name=collection_name)
indexer = ChromaIndexer(config)
count = indexer.count_documents()
return {"count": count}
except Exception as e:
logger.error(f"Error counting documents: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{collection_name}/process_pdfs", summary="Process and index PDF files")
async def process_pdfs(
collection_name: str,
files: List[UploadFile] = File(..., description="PDF files to process"),
chunk_size: int = Query(
default=10000,
gt=0,
description="Size of document chunks. Larger values mean longer but fewer chunks"
),
chunk_overlap: int = Query(
default=200,
ge=0,
lt=10000,
description="Number of characters to overlap between chunks. Helps maintain context between chunks"
)
):
"""
Process PDF files and add their content to the collection.
- Supports multiple PDF files
- Customize chunk size and overlap for text splitting
- Automatically processes and indexes all content
Example chunk sizes:
- 10000: Good for general purpose use
- 4000: Better for precise retrievals
- 2000: Best for very specific queries
Example overlaps:
- 200: Standard overlap
- 500: More context preservation
- 1000: Maximum context preservation
"""
try:
pipeline = SimpleIndexChromaPipeline(
collection_name=collection_name,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap
)
processed_docs = []
with tempfile.TemporaryDirectory() as temp_dir:
for file in files:
temp_file_path = os.path.join(temp_dir, file.filename)
with open(temp_file_path, "wb") as buffer:
buffer.write(await file.read())
processed_docs.extend(pipeline.process_pdf(temp_file_path))
return {
"message": f"{len(processed_docs)} documents processed and added to collection '{collection_name}'",
"processed_files": [file.filename for file in files],
"chunking_config": {
"chunk_size": chunk_size,
"chunk_overlap": chunk_overlap
}
}
except Exception as e:
logger.error(f"Error processing PDFs: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{collection_name}/process_folder", summary="Process and index folder of PDFs")
async def process_folder(
collection_name: str,
folder_path: str = Body(..., embed=True, description="Path to folder containing PDF files"),
chunk_size: int = Query(
default=10000,
gt=0,
description="Size of document chunks. Larger values mean longer but fewer chunks"
),
chunk_overlap: int = Query(
default=200,
ge=0,
lt=10000,
description="Number of characters to overlap between chunks. Helps maintain context between chunks"
)
):
"""
Process all PDF files in a folder and add their content to the collection.
- Processes all PDFs in the specified folder
- Customize chunk size and overlap for text splitting
- Automatically processes and indexes all content
Example chunk sizes:
- 10000: Good for general purpose use
- 4000: Better for precise retrievals
- 2000: Best for very specific queries
Example overlaps:
- 200: Standard overlap
- 500: More context preservation
- 1000: Maximum context preservation
"""
try:
pipeline = SimpleIndexChromaPipeline(
collection_name=collection_name,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap
)
processed_docs = pipeline.process_folder(folder_path)
return {
"message": f"{len(processed_docs)} documents processed and added to collection '{collection_name}'",
"folder_path": folder_path,
"chunking_config": {
"chunk_size": chunk_size,
"chunk_overlap": chunk_overlap
}
}
except Exception as e:
logger.error(f"Error processing folder: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
========================================
File Name: api\routers\download_router.py
========================================
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import RedirectResponse
from app.core.loaders.gdrive_loader import GDriveLoader
router = APIRouter(prefix="/gdrive", tags=["Google Drive"])
gdrive_loader = GDriveLoader()
@router.get("/authorize")
async def authorize():
authorization_url, _ = gdrive_loader.authenticate()
return RedirectResponse(url=authorization_url)
@router.get("/oauth2callback")
async def oauth2callback(request: Request):
try:
state = request.query_params.get('state')
authorization_response = str(request.url)
gdrive_loader.set_credentials(authorization_response, state)
# Redirect to the Streamlit UI with a success parameter
return RedirectResponse(url="http://localhost:8501/Chroma_Index_Operations?auth_success=true")
except Exception as error:
raise HTTPException(status_code=500, detail=str(error))
@router.get("/download_files/{folder_id}")
async def download_files(folder_id: str):
try:
downloaded_files = gdrive_loader.download_files(folder_id)
if not downloaded_files:
raise HTTPException(status_code=404, detail=f"No files found in folder ID: {folder_id}")
return {"message": f"Files downloaded successfully!", "files": downloaded_files}
except Exception as error:
raise HTTPException(status_code=500, detail=str(error))
========================================
File Name: api\routers\__init__.py
========================================
========================================
File Name: core\__init__.py
========================================
========================================
File Name: core\agents\__init__.py
========================================
========================================
File Name: core\agents\langgraph\__init__.py
========================================
========================================
File Name: core\agents\langgraph\complex_agent\agent.py
========================================
from typing import Optional, List, Dict, Any
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END
from app.core.indexers.chroma_indexer import ChromaIndexer
from app.core.config.schemas import AgentConfig
from app.core.config.default_config import DEFAULT_AGENT_CONFIG
from langchain_core.output_parsers import StrOutputParser
from .state import GraphState
from .tools import web_search_tool
import logging
from dotenv import load_dotenv
load_dotenv()
logger = logging.getLogger(__name__)
class LangComplexRAG:
"""LangChain Graph-based Complex RAG Agent with multiple feedback loops"""
def __init__(self, config: Optional[AgentConfig] = None):
"""Initialize the agent with optional configuration"""
self.config = config or DEFAULT_AGENT_CONFIG
# Get agent-specific parameters with defaults
self.MAX_RETRIEVALS = self.config.agent_parameters.get("max_retrievals", 3)
self.MAX_GENERATIONS = self.config.agent_parameters.get("max_generations", 3)
logger.info(f"Initializing LangComplexRAG with max_retrievals={self.MAX_RETRIEVALS}, "
f"max_generations={self.MAX_GENERATIONS}")
# Initialize all components
self._initialize_components()
self._initialize_output_parsers()
self._initialize_chains()
self._initialize_nodes()
self.pipeline = self._build_pipeline()
def run(self, question: str) -> str:
"""Run the agent synchronously"""
try:
inputs = {"question": question}
result = self.pipeline.invoke(inputs)
return result["generation"]
except Exception as e:
logger.error(f"Error running agent: {str(e)}")
raise
def stream(self, question: str):
"""Stream the agent's response"""
try:
inputs = {"question": question}
for output in self.pipeline.stream(inputs, stream_mode='updates'):
yield output
except Exception as e:
logger.error(f"Error streaming response: {str(e)}")
raise
def _initialize_components(self):
"""Initialize base components: LLM and Retriever"""
try:
# Initialize LLM
self.llm_engine = ChatOpenAI(
model=self.config.llm.name,
**self.config.llm.parameters
)
# Initialize Retriever
self.indexer = ChromaIndexer(self.config.retriever)
self.retriever = self.indexer.as_retriever()
logger.info("Components initialized successfully")
except Exception as e:
logger.error(f"Error initializing components: {str(e)}")
raise
def _initialize_output_parsers(self):
"""Initialize Pydantic output parsers for structured outputs"""
try:
from .utils import (
GradeHallucinations,
GradeDocuments,
GradeAnswer,
RouteQuery
)
# Store parser classes
self.parsers = {
"hallucination": GradeHallucinations,
"documents": GradeDocuments,
"answer": GradeAnswer,
"route": RouteQuery
}
logger.info("Output parsers initialized successfully")
except Exception as e:
logger.error(f"Error initializing output parsers: {str(e)}")
raise
def _initialize_chains(self):
"""Initialize all LangChain chains"""
try:
from .prompts import (
rag_prompt,
db_query_rewrite_prompt,
hallucination_prompt,
answer_prompt,
query_feedback_prompt,
generation_feedback_prompt,
give_up_prompt,
grade_doc_prompt,
knowledge_extraction_prompt,
router_prompt,
websearch_query_rewrite_prompt,
simple_question_prompt
)
# Basic chains
self.rag_chain = rag_prompt | self.llm_engine | StrOutputParser()
self.db_query_rewriter = db_query_rewrite_prompt | self.llm_engine | StrOutputParser()
self.query_feedback_chain = query_feedback_prompt | self.llm_engine | StrOutputParser()
self.generation_feedback_chain = generation_feedback_prompt | self.llm_engine | StrOutputParser()
self.give_up_chain = give_up_prompt | self.llm_engine | StrOutputParser()
self.knowledge_extractor = knowledge_extraction_prompt | self.llm_engine | StrOutputParser()
self.websearch_query_rewriter = websearch_query_rewrite_prompt | self.llm_engine | StrOutputParser()
self.simple_question_chain = simple_question_prompt | self.llm_engine | StrOutputParser()
# Structured output chains
self.hallucination_grader = hallucination_prompt | self.llm_engine.with_structured_output(self.parsers["hallucination"])
self.answer_grader = answer_prompt | self.llm_engine.with_structured_output(self.parsers["answer"])
self.retrieval_grader = grade_doc_prompt | self.llm_engine.with_structured_output(self.parsers["documents"])
self.question_router = router_prompt | self.llm_engine.with_structured_output(self.parsers["route"])
logger.info("Chains initialized successfully")
except Exception as e:
logger.error(f"Error initializing chains: {str(e)}")
raise
def _initialize_nodes(self):
"""Initialize all nodes with exact same logic as original"""
try:
def retriever_node(state: GraphState):
new_documents = self.retriever.invoke(state.rewritten_question)
new_documents = [d.page_content for d in new_documents]
state.documents.extend(new_documents)
return {
"documents": state.documents,
"retrieval_num": state.retrieval_num + 1
}
def generation_node(state: GraphState):
generation = self.rag_chain.invoke({
"context": "\n\n".join(state.documents),
"question": state.question,
"feedback": "\n".join(state.generation_feedbacks)
})
return {
"generation": generation,
"generation_num": state.generation_num + 1
}
def db_query_rewriting_node(state: GraphState):
rewritten_question = self.db_query_rewriter.invoke({
"question": state.question,
"feedback": "\n".join(state.query_feedbacks)
})
return {"rewritten_question": rewritten_question, "search_mode": "vectorstore"}
def answer_evaluation_node(state: GraphState):
# assess hallucination
hallucination_grade = self.hallucination_grader.invoke(
{"documents": state.documents, "generation": state.generation}
)
if hallucination_grade.binary_score == "yes":
# if no hallucination, assess relevance
answer_grade = self.answer_grader.invoke({
"question": state.question,
"generation": state.generation
})
if answer_grade.binary_score == "yes":
# no hallucination and relevant
return "useful"
elif state.generation_num > self.MAX_GENERATIONS:
return "max_generation_reached"
else:
# no hallucination but not relevant
return "not relevant"
elif state.generation_num > self.MAX_GENERATIONS:
return "max_generation_reached"
else:
# we have hallucination
return "hallucination"
def generation_feedback_node(state: GraphState):
feedback = self.generation_feedback_chain.invoke({
"question": state.question,
"documents": "\n\n".join(state.documents),
"generation": state.generation
})
feedback = 'Feedback about the answer "{}": {}'.format(
state.generation, feedback
)
state.generation_feedbacks.append(feedback)
return {"generation_feedbacks": state.generation_feedbacks}
def query_feedback_node(state: GraphState):
feedback = self.query_feedback_chain.invoke({
"question": state.question,
"rewritten_question": state.rewritten_question,
"documents": "\n\n".join(state.documents),
"generation": state.generation
})
feedback = 'Feedback about the query "{}": {}'.format(
state.rewritten_question, feedback
)
state.query_feedbacks.append(feedback)
return {"query_feedbacks": state.query_feedbacks}
def give_up_node(state: GraphState):
response = self.give_up_chain.invoke(state.question)
return {"generation": response}
def filter_relevant_documents_node(state: GraphState):
# first, we grade every documents
grades = self.retrieval_grader.batch([
{"question": state.question, "document": doc}
for doc in state.documents
])
# Then we keep only the documents that were graded as relevant
filtered_docs = [
doc for grade, doc
in zip(grades, state.documents)
if grade.binary_score == 'yes'
]
# If we didn't get any relevant document, let's capture that
# as a feedback for the next retrieval iteration
if not filtered_docs:
feedback = 'Feedback about the query "{}": did not generate any relevant documents.'.format(
state.rewritten_question
)
state.query_feedbacks.append(feedback)
return {
"documents": filtered_docs,
"query_feedbacks": state.query_feedbacks
}
def knowledge_extractor_node(state: GraphState):
filtered_docs = self.knowledge_extractor.batch([
{"question": state.question, "document": doc}
for doc in state.documents
])
# we keep only the non empty documents
filtered_docs = [doc for doc in filtered_docs if doc]
return {"documents": filtered_docs}
def router_node(state: GraphState):
route_query = self.question_router.invoke(state.question)
return route_query.route
def simple_question_node(state: GraphState):
answer = self.simple_question_chain.invoke(state.question)
return {"generation": answer, "search_mode": "QA_LM"}
def websearch_query_rewriting_node(state: GraphState):
rewritten_question = self.websearch_query_rewriter.invoke({
"question": state.question,
"feedback": "\n".join(state.query_feedbacks)
})
if state.search_mode != "websearch":
state.retrieval_num = 0
return {
"rewritten_question": rewritten_question,
"search_mode": "websearch",
"retrieval_num": state.retrieval_num
}
def web_search_node(state: GraphState):
try:
new_docs = web_search_tool.invoke(
{"query": state.rewritten_question}
)
if isinstance(new_docs, str):
web_results = [new_docs]
elif isinstance(new_docs, list):
web_results = [d.get("content", str(d)) if isinstance(d, dict) else str(d) for d in new_docs]
else:
web_results = [str(new_docs)]
state.documents.extend(web_results)
return {
"documents": state.documents,
"retrieval_num": state.retrieval_num + 1
}
except Exception as e:
return {
"error": f"Web search failed: {str(e)}",
"retrieval_num": state.retrieval_num + 1
}
def search_mode_node(state: GraphState):
return state.search_mode
def relevant_documents_validation_node(state: GraphState):
if state.documents:
# we have relevant documents
return "knowledge_extraction"
elif state.search_mode == 'vectorsearch' and state.retrieval_num > self.MAX_RETRIEVALS:
# we don't have relevant documents
# and we reached the maximum number of retrievals
return "max_db_search"
elif state.search_mode == 'websearch' and state.retrieval_num > self.MAX_RETRIEVALS:
# we don't have relevant documents
# and we reached the maximum number of websearches
return "max_websearch"
else:
# we don't have relevant documents
# so we retry the search
return state.search_mode
self.nodes = {
"retriever_node": retriever_node,
"generation_node": generation_node,
"db_query_rewriting_node": db_query_rewriting_node,
"generation_feedback": generation_feedback_node,
"generation_feedback_node": query_feedback_node,
"give_up_node": give_up_node,
"filter_relevant_documents_node": filter_relevant_documents_node,
"knowledge_extractor_node": knowledge_extractor_node,
"simple_question_node": simple_question_node,
"websearch_query_rewriting_node": websearch_query_rewriting_node,
"web_search_node": web_search_node,
"router_node": router_node,
"search_mode_node": search_mode_node,
"answer_evaluation_node": answer_evaluation_node,
"relevant_documents_validation_node": relevant_documents_validation_node
}
logger.info("Nodes initialized successfully")
except Exception as e:
logger.error(f"Error initializing nodes: {str(e)}")
raise
def _build_pipeline(self) -> StateGraph:
"""Build the LangGraph pipeline"""
try:
# Create graph
graph = StateGraph(GraphState)
# Add nodes
graph.add_node('db_query_rewrite_node', self.nodes['db_query_rewriting_node'])
graph.add_node('retrieval_node', self.nodes['retriever_node'])
graph.add_node('generator_node', self.nodes['generation_node'])
graph.add_node('query_feedback_node', self.nodes['generation_feedback_node']) # Note the name change here
graph.add_node('generation_feedback_node', self.nodes['generation_feedback']) # And here
graph.add_node('simple_question_node', self.nodes['simple_question_node'])
graph.add_node('websearch_query_rewriting_node', self.nodes['websearch_query_rewriting_node'])
graph.add_node('web_search_node', self.nodes['web_search_node'])
graph.add_node('give_up_node', self.nodes['give_up_node'])
graph.add_node('filter_docs_node', self.nodes['filter_relevant_documents_node'])
graph.add_node('extract_knowledge_node', self.nodes['knowledge_extractor_node'])
# Add conditional edges from START
graph.add_conditional_edges(
START,
self.nodes['router_node'],
{
"vectorstore": 'db_query_rewrite_node',
"websearch": 'websearch_query_rewriting_node',
"QA_LM": 'simple_question_node'
}
)
# Add simple edges
graph.add_edge('db_query_rewrite_node', 'retrieval_node')
graph.add_edge('retrieval_node', 'filter_docs_node')
graph.add_edge('extract_knowledge_node', 'generator_node')
graph.add_edge('websearch_query_rewriting_node', 'web_search_node')
graph.add_edge('web_search_node', 'filter_docs_node')
graph.add_edge('generation_feedback_node', 'generator_node')
graph.add_edge('simple_question_node', END)
graph.add_edge('give_up_node', END)
# Add conditional edges for answer evaluation
graph.add_conditional_edges(
'generator_node',
self.nodes['answer_evaluation_node'],
{
"useful": END,
"not relevant": 'query_feedback_node',
"hallucination": 'generation_feedback_node',
"max_generation_reached": 'give_up_node'
}
)
# Add conditional edges for search mode
graph.add_conditional_edges(
'query_feedback_node',
self.nodes['search_mode_node'],
{
"vectorstore": 'db_query_rewrite_node',
"websearch": 'websearch_query_rewriting_node',
}
)
# Add conditional edges for document validation
graph.add_conditional_edges(
'filter_docs_node',
self.nodes['relevant_documents_validation_node'],
{
"knowledge_extraction": 'extract_knowledge_node',
"websearch": 'websearch_query_rewriting_node',
"vectorstore": 'db_query_rewrite_node',
"max_db_search": 'websearch_query_rewriting_node',
"max_websearch": 'give_up_node'
}
)
logger.info("Pipeline built successfully")
return graph.compile()
except Exception as e:
logger.error(f"Error building pipeline: {str(e)}")
raise
========================================
File Name: core\agents\langgraph\complex_agent\prompts.py
========================================
from langchain_core.prompts import ChatPromptTemplate
system_prompt = """
You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question.