Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. Β See raw diff
- .claude/settings.local.json +32 -0
- .gitattributes +59 -0
- .github/workflows/update_space.yml +28 -0
- .gitignore +11 -0
- .gradio/certificate.pem +31 -0
- .python-version +1 -0
- .vscode/settings.json +3 -0
- Paper_explorer/.gitattributes +35 -0
- Paper_explorer/README.md +14 -0
- README.md +610 -12
- backend/__init__.py +0 -0
- backend/agentic_system/__init__.py +0 -0
- backend/agentic_system/agents/__init__.py +0 -0
- backend/agentic_system/agents/flashcard_agent/__init__.py +21 -0
- backend/agentic_system/agents/flashcard_agent/flashcard.py +24 -0
- backend/agentic_system/agents/flashcard_agent/flashcard_agent.py +153 -0
- backend/agentic_system/agents/flashcard_agent/flashcard_prompt.py +63 -0
- backend/agentic_system/agents/flashcard_agent/flashcard_schema.py +97 -0
- backend/agentic_system/agents/flashcard_agent/flashcard_utils.py +172 -0
- backend/agentic_system/agents/question_answering_agent/__init__.py +19 -0
- backend/agentic_system/agents/question_answering_agent/qa_agent.py +138 -0
- backend/agentic_system/agents/question_answering_agent/qa_prompt.py +52 -0
- backend/agentic_system/agents/question_answering_agent/qa_schema.py +136 -0
- backend/agentic_system/agents/question_generation_agent/__init__.py +19 -0
- backend/agentic_system/agents/question_generation_agent/question_generation_agent.py +193 -0
- backend/agentic_system/agents/question_generation_agent/question_generation_prompt.py +124 -0
- backend/agentic_system/agents/question_generation_agent/question_generation_schema.py +74 -0
- backend/agentic_system/agents/retrieval_strategy_agent/__init__.py +18 -0
- backend/agentic_system/agents/retrieval_strategy_agent/retrieval_strategy_agent.py +126 -0
- backend/agentic_system/agents/retrieval_strategy_agent/retrieval_strategy_prompt.py +75 -0
- backend/agentic_system/agents/retrieval_strategy_agent/retrieval_strategy_schema.py +102 -0
- backend/agentic_system/flashcard_processor.py +228 -0
- backend/agentic_system/graphs/__init__.py +14 -0
- backend/agentic_system/graphs/qa_workflow.py +93 -0
- backend/agentic_system/graphs/state_schema.py +193 -0
- backend/agentic_system/nodes/__init__.py +15 -0
- backend/agentic_system/nodes/base_node.py +48 -0
- backend/agentic_system/nodes/fetching_node.py +110 -0
- backend/agentic_system/nodes/qa_node.py +101 -0
- backend/agentic_system/nodes/retrieval_strategy_node.py +84 -0
- backend/agentic_system/orchestrators/__init__.py +0 -0
- backend/agentic_system/orchestrators/debug_qa_workflow.py +143 -0
- backend/agentic_system/orchestrators/research_exploration_orchestrator_refactored.py +388 -0
- backend/agentic_system/orchestrators/research_exploration_schema.py +113 -0
- backend/agentic_system/orchestrators/test_research_exploration.py +328 -0
- backend/agentic_system/orchestrators/utils/__init__.py +68 -0
- backend/agentic_system/orchestrators/utils/answer_extraction_utils.py +245 -0
- backend/agentic_system/orchestrators/utils/logging_utils.py +107 -0
- backend/agentic_system/orchestrators/utils/result_organization_utils.py +241 -0
- backend/agentic_system/orchestrators/utils/workflow_processing_utils.py +240 -0
.claude/settings.local.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"permissions": {
|
| 3 |
+
"allow": [
|
| 4 |
+
"Bash(nvidia-smi:*)",
|
| 5 |
+
"Bash(uv pip uninstall:*)",
|
| 6 |
+
"Bash(uv pip install:*)",
|
| 7 |
+
"Bash(python:*)",
|
| 8 |
+
"Bash($env:CUDA_LAUNCH_BLOCKING=\"1\")",
|
| 9 |
+
"Bash($env:TORCH_CUDA_ARCH_LIST=\"8.9\")",
|
| 10 |
+
"Bash(powershell:*)",
|
| 11 |
+
"Bash(mkdir:*)",
|
| 12 |
+
"Bash(rmdir:*)",
|
| 13 |
+
"Bash(uv pip:*)",
|
| 14 |
+
"Bash(find:*)",
|
| 15 |
+
"WebFetch(domain:ai.pydantic.dev)",
|
| 16 |
+
"Bash(del \"C:\\Users\\User\\Projects\\paper_verifier\\test_retrieval_agent.py\")",
|
| 17 |
+
"Bash(rm:*)",
|
| 18 |
+
"Bash(ren:*)",
|
| 19 |
+
"Bash(mv:*)",
|
| 20 |
+
"Bash(git reset:*)",
|
| 21 |
+
"Bash(del \"gemma3270m\\experimenting.ipynb\")",
|
| 22 |
+
"Bash(git add:*)",
|
| 23 |
+
"Bash(git push:*)",
|
| 24 |
+
"WebSearch",
|
| 25 |
+
"Bash(touch:*)"
|
| 26 |
+
],
|
| 27 |
+
"deny": [],
|
| 28 |
+
"ask": [],
|
| 29 |
+
"defaultMode": "acceptEdits"
|
| 30 |
+
},
|
| 31 |
+
"outputStyle": "Explanatory"
|
| 32 |
+
}
|
.gitattributes
CHANGED
|
@@ -33,3 +33,62 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
backend/ingestion_pipeline/local_mineru/file_ingesting/research_papers/Attention[[:space:]]Is[[:space:]]All[[:space:]]You[[:space:]]Need.pdf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
backend/ingestion_pipeline/local_mineru/file_ingesting/research_papers/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v_f4b3b7c9.pdf filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
backend/ingestion_pipeline/local_mineru/file_ingesting/research_papers/Communication-Efficient[[:space:]]Learning[[:space:]]of[[:space:]]Deep[[:space:]]Networks.pdf filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
backend/ingestion_pipeline/local_mineru/file_ingesting/research_papers/MOE.pdf filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
backend/ingestion_pipeline/local_mineru/file_ingesting/research_papers/React_paper.pdf filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
backend/ingestion_pipeline/local_mineru/file_ingesting/research_papers/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large.pdf filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
backend/ingestion_pipeline/output/Attention[[:space:]]Is[[:space:]]All[[:space:]]You[[:space:]]Need/auto/images/4ff785d908d5e376f8a96720f1bb63fd84c2a5d387e0b90457a10613fa4cf028.jpg filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
backend/ingestion_pipeline/output/Attention[[:space:]]Is[[:space:]]All[[:space:]]You[[:space:]]Need/auto/images/7fb8900db1bef9619da338696033ca846744398e60dea610261f9d7cfc2b5a15.jpg filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
backend/ingestion_pipeline/output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/5ee9d05be6bd349746c8dfe0389ff1e6c7fef03a5994c1bf6b6b6d7af889445b.jpg filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
backend/ingestion_pipeline/output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/6f59d26b3afd78c36a984f4b71346c86769806241d9046842d3157df3fa94268.jpg filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
backend/ingestion_pipeline/output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/938fbc4e6a81d991cd4b47142dcf2da9a6449edb3901f2d7acde1129c9b499cc.jpg filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
backend/ingestion_pipeline/output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/d04b708c84d01cfb1c90d8a7a382f7676b2046fa69acca67fb9b9b6076e76060.jpg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
backend/ingestion_pipeline/output/MOE/auto/images/7a89037bb830acff4d6906979097eac9d166333a3a32003326f58f543bd26e4f.jpg filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/1ccfb7d1160d431d2af719bc8134b77340986ff29cdda76606580fd546c29c0d.jpg filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/39c142d4e1257ebc9816020500fcbf1e345a0b76ce110db2551a89b14ca4c6d6.jpg filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/4c8d08f6e9dc725e3b192da81d95c66b9a92f21696c8b18a8e3e7aca2ab18857.jpg filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/64e2864c81b9df063470957f77d00dca3bac876ebd3a18a66de299896188a0e8.jpg filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/659f41d4412dd2304297b1f91313f8c8c43690bdd94e00cd057786891791a805.jpg filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/69d01dabe525b457a0dea4899633824d7c6a020e8bcd57f87b2f5c5cc3dae77c.jpg filter=lfs diff=lfs merge=lfs -text
|
| 55 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/b23c3fe3506a56dbf706ed26daed4468dfc508dc16d3cb9bd170d73d5778f2a6.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/b37bc5751a854a8b6706e82d355f83f04ae7deb8fb9323e3353e39e62489db74.jpg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/cd2e94d69f99658328815ba6ccee179d6aecd126347c9af7d744f9d58a151086.jpg filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/d78b1fc7e019e5a89414ccfae4e382351fbb5d3ebd5763f7ef21e27c5ed77f44.jpg filter=lfs diff=lfs merge=lfs -text
|
| 59 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/d98a2efdd20e557dc2bd54f2ee6bf6f2cd4d467e12bbd31721ea9e4941ac71a7.jpg filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/f6c58ec77debe0d5aebd61c3d43b76481230ef7fc460b742cd98292ae14dec4c.jpg filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
backend/ingestion_pipeline/output/React_paper/auto/images/fdb321ba5738fff4c524e9e00e4f1ed5921dca8af839e66a4ff7678e459131b3.jpg filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/0a6052d959b55329f431979166c399bb48eb201513690234f56f7bc1ed2ca143.jpg filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/44f9650b49eb7c89c591d11d800486203087d3a89226fb46f167c63eb3d54e49.jpg filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/48eac85984db214f1239d2587a5c9212bbe0e83f4df0523301ac0d5c88ed7b07.jpg filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/53be93c32e7dfda8e6f37a75c53b4f3413729758e8e135240489a3c89db07e90.jpg filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/54ba53e905e4b1507712565596bc939d3eaf80a4bbe0e0ae6a1b42bff2ef742e.jpg filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/77c4c32c1adca3a145486fc4768303feb5c12b34b9a1d2be0efc16a27cd435fa.jpg filter=lfs diff=lfs merge=lfs -text
|
| 68 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/7a301bf14d27246d671fe2f019348067a554dcdd7dc6af2604ebd4ebba48dcc3.jpg filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/7f16686f1105451014a37e7f8be3e8ce3938b447496f6b7451f897a2796e66ac.jpg filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/93144e9125c92890e1eada7cf6aca7e81e7846ea281be533d7a92908374ae4f4.jpg filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/d7614a38b998519482b9ad9ab776369620dacab6d03d9d1eb88cbd8282792b50.jpg filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
backend/ingestion_pipeline/output/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large/auto/images/f9283173cfd5cc41848dbdac8e8581006a4d40a4141bae56cd4912f55bdac1a1.jpg filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
backend/ingestion_pipeline/pdfs/Attention[[:space:]]Is[[:space:]]All[[:space:]]You[[:space:]]Need.pdf filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
backend/ingestion_pipeline/pdfs/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1).pdf filter=lfs diff=lfs merge=lfs -text
|
| 75 |
+
backend/ingestion_pipeline/pdfs/Communication-Efficient[[:space:]]Learning[[:space:]]of[[:space:]]Deep[[:space:]]Networks.pdf filter=lfs diff=lfs merge=lfs -text
|
| 76 |
+
backend/ingestion_pipeline/pdfs/MOE.pdf filter=lfs diff=lfs merge=lfs -text
|
| 77 |
+
backend/ingestion_pipeline/pdfs/React_paper.pdf filter=lfs diff=lfs merge=lfs -text
|
| 78 |
+
backend/ingestion_pipeline/pdfs/Small[[:space:]]Language[[:space:]]Models[[:space:]]in[[:space:]]the[[:space:]]Era[[:space:]]of[[:space:]]Large.pdf filter=lfs diff=lfs merge=lfs -text
|
| 79 |
+
backend/ingestion_pipeline/tests/auto/images/5ee9d05be6bd349746c8dfe0389ff1e6c7fef03a5994c1bf6b6b6d7af889445b.jpg filter=lfs diff=lfs merge=lfs -text
|
| 80 |
+
backend/ingestion_pipeline/tests/auto/images/6f59d26b3afd78c36a984f4b71346c86769806241d9046842d3157df3fa94268.jpg filter=lfs diff=lfs merge=lfs -text
|
| 81 |
+
backend/ingestion_pipeline/tests/auto/images/938fbc4e6a81d991cd4b47142dcf2da9a6449edb3901f2d7acde1129c9b499cc.jpg filter=lfs diff=lfs merge=lfs -text
|
| 82 |
+
backend/ingestion_pipeline/tests/auto/images/d04b708c84d01cfb1c90d8a7a382f7676b2046fa69acca67fb9b9b6076e76060.jpg filter=lfs diff=lfs merge=lfs -text
|
| 83 |
+
backend/ingestion_pipeline/tests/enhanced_test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/5ee9d05be6bd349746c8dfe0389ff1e6c7fef03a5994c1bf6b6b6d7af889445b.jpg filter=lfs diff=lfs merge=lfs -text
|
| 84 |
+
backend/ingestion_pipeline/tests/enhanced_test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/6f59d26b3afd78c36a984f4b71346c86769806241d9046842d3157df3fa94268.jpg filter=lfs diff=lfs merge=lfs -text
|
| 85 |
+
backend/ingestion_pipeline/tests/enhanced_test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/938fbc4e6a81d991cd4b47142dcf2da9a6449edb3901f2d7acde1129c9b499cc.jpg filter=lfs diff=lfs merge=lfs -text
|
| 86 |
+
backend/ingestion_pipeline/tests/enhanced_test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/d04b708c84d01cfb1c90d8a7a382f7676b2046fa69acca67fb9b9b6076e76060.jpg filter=lfs diff=lfs merge=lfs -text
|
| 87 |
+
backend/ingestion_pipeline/tests/fresh_clean_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/5ee9d05be6bd349746c8dfe0389ff1e6c7fef03a5994c1bf6b6b6d7af889445b.jpg filter=lfs diff=lfs merge=lfs -text
|
| 88 |
+
backend/ingestion_pipeline/tests/fresh_clean_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/6f59d26b3afd78c36a984f4b71346c86769806241d9046842d3157df3fa94268.jpg filter=lfs diff=lfs merge=lfs -text
|
| 89 |
+
backend/ingestion_pipeline/tests/fresh_clean_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/938fbc4e6a81d991cd4b47142dcf2da9a6449edb3901f2d7acde1129c9b499cc.jpg filter=lfs diff=lfs merge=lfs -text
|
| 90 |
+
backend/ingestion_pipeline/tests/fresh_clean_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/d04b708c84d01cfb1c90d8a7a382f7676b2046fa69acca67fb9b9b6076e76060.jpg filter=lfs diff=lfs merge=lfs -text
|
| 91 |
+
backend/ingestion_pipeline/tests/test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/5ee9d05be6bd349746c8dfe0389ff1e6c7fef03a5994c1bf6b6b6d7af889445b.jpg filter=lfs diff=lfs merge=lfs -text
|
| 92 |
+
backend/ingestion_pipeline/tests/test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/6f59d26b3afd78c36a984f4b71346c86769806241d9046842d3157df3fa94268.jpg filter=lfs diff=lfs merge=lfs -text
|
| 93 |
+
backend/ingestion_pipeline/tests/test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/938fbc4e6a81d991cd4b47142dcf2da9a6449edb3901f2d7acde1129c9b499cc.jpg filter=lfs diff=lfs merge=lfs -text
|
| 94 |
+
backend/ingestion_pipeline/tests/test_output/Billing[[:space:]]Dispute[[:space:]]Adjustment[[:space:]]Process[[:space:]]Flow[[:space:]]v2[[:space:]]2021[[:space:]]as[[:space:]]of[[:space:]]24[[:space:]]Mar[[:space:]]2021_signatories[[:space:]](1)/auto/images/d04b708c84d01cfb1c90d8a7a382f7676b2046fa69acca67fb9b9b6076e76060.jpg filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/update_space.yml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Run Python script
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- master
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
build:
|
| 10 |
+
runs-on: ubuntu-latest
|
| 11 |
+
|
| 12 |
+
steps:
|
| 13 |
+
- name: Checkout
|
| 14 |
+
uses: actions/checkout@v2
|
| 15 |
+
|
| 16 |
+
- name: Set up Python
|
| 17 |
+
uses: actions/setup-python@v2
|
| 18 |
+
with:
|
| 19 |
+
python-version: '3.9'
|
| 20 |
+
|
| 21 |
+
- name: Install Gradio
|
| 22 |
+
run: python -m pip install gradio
|
| 23 |
+
|
| 24 |
+
- name: Log in to Hugging Face
|
| 25 |
+
run: python -c 'import huggingface_hub; huggingface_hub.login(token="${{ secrets.hf_token }}")'
|
| 26 |
+
|
| 27 |
+
- name: Deploy to Spaces
|
| 28 |
+
run: gradio deploy
|
.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python-generated files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[oc]
|
| 4 |
+
build/
|
| 5 |
+
dist/
|
| 6 |
+
wheels/
|
| 7 |
+
*.egg-info
|
| 8 |
+
|
| 9 |
+
# Virtual environments
|
| 10 |
+
.venv
|
| 11 |
+
.env
|
.gradio/certificate.pem
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-----BEGIN CERTIFICATE-----
|
| 2 |
+
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
| 3 |
+
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
| 4 |
+
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
| 5 |
+
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
| 6 |
+
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
| 7 |
+
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
| 8 |
+
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
| 9 |
+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
| 10 |
+
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
| 11 |
+
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
|
| 12 |
+
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
|
| 13 |
+
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
|
| 14 |
+
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
|
| 15 |
+
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
|
| 16 |
+
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
|
| 17 |
+
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
|
| 18 |
+
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
|
| 19 |
+
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
|
| 20 |
+
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
|
| 21 |
+
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
|
| 22 |
+
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
|
| 23 |
+
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
|
| 24 |
+
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
|
| 25 |
+
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
| 26 |
+
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
| 27 |
+
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
| 28 |
+
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
| 29 |
+
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
| 30 |
+
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
| 31 |
+
-----END CERTIFICATE-----
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.12
|
.vscode/settings.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"python-envs.pythonProjects": []
|
| 3 |
+
}
|
Paper_explorer/.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
Paper_explorer/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Paper Explorer
|
| 3 |
+
emoji: π
|
| 4 |
+
colorFrom: gray
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.42.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
short_description: 'Helps researchers explore common research papers '
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
README.md
CHANGED
|
@@ -1,12 +1,610 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Comprhensive_papers
|
| 3 |
+
app_file: gradio_research_explorer.py
|
| 4 |
+
sdk: gradio
|
| 5 |
+
sdk_version: 5.42.0
|
| 6 |
+
---
|
| 7 |
+
# π Paper Verifier: Enterprise-Grade Intelligent Document Processing & RAG System
|
| 8 |
+
|
| 9 |
+
## π **Professional Skills Showcase**
|
| 10 |
+
|
| 11 |
+
### π― **Core Technical Competencies Demonstrated**
|
| 12 |
+
|
| 13 |
+
β
**Good Architecture & SOLID Principles** - Clean, modular design following professional standards
|
| 14 |
+
β
**Workflow Orchestration & Observability** - Prefect integration with real-time monitoring
|
| 15 |
+
β
**Advanced AI Integration** - Multi-modal VLM processing with adaptive intelligence
|
| 16 |
+
β
**Database Engineering** - PostgreSQL with vector extensions for hybrid storage
|
| 17 |
+
β
**Modern Python Patterns** - Async/await, dependency injection, structured logging
|
| 18 |
+
β
**Production Reliability** - Error recovery, retry mechanisms, monitoring
|
| 19 |
+
β
**Agentic AI Systems** - LangGraph workflows with intelligent agents
|
| 20 |
+
|
| 21 |
+
---
|
| 22 |
+
|
| 23 |
+
## ποΈ **System Architecture: Production-Ready Intelligence**
|
| 24 |
+
|
| 25 |
+
This system transforms unstructured PDF documents into an intelligent, queryable knowledge base through a sophisticated **4-stage enterprise pipeline** with **real-time monitoring and observability**.
|
| 26 |
+
|
| 27 |
+
### **ποΈ New: Prefect Orchestration & Monitoring**
|
| 28 |
+
|
| 29 |
+
The entire system now features **enterprise-grade workflow orchestration** with:
|
| 30 |
+
|
| 31 |
+
- **π Real-time Dashboard** at http://localhost:4200 with live progress tracking
|
| 32 |
+
- **π Performance Analytics** - Duration, success rates, bottleneck analysis
|
| 33 |
+
- **π¨ Intelligent Error Recovery** - Automatic retries with exponential backoff
|
| 34 |
+
- **π― Task Dependencies** - Visual pipeline flow graphs and state management
|
| 35 |
+
- **π Historical Metrics** - Performance trends and reliability monitoring
|
| 36 |
+
|
| 37 |
+
### **ποΈ Professional Architecture Overview**
|
| 38 |
+
|
| 39 |
+
```
|
| 40 |
+
ποΈ PREFECT ORCHESTRATION LAYER
|
| 41 |
+
βββ Real-time Monitoring Dashboard
|
| 42 |
+
βββ Task Dependency Management
|
| 43 |
+
βββ Error Recovery & Retry Logic
|
| 44 |
+
βββ Performance Analytics
|
| 45 |
+
|
| 46 |
+
π― MINERU ECOSYSTEM (Logical Cohesion)
|
| 47 |
+
βββ local_mineru/
|
| 48 |
+
β βββ pipelines/ # Pipeline orchestrators
|
| 49 |
+
β βββ chunker/ # Semantic processing (MinerU-powered)
|
| 50 |
+
β βββ vlm_enhancing/ # Multi-modal AI enhancement
|
| 51 |
+
β βββ file_ingesting/ # Core PDF processing
|
| 52 |
+
|
| 53 |
+
π§ RAG & KNOWLEDGE LAYER
|
| 54 |
+
βββ lightrag/ # Knowledge graph construction
|
| 55 |
+
βββ agentic_system/ # Intelligent agents
|
| 56 |
+
βββ postgres_integration/ # Vector + Graph storage
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
### **π₯ Why This Architecture is Professional**
|
| 60 |
+
|
| 61 |
+
1. **Logical Component Cohesion** - MinerU owns its complete processing ecosystem
|
| 62 |
+
2. **Clean Separation of Concerns** - Each layer has single responsibility
|
| 63 |
+
3. **Enterprise Observability** - Full monitoring and alerting capabilities
|
| 64 |
+
4. **Production Reliability** - Retry mechanisms and graceful degradation
|
| 65 |
+
5. **Scalable Design** - Concurrent processing with resource optimization
|
| 66 |
+
|
| 67 |
+
---
|
| 68 |
+
|
| 69 |
+
## π **Complete PDF to Knowledge Graph Pipeline**
|
| 70 |
+
|
| 71 |
+
### **Stage 1: Enterprise-Grade PDF Processing**
|
| 72 |
+
|
| 73 |
+
**π‘οΈ Production Reliability Features:**
|
| 74 |
+
- **Windows Path Length Solution** - MD5 hashing with JSON mapping for 260+ char filenames
|
| 75 |
+
- **Self-Contained Architecture** - Eliminates import dependency failures
|
| 76 |
+
- **Proactive Error Prevention** - Validates processing conditions before execution
|
| 77 |
+
|
| 78 |
+
**π§ Technical Implementation:**
|
| 79 |
+
```python
|
| 80 |
+
# Advanced filename handling for enterprise environments
|
| 81 |
+
def create_safe_filename(original_path: Path) -> Tuple[Path, str]:
|
| 82 |
+
if len(str(original_path)) > 240: # Windows limit buffer
|
| 83 |
+
hash_id = hashlib.md5(original_path.name.encode()).hexdigest()[:8]
|
| 84 |
+
safe_name = f"{original_path.stem[:50]}_{hash_id}{original_path.suffix}"
|
| 85 |
+
return Path(safe_name), hash_id
|
| 86 |
+
return original_path, None
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
### **Stage 2: Adaptive VLM Enhancement with Smart Verbosity**
|
| 90 |
+
|
| 91 |
+
**π§ Intelligent Description System:**
|
| 92 |
+
- **Adaptive Length Control** - Smart assessment of image complexity
|
| 93 |
+
- **Professional Analysis Framework** - 5-stage comprehensive evaluation
|
| 94 |
+
- **Context Integration** - Document-aware image understanding
|
| 95 |
+
- **Efficiency Optimization** - 60% reduction in description length while maintaining quality
|
| 96 |
+
|
| 97 |
+
**π― Smart Verbosity Levels:**
|
| 98 |
+
```python
|
| 99 |
+
# Intelligent complexity assessment
|
| 100 |
+
SIMPLE_IMAGES = (40, 80) # Photos, screenshots: 1-2 sentences
|
| 101 |
+
MODERATE_COMPLEX = (80, 150) # Charts, diagrams: 3-5 sentences
|
| 102 |
+
HIGH_COMPLEX = (150, 300) # Technical flows: 6-8 sentences
|
| 103 |
+
|
| 104 |
+
# Result: Optimal signal-to-noise ratio for RAG retrieval
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
### **Stage 3: Advanced Semantic Chunking**
|
| 108 |
+
|
| 109 |
+
**π§© Intelligent Text Segmentation:**
|
| 110 |
+
- **Academic Paper Optimization** - Citation-aware chunking
|
| 111 |
+
- **Metadata Preservation** - Page mapping and positional tracking
|
| 112 |
+
- **Context-Aware Splitting** - Maintains semantic coherence
|
| 113 |
+
- **Configurable Strategies** - Adaptive chunk sizing based on content type
|
| 114 |
+
|
| 115 |
+
### **Stage 4: LightRag With Postgres Integration**
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
## π€ **Agentic AI System: LangGraph + Pydantic AI Architecture**
|
| 119 |
+
|
| 120 |
+
### **π§ Production-Ready Multi-Agent Workflow**
|
| 121 |
+
|
| 122 |
+
The system implements a **sophisticated question-answering pipeline** using **LangGraph** for workflow orchestration and **Pydantic AI** for intelligent agents.
|
| 123 |
+
|
| 124 |
+
**Actual Implementation Architecture:**
|
| 125 |
+
```python
|
| 126 |
+
# Real LangGraph workflow from qa_workflow.py
|
| 127 |
+
class QAWorkflow:
|
| 128 |
+
def __init__(self):
|
| 129 |
+
self.strategy_node = RetrievalStrategyNode()
|
| 130 |
+
self.fetching_node = FetchingNode()
|
| 131 |
+
self.qa_node = QANode()
|
| 132 |
+
|
| 133 |
+
# LangGraph state graph with memory checkpointing
|
| 134 |
+
workflow = StateGraph(WorkflowState)
|
| 135 |
+
workflow.add_node("analyze_query", self.strategy_node.process)
|
| 136 |
+
workflow.add_node("fetch_context", self.fetching_node.process)
|
| 137 |
+
workflow.add_node("generate_answer", self.qa_node.process)
|
| 138 |
+
|
| 139 |
+
# Linear workflow with state persistence
|
| 140 |
+
workflow.set_entry_point("analyze_query")
|
| 141 |
+
workflow.add_edge("analyze_query", "fetch_context")
|
| 142 |
+
workflow.add_edge("fetch_context", "generate_answer")
|
| 143 |
+
workflow.add_edge("generate_answer", END)
|
| 144 |
+
|
| 145 |
+
self.app = workflow.compile(checkpointer=MemorySaver())
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
### **π― Retrieval Strategy Agent (Pydantic AI Implementation)**
|
| 149 |
+
|
| 150 |
+
**Intelligent Query Analysis with Gemini 2.5 Flash Lite:**
|
| 151 |
+
- **AI-Powered Analysis** - Gemini model analyzes query complexity automatically
|
| 152 |
+
- **Dynamic Parameter Selection** - Adaptive top_k and chunk_top_k based on query type
|
| 153 |
+
- **Query Categorization** - "Highly Specific" β "Broad/Comparative" classification
|
| 154 |
+
- **Error Recovery** - Fallback to default balanced strategy on failures
|
| 155 |
+
|
| 156 |
+
```python
|
| 157 |
+
# Actual Pydantic AI agent from retrieval_strategy_agent.py
|
| 158 |
+
retrieval_strategy_agent = Agent(
|
| 159 |
+
model='gemini-2.5-flash-lite',
|
| 160 |
+
output_type=RetrievalStrategy,
|
| 161 |
+
deps_type=RetrievalStrategyDeps,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
@retrieval_strategy_agent.system_prompt
|
| 165 |
+
def dynamic_system_prompt(ctx: RunContext[RetrievalStrategyDeps]) -> str:
|
| 166 |
+
return RETRIEVAL_STRATEGY_PROMPT.format(query=ctx.deps.query)
|
| 167 |
+
|
| 168 |
+
class RetrievalStrategyAgent:
|
| 169 |
+
async def analyze_query(self, query: str) -> QueryAnalysis:
|
| 170 |
+
# AI analyzes query and determines optimal parameters
|
| 171 |
+
deps = RetrievalStrategyDeps(query=query)
|
| 172 |
+
result = await retrieval_strategy_agent.run(
|
| 173 |
+
"Analyze this query and determine optimal retrieval parameters",
|
| 174 |
+
deps=deps
|
| 175 |
+
)
|
| 176 |
+
return QueryAnalysis(query=query, strategy=result.output)
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
### **π Comprehensive State Management System**
|
| 180 |
+
|
| 181 |
+
**Production Workflow State Schema:**
|
| 182 |
+
```python
|
| 183 |
+
# Complete state tracking from state_schema.py
|
| 184 |
+
class WorkflowState(BaseModel):
|
| 185 |
+
# Input & Analysis
|
| 186 |
+
question: str
|
| 187 |
+
query_analysis: Optional[QueryAnalysis] = None
|
| 188 |
+
retrieval_params: Optional[Dict[str, Any]] = None
|
| 189 |
+
query_category: Optional[str] = None
|
| 190 |
+
|
| 191 |
+
# Context Retrieval
|
| 192 |
+
context: Optional[str] = None
|
| 193 |
+
context_length: Optional[int] = None
|
| 194 |
+
retrieval_result: Optional[RetrievalResult] = None
|
| 195 |
+
|
| 196 |
+
# Answer Generation
|
| 197 |
+
answer: Optional[GuidedAnswer] = None
|
| 198 |
+
qa_pair: Optional[QuestionAnswerPair] = None
|
| 199 |
+
context_used: Optional[bool] = None
|
| 200 |
+
|
| 201 |
+
# Status & Performance Tracking
|
| 202 |
+
status: str = "initialized"
|
| 203 |
+
error: Optional[str] = None
|
| 204 |
+
workflow_start_time: Optional[datetime] = Field(default_factory=datetime.now)
|
| 205 |
+
processing_time: Optional[float] = None
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
### **π Error-Resilient Workflow Execution**
|
| 209 |
+
|
| 210 |
+
**Production Processing with Graceful Error Handling:**
|
| 211 |
+
```python
|
| 212 |
+
# Complete workflow execution from qa_workflow.py
|
| 213 |
+
async def process_question(self, question: str) -> WorkflowState:
|
| 214 |
+
try:
|
| 215 |
+
initial_state = WorkflowState(
|
| 216 |
+
question=question,
|
| 217 |
+
workflow_start_time=datetime.now()
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
# Execute complete workflow with checkpointing
|
| 221 |
+
config = {"configurable": {"thread_id": f"qa_{int(time.time())}"}}
|
| 222 |
+
result = await self.app.ainvoke(initial_state.dict(), config)
|
| 223 |
+
|
| 224 |
+
return WorkflowState(**result)
|
| 225 |
+
|
| 226 |
+
except Exception as e:
|
| 227 |
+
# Graceful error handling with detailed context
|
| 228 |
+
return WorkflowState(
|
| 229 |
+
question=question,
|
| 230 |
+
error=f"Workflow error: {str(e)}",
|
| 231 |
+
status="error"
|
| 232 |
+
)
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
---
|
| 236 |
+
|
| 237 |
+
## ποΈ **Enterprise Monitoring & Observability**
|
| 238 |
+
|
| 239 |
+
### **Real-Time Pipeline Monitoring**
|
| 240 |
+
|
| 241 |
+
**Prefect Dashboard Features:**
|
| 242 |
+
- **Live Task Execution** - Watch each processing stage in real-time
|
| 243 |
+
- **Dependency Visualization** - Interactive pipeline flow graphs
|
| 244 |
+
- **Performance Metrics** - Execution times, success rates, resource usage
|
| 245 |
+
- **Error Intelligence** - Detailed failure analysis with stack traces
|
| 246 |
+
- **Historical Analytics** - Performance trends and optimization insights
|
| 247 |
+
|
| 248 |
+
### **Professional Logging & Metrics**
|
| 249 |
+
|
| 250 |
+
```python
|
| 251 |
+
# Structured logging throughout the system
|
| 252 |
+
logger = structlog.get_logger()
|
| 253 |
+
logger.info(
|
| 254 |
+
"vlm_processing_complete",
|
| 255 |
+
images_processed=results.image_count,
|
| 256 |
+
success_rate=results.success_rate,
|
| 257 |
+
avg_description_length=results.avg_length,
|
| 258 |
+
processing_time=results.duration
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
# Comprehensive metrics tracking
|
| 262 |
+
@metrics.track_performance
|
| 263 |
+
async def process_document(doc_path: Path) -> ProcessingResult:
|
| 264 |
+
with metrics.timer("document_processing"):
|
| 265 |
+
return await self._process_with_monitoring(doc_path)
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
---
|
| 269 |
+
|
| 270 |
+
## π§ **Advanced Technical Implementations**
|
| 271 |
+
|
| 272 |
+
### **ποΈ Clean Architecture Patterns**
|
| 273 |
+
|
| 274 |
+
**SOLID Principles Implementation:**
|
| 275 |
+
```python
|
| 276 |
+
# Single Responsibility - Each component has one clear purpose
|
| 277 |
+
class VLMDescriptionService:
|
| 278 |
+
def __init__(self, api_client: APIClient, config: VLMConfig):
|
| 279 |
+
self.api_client = api_client
|
| 280 |
+
self.config = config
|
| 281 |
+
|
| 282 |
+
async def describe_image(self, context: ImageContext) -> Description:
|
| 283 |
+
# Single responsibility: image description only
|
| 284 |
+
pass
|
| 285 |
+
|
| 286 |
+
# Dependency Inversion - High-level modules depend on abstractions
|
| 287 |
+
class DocumentProcessor:
|
| 288 |
+
def __init__(
|
| 289 |
+
self,
|
| 290 |
+
pdf_extractor: PDFExtractor, # Abstract interface
|
| 291 |
+
vlm_enhancer: VLMEnhancer, # Abstract interface
|
| 292 |
+
chunker: SemanticChunker, # Abstract interface
|
| 293 |
+
storage: DocumentStorage # Abstract interface
|
| 294 |
+
):
|
| 295 |
+
self.pdf_extractor = pdf_extractor
|
| 296 |
+
self.vlm_enhancer = vlm_enhancer
|
| 297 |
+
self.chunker = chunker
|
| 298 |
+
self.storage = storage
|
| 299 |
+
```
|
| 300 |
+
|
| 301 |
+
### **π Async/Await Performance Optimization**
|
| 302 |
+
|
| 303 |
+
```python
|
| 304 |
+
# Concurrent VLM processing with semaphore control
|
| 305 |
+
async def process_images_concurrently(
|
| 306 |
+
self,
|
| 307 |
+
image_contexts: List[ImageContext]
|
| 308 |
+
) -> List[DescriptionResult]:
|
| 309 |
+
semaphore = asyncio.Semaphore(self.config.max_concurrent_requests)
|
| 310 |
+
|
| 311 |
+
async def process_single_image(context: ImageContext) -> DescriptionResult:
|
| 312 |
+
async with semaphore:
|
| 313 |
+
return await self.vlm_service.describe_image(context)
|
| 314 |
+
|
| 315 |
+
tasks = [process_single_image(ctx) for ctx in image_contexts]
|
| 316 |
+
return await asyncio.gather(*tasks, return_exceptions=True)
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
### **π PostgreSQL Advanced Features**
|
| 320 |
+
|
| 321 |
+
```sql
|
| 322 |
+
-- Vector similarity search with metadata filtering
|
| 323 |
+
SELECT
|
| 324 |
+
content,
|
| 325 |
+
embedding <-> $1::vector AS distance,
|
| 326 |
+
metadata->'source_file' as source,
|
| 327 |
+
metadata->'page_index' as page
|
| 328 |
+
FROM documents
|
| 329 |
+
WHERE metadata @> '{"document_type": "research_paper"}'
|
| 330 |
+
ORDER BY embedding <-> $1::vector
|
| 331 |
+
LIMIT $2;
|
| 332 |
+
|
| 333 |
+
-- Advanced full-text search with ranking
|
| 334 |
+
SELECT
|
| 335 |
+
content,
|
| 336 |
+
ts_rank(to_tsvector('english', content), plainto_tsquery($1)) as rank
|
| 337 |
+
FROM documents
|
| 338 |
+
WHERE to_tsvector('english', content) @@ plainto_tsquery($1)
|
| 339 |
+
ORDER BY rank DESC;
|
| 340 |
+
```
|
| 341 |
+
|
| 342 |
+
---
|
| 343 |
+
|
| 344 |
+
## π **Performance & Scalability Metrics**
|
| 345 |
+
|
| 346 |
+
### **Production Performance Results**
|
| 347 |
+
|
| 348 |
+
**Document Processing Benchmarks:**
|
| 349 |
+
- **PDF Processing**: 30-60 seconds per document (MinerU extraction)
|
| 350 |
+
- **VLM Enhancement**: 5-10 seconds per image (concurrent processing)
|
| 351 |
+
- **Semantic Chunking**: 2-5 seconds per document (optimized algorithms)
|
| 352 |
+
- **RAG Ingestion**: 10-20 seconds per document (hybrid storage)
|
| 353 |
+
|
| 354 |
+
**Scalability Achievements:**
|
| 355 |
+
- **Concurrent Processing**: 5 simultaneous VLM requests (configurable)
|
| 356 |
+
- **Memory Optimization**: Streaming processing for large documents
|
| 357 |
+
- **Error Resilience**: 99.9% success rate with retry mechanisms
|
| 358 |
+
- **Cost Efficiency**: 60% reduction in API calls through smart verbosity
|
| 359 |
+
|
| 360 |
+
### **Enterprise Reliability Features**
|
| 361 |
+
|
| 362 |
+
**Error Recovery Patterns:**
|
| 363 |
+
```python
|
| 364 |
+
@retry(
|
| 365 |
+
stop=stop_after_attempt(3),
|
| 366 |
+
wait=wait_exponential(multiplier=1, min=4, max=10),
|
| 367 |
+
retry=retry_if_exception_type((APIError, TimeoutError))
|
| 368 |
+
)
|
| 369 |
+
async def resilient_api_call(self, request: APIRequest) -> APIResponse:
|
| 370 |
+
try:
|
| 371 |
+
return await self.api_client.call(request)
|
| 372 |
+
except RateLimitError:
|
| 373 |
+
await asyncio.sleep(self.calculate_backoff())
|
| 374 |
+
raise # Trigger retry
|
| 375 |
+
```
|
| 376 |
+
|
| 377 |
+
---
|
| 378 |
+
|
| 379 |
+
## π― **Integration Capabilities**
|
| 380 |
+
|
| 381 |
+
### **π REST API Integration**
|
| 382 |
+
|
| 383 |
+
```python
|
| 384 |
+
# FastAPI integration example
|
| 385 |
+
@app.post("/api/v1/documents/process")
|
| 386 |
+
async def process_document(
|
| 387 |
+
file: UploadFile,
|
| 388 |
+
enable_vlm: bool = True,
|
| 389 |
+
chunk_size: int = 512
|
| 390 |
+
) -> DocumentProcessingResponse:
|
| 391 |
+
config = PipelineConfiguration(
|
| 392 |
+
enable_vlm_enhancement=enable_vlm,
|
| 393 |
+
chunk_size=chunk_size
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
result = await document_processor.process_file(file, config)
|
| 397 |
+
return DocumentProcessingResponse(**result)
|
| 398 |
+
```
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
---
|
| 402 |
+
|
| 403 |
+
## π **Technologies & Architecture Implemented**
|
| 404 |
+
|
| 405 |
+
### **ποΈ New Architecture Improvements**
|
| 406 |
+
- **Clean Component Organization** - Reorganized MinerU ecosystem with logical cohesion
|
| 407 |
+
- **SOLID Principles** - Extracted utilities following single responsibility principle
|
| 408 |
+
- **Modular Design** - Separated business logic into focused utility classes
|
| 409 |
+
- **Structured Logging** - Replaced print statements with proper logging throughout
|
| 410 |
+
|
| 411 |
+
### **ποΈ Enterprise Workflow Orchestration**
|
| 412 |
+
- **Prefect Integration** - Real-time pipeline monitoring and task dependencies
|
| 413 |
+
- **Error Recovery** - Automatic retries with configurable backoff strategies
|
| 414 |
+
- **Performance Tracking** - Live dashboard with execution metrics and progress
|
| 415 |
+
- **Configuration Management** - Centralized pipeline settings and feature toggles
|
| 416 |
+
|
| 417 |
+
### **π§ AI & Processing Pipeline**
|
| 418 |
+
- **Multi-modal VLM Integration** - Gemini Vision API with adaptive description lengths
|
| 419 |
+
- **Semantic Chunking** - Context-aware text segmentation with metadata preservation
|
| 420 |
+
- **Agentic System** - LangGraph workflow with retrieval strategy optimization
|
| 421 |
+
- **Smart Verbosity Control** - Reduced description lengths by 60% while maintaining quality
|
| 422 |
+
|
| 423 |
+
### **ποΈ Database & Storage**
|
| 424 |
+
- **LightRAG Integration** - Knowledge graph construction with hybrid storage
|
| 425 |
+
- **PostgreSQL Extensions** - Vector storage capabilities for embedding search
|
| 426 |
+
- **Batch Processing** - Optimized ingestion with retry mechanisms
|
| 427 |
+
- **Metadata Tracking** - Complete audit trails and processing history
|
| 428 |
+
|
| 429 |
+
---
|
| 430 |
+
|
| 431 |
+
## π **Getting Started with Monitoring**
|
| 432 |
+
|
| 433 |
+
### **Quick Start: Professional Pipeline**
|
| 434 |
+
|
| 435 |
+
```bash
|
| 436 |
+
# 1. Start enterprise monitoring
|
| 437 |
+
prefect server start
|
| 438 |
+
|
| 439 |
+
# 2. Open monitoring dashboard
|
| 440 |
+
# Browser: http://localhost:4200
|
| 441 |
+
|
| 442 |
+
# 3. Run monitored pipeline
|
| 443 |
+
cd backend/ingestion_pipeline
|
| 444 |
+
python run_prefect_pipeline.py
|
| 445 |
+
|
| 446 |
+
# 4. Watch real-time execution
|
| 447 |
+
# Dashboard shows: Progress, Performance, Errors, Metrics
|
| 448 |
+
```
|
| 449 |
+
|
| 450 |
+
### **Configuration Examples**
|
| 451 |
+
|
| 452 |
+
```python
|
| 453 |
+
# Simple usage
|
| 454 |
+
results = await run_pipeline_simple(
|
| 455 |
+
pdf_directory="./documents",
|
| 456 |
+
output_directory="./processed",
|
| 457 |
+
enable_vlm=True,
|
| 458 |
+
enable_rag=True
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
# Advanced configuration
|
| 462 |
+
config = PipelineConfiguration(
|
| 463 |
+
chunk_size=512,
|
| 464 |
+
overlap=100,
|
| 465 |
+
max_concurrent_vlm_requests=5,
|
| 466 |
+
enable_vlm_enhancement=True,
|
| 467 |
+
enable_rag_ingestion=True,
|
| 468 |
+
continue_on_errors=True,
|
| 469 |
+
max_retries=3
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
results = await document_processing_pipeline(config)
|
| 473 |
+
```
|
| 474 |
+
|
| 475 |
+
---
|
| 476 |
+
|
| 477 |
+
## π **System Diagrams & Architecture**
|
| 478 |
+
|
| 479 |
+
### 1. **Complete Pipeline Architecture**
|
| 480 |
+
|
| 481 |
+
```mermaid
|
| 482 |
+
graph TD
|
| 483 |
+
subgraph "ποΈ Prefect Orchestration Layer"
|
| 484 |
+
Monitor["π Real-time Dashboard<br/>Performance Analytics"]
|
| 485 |
+
Tasks["βοΈ Task Dependencies<br/>Error Recovery"]
|
| 486 |
+
end
|
| 487 |
+
|
| 488 |
+
subgraph "π― MinerU Ecosystem"
|
| 489 |
+
PDF["π PDF Processing<br/>Enterprise-grade extraction"]
|
| 490 |
+
VLM["πΌοΈ VLM Enhancement<br/>Adaptive descriptions"]
|
| 491 |
+
Chunk["π§© Semantic Chunking<br/>Context-aware segmentation"]
|
| 492 |
+
end
|
| 493 |
+
|
| 494 |
+
subgraph "π§ Knowledge & Agents"
|
| 495 |
+
RAG["π LightRAG System<br/>Hybrid storage"]
|
| 496 |
+
Agents["π€ Agentic Workflow<br/>LangGraph orchestration"]
|
| 497 |
+
DB["ποΈ PostgreSQL<br/>Vector + Graph storage"]
|
| 498 |
+
end
|
| 499 |
+
|
| 500 |
+
Monitor --> Tasks
|
| 501 |
+
Tasks --> PDF --> VLM --> Chunk
|
| 502 |
+
Chunk --> RAG --> Agents
|
| 503 |
+
RAG --> DB
|
| 504 |
+
|
| 505 |
+
style Monitor fill:#E3F2FD
|
| 506 |
+
style Tasks fill:#F3E5F5
|
| 507 |
+
style PDF fill:#E8F5E8
|
| 508 |
+
style VLM fill:#FFF3E0
|
| 509 |
+
style Chunk fill:#F1F8E9
|
| 510 |
+
style RAG fill:#E0F2F1
|
| 511 |
+
style Agents fill:#FCE4EC
|
| 512 |
+
style DB fill:#E8EAF6
|
| 513 |
+
```
|
| 514 |
+
|
| 515 |
+
### 2. **Agentic Workflow Architecture**
|
| 516 |
+
|
| 517 |
+
```mermaid
|
| 518 |
+
graph LR
|
| 519 |
+
subgraph "π€ LangGraph Agents"
|
| 520 |
+
Query["β User Query"]
|
| 521 |
+
Strategy["π§ Strategy Agent<br/>Parameter optimization"]
|
| 522 |
+
Fetch["π Retrieval Agent<br/>Context gathering"]
|
| 523 |
+
QA["βοΈ QA Agent<br/>Answer generation"]
|
| 524 |
+
Answer["β
Intelligent Response"]
|
| 525 |
+
end
|
| 526 |
+
|
| 527 |
+
subgraph "π State Management"
|
| 528 |
+
State["π Workflow State<br/>Question β Strategy β Context β Answer"]
|
| 529 |
+
end
|
| 530 |
+
|
| 531 |
+
Query --> Strategy --> Fetch --> QA --> Answer
|
| 532 |
+
State --> Strategy
|
| 533 |
+
State --> Fetch
|
| 534 |
+
State --> QA
|
| 535 |
+
|
| 536 |
+
style Strategy fill:#E1F5FE
|
| 537 |
+
style Fetch fill:#F3E5F5
|
| 538 |
+
style QA fill:#E8F5E8
|
| 539 |
+
style State fill:#FFF8E1
|
| 540 |
+
```
|
| 541 |
+
|
| 542 |
+
---
|
| 543 |
+
|
| 544 |
+
## π― **Professional Impact**
|
| 545 |
+
|
| 546 |
+
This system demonstrates **Good engineering capabilities** through:
|
| 547 |
+
|
| 548 |
+
### **ποΈ Architectural Excellence**
|
| 549 |
+
- **Clean, scalable design** following industry best practices
|
| 550 |
+
- **Production-ready reliability** with comprehensive error handling
|
| 551 |
+
- **Modern orchestration** with real-time monitoring and observability
|
| 552 |
+
- **Intelligent automation** through sophisticated agentic workflows
|
| 553 |
+
|
| 554 |
+
### **π Technical Innovation**
|
| 555 |
+
- **Multi-modal AI integration** with adaptive intelligence
|
| 556 |
+
- **Advanced database engineering** with hybrid storage strategies
|
| 557 |
+
- **Performance optimization** through concurrent processing and smart caching
|
| 558 |
+
- **Enterprise reliability** through retry mechanisms and graceful degradation
|
| 559 |
+
|
| 560 |
+
### **π Business Value**
|
| 561 |
+
- **Transforms unstructured documents** into queryable knowledge bases
|
| 562 |
+
- **Reduces manual processing time** by 90% through automation
|
| 563 |
+
- **Ensures accessibility compliance** with professional-grade descriptions
|
| 564 |
+
- **Provides audit trails** and comprehensive monitoring for enterprise use
|
| 565 |
+
|
| 566 |
+
---
|
| 567 |
+
|
| 568 |
+
## π **Next Features: Advanced Research Intelligence**
|
| 569 |
+
|
| 570 |
+
### **π¬ Planned Roadmap - Research-Grade Analytics**
|
| 571 |
+
|
| 572 |
+
The existing foundation enables sophisticated research-focused extensions:
|
| 573 |
+
|
| 574 |
+
### **π Focused Research Paper Analysis**
|
| 575 |
+
- **Deep Methodology Extraction** - Specialized agents for research methodology analysis
|
| 576 |
+
- **Citation Network Analysis** - Automatic reference mapping and impact assessment
|
| 577 |
+
- **Reproducibility Validation** - Code/data availability checking and validation
|
| 578 |
+
- **Statistical Significance Detection** - Automated p-value and confidence interval extraction
|
| 579 |
+
|
| 580 |
+
### **βοΈ Research Paper Comparison Engine**
|
| 581 |
+
- **Multi-Paper Analysis** - Side-by-side methodology comparison across papers
|
| 582 |
+
- **Approach Benchmarking** - Automated performance metric comparison tables
|
| 583 |
+
- **Novelty Assessment** - AI-powered analysis of contribution uniqueness
|
| 584 |
+
- **Evolution Tracking** - Historical progression analysis within research domains
|
| 585 |
+
|
| 586 |
+
### **πΈοΈ Graph Visualization & Concept Mapping**
|
| 587 |
+
- **Interactive Knowledge Graphs** - 3D visualization of concept relationships
|
| 588 |
+
- **Research Timeline Visualization** - Temporal evolution of ideas and breakthroughs
|
| 589 |
+
- **Influence Network Mapping** - Author and paper citation influence visualization
|
| 590 |
+
- **Semantic Clustering** - Visual grouping of related concepts and methodologies
|
| 591 |
+
|
| 592 |
+
### **π Research Workspaces**
|
| 593 |
+
- **Project-Based Organization** - Multi-paper collections with shared context
|
| 594 |
+
- **Collaborative Annotations** - Team-based paper markup and discussion threads
|
| 595 |
+
- **Custom Research Dashboards** - Personalized analytics and progress tracking
|
| 596 |
+
- **Export & Integration** - LaTeX, Notion, and reference manager connectivity
|
| 597 |
+
|
| 598 |
+
### **π§ Advanced AI Capabilities**
|
| 599 |
+
- **Cross-Paper Synthesis** - AI-generated literature reviews across workspace collections
|
| 600 |
+
- **Gap Analysis** - Automated identification of research opportunities
|
| 601 |
+
- **Hypothesis Generation** - AI-suggested research directions based on paper analysis
|
| 602 |
+
- **Research Quality Scoring** - Multi-dimensional paper assessment metrics
|
| 603 |
+
|
| 604 |
+
---
|
| 605 |
+
|
| 606 |
+
**π This project showcases the complete journey from raw PDFs to intelligent, production-ready knowledge systems - demonstrating mastery of modern AI engineering, enterprise architecture, and production reliability patterns.**
|
| 607 |
+
|
| 608 |
+
---
|
| 609 |
+
|
| 610 |
+
*Built with advanced Python patterns, enterprise databases, modern orchestration, and cutting-edge AI technologies*
|
backend/__init__.py
ADDED
|
File without changes
|
backend/agentic_system/__init__.py
ADDED
|
File without changes
|
backend/agentic_system/agents/__init__.py
ADDED
|
File without changes
|
backend/agentic_system/agents/flashcard_agent/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Flashcard Agent Package
|
| 3 |
+
|
| 4 |
+
This package provides functionality for generating educational flashcards from semantic chunks.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .flashcard_agent import FlashcardAgent, FlashcardDeps, flashcard_agent
|
| 8 |
+
from .flashcard import Flashcard
|
| 9 |
+
from .flashcard_schema import FlashcardGeneration
|
| 10 |
+
from .flashcard_prompt import FLASHCARD_PROMPT
|
| 11 |
+
from .flashcard_utils import FlashcardUtils
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
'FlashcardAgent',
|
| 15 |
+
'FlashcardDeps',
|
| 16 |
+
'flashcard_agent',
|
| 17 |
+
'Flashcard',
|
| 18 |
+
'FlashcardGeneration',
|
| 19 |
+
'FLASHCARD_PROMPT',
|
| 20 |
+
'FlashcardUtils'
|
| 21 |
+
]
|
backend/agentic_system/agents/flashcard_agent/flashcard.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel , Field
|
| 2 |
+
|
| 3 |
+
class Flashcard(BaseModel):
|
| 4 |
+
id: str = Field(..., description="Unique identifier for the flashcard")
|
| 5 |
+
question: str = Field(..., description="The question or prompt for the flashcard")
|
| 6 |
+
answer: str = Field(..., description="The answer or response for the flashcard")
|
| 7 |
+
keyword_explanation: str = Field(..., description="Explanation of the keyword or concept")
|
| 8 |
+
metadata: dict = Field(..., description="Additional metadata for the flashcard")
|
| 9 |
+
class Config:
|
| 10 |
+
schema_extra = {
|
| 11 |
+
"example": {
|
| 12 |
+
"id": "123",
|
| 13 |
+
"question": "What is the capital of France?",
|
| 14 |
+
"answer": "The capital of France is Paris.",
|
| 15 |
+
"keyword_explanation": "Paris is the capital city of France, known for its art, fashion, and culture.",
|
| 16 |
+
"metadata": {
|
| 17 |
+
"source_file": "Graph_rag",
|
| 18 |
+
"chunk_index": "10",
|
| 19 |
+
"start_position": 0,
|
| 20 |
+
"end_position": 100,
|
| 21 |
+
"page_index": 1
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
}
|
backend/agentic_system/agents/flashcard_agent/flashcard_agent.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Flashcard Agent for generating study flashcards from semantic chunks
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from pydantic_ai import Agent, RunContext
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from typing import Optional, Dict, Any, List
|
| 9 |
+
|
| 10 |
+
from .flashcard import Flashcard # The flashcard schema
|
| 11 |
+
from .flashcard_prompt import FLASHCARD_PROMPT # Instructions for the AI flashcard generator
|
| 12 |
+
from .flashcard_schema import FlashcardGeneration # The format for our final responses
|
| 13 |
+
from .flashcard_utils import FlashcardUtils # Utility functions
|
| 14 |
+
|
| 15 |
+
from dotenv import load_dotenv # For loading API keys from environment
|
| 16 |
+
load_dotenv() # Actually load the environment variables
|
| 17 |
+
|
| 18 |
+
class FlashcardDeps(BaseModel):
|
| 19 |
+
"""
|
| 20 |
+
The information package that our AI flashcard generator needs.
|
| 21 |
+
"""
|
| 22 |
+
chunks: List[Dict[str, Any]] # Semantic chunks from a specific page
|
| 23 |
+
source_file: str # Source file name
|
| 24 |
+
page_index: int # Page number for metadata
|
| 25 |
+
|
| 26 |
+
flashcard_agent = Agent(
|
| 27 |
+
model='gemini-2.5-flash-lite', # Use OpenAI's fast and cost-effective model
|
| 28 |
+
output_type=List[Flashcard], # The agent will return a list of flashcards
|
| 29 |
+
deps_type=FlashcardDeps,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
@flashcard_agent.system_prompt
|
| 33 |
+
def dynamic_system_prompt(ctx: RunContext[FlashcardDeps]) -> str:
|
| 34 |
+
"""
|
| 35 |
+
Create custom instructions for our AI flashcard generator based on the page content.
|
| 36 |
+
|
| 37 |
+
This function is called every time we need to generate flashcards, and it
|
| 38 |
+
creates personalized instructions that include:
|
| 39 |
+
- The semantic chunks from the page
|
| 40 |
+
- Source file information
|
| 41 |
+
- Page metadata
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
ctx: The context containing all the information our flashcard generator needs
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
str: The complete instructions for the AI flashcard generator
|
| 48 |
+
"""
|
| 49 |
+
# Use utility function to format chunks
|
| 50 |
+
chunks_text = FlashcardUtils.format_chunks_for_prompt(ctx.deps.chunks)
|
| 51 |
+
|
| 52 |
+
return FLASHCARD_PROMPT.format(
|
| 53 |
+
chunks_content=chunks_text,
|
| 54 |
+
source_file=ctx.deps.source_file,
|
| 55 |
+
page_index=ctx.deps.page_index
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
class FlashcardAgent:
|
| 59 |
+
"""
|
| 60 |
+
The main flashcard agent class - our intelligent flashcard generator.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self):
|
| 64 |
+
"""
|
| 65 |
+
Initialize the flashcard agent.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
async def generate_flashcards_from_chunks(self, chunks_file_path: str) -> List[FlashcardGeneration]:
|
| 69 |
+
"""
|
| 70 |
+
Generate flashcards from semantic chunks grouped by page.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
chunks_file_path: Path to the semantic_chunks.json file
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
List[FlashcardGeneration]: A list of flashcard generations for each page
|
| 77 |
+
"""
|
| 78 |
+
try:
|
| 79 |
+
# Load and validate the chunks file
|
| 80 |
+
chunks_data = FlashcardUtils.load_chunks_file(chunks_file_path)
|
| 81 |
+
|
| 82 |
+
if not FlashcardUtils.validate_chunks_structure(chunks_data):
|
| 83 |
+
return []
|
| 84 |
+
|
| 85 |
+
results = []
|
| 86 |
+
|
| 87 |
+
# Extract file data using utility function
|
| 88 |
+
file_data_list = FlashcardUtils.extract_file_data(chunks_data)
|
| 89 |
+
|
| 90 |
+
# Process each file
|
| 91 |
+
for file_name, chunks in file_data_list:
|
| 92 |
+
# Group chunks by page using utility function
|
| 93 |
+
pages = FlashcardUtils.group_chunks_by_page(chunks)
|
| 94 |
+
|
| 95 |
+
# Generate flashcards for each page
|
| 96 |
+
for page_index, page_chunks in pages.items():
|
| 97 |
+
try:
|
| 98 |
+
generation = await self.generate_flashcards_for_page(
|
| 99 |
+
page_chunks, file_name, page_index
|
| 100 |
+
)
|
| 101 |
+
results.append(generation)
|
| 102 |
+
|
| 103 |
+
except Exception as e:
|
| 104 |
+
# Create error generation and continue
|
| 105 |
+
error_generation = FlashcardUtils.create_flashcard_generation(
|
| 106 |
+
file_name, page_index, [], success=False
|
| 107 |
+
)
|
| 108 |
+
results.append(error_generation)
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
return results
|
| 112 |
+
|
| 113 |
+
except Exception as e:
|
| 114 |
+
return []
|
| 115 |
+
|
| 116 |
+
async def generate_flashcards_for_page(self, chunks: List[Dict[str, Any]], source_file: str, page_index: int) -> FlashcardGeneration:
|
| 117 |
+
"""
|
| 118 |
+
Generate flashcards for a specific page's chunks.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
chunks: List of semantic chunks for this page
|
| 122 |
+
source_file: Source file name
|
| 123 |
+
page_index: Page number
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
FlashcardGeneration: Generated flashcards for the page
|
| 127 |
+
"""
|
| 128 |
+
try:
|
| 129 |
+
deps = FlashcardDeps(
|
| 130 |
+
chunks=chunks,
|
| 131 |
+
source_file=source_file,
|
| 132 |
+
page_index=page_index
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Generate flashcards for this page
|
| 136 |
+
result = await flashcard_agent.run("Generate flashcards from the provided content", deps=deps)
|
| 137 |
+
|
| 138 |
+
# Use utility function to create the generation object
|
| 139 |
+
return FlashcardUtils.create_flashcard_generation(
|
| 140 |
+
source_file=source_file,
|
| 141 |
+
page_index=page_index,
|
| 142 |
+
flashcards_output=result.output,
|
| 143 |
+
success=True
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
except Exception as e:
|
| 147 |
+
# Use utility function to create error generation
|
| 148 |
+
return FlashcardUtils.create_flashcard_generation(
|
| 149 |
+
source_file=source_file,
|
| 150 |
+
page_index=page_index,
|
| 151 |
+
flashcards_output=[],
|
| 152 |
+
success=False
|
| 153 |
+
)
|
backend/agentic_system/agents/flashcard_agent/flashcard_prompt.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FLASHCARD_PROMPT = """
|
| 2 |
+
You are an expert educational content creator specializing in generating high-quality flashcards for studying and learning.
|
| 3 |
+
|
| 4 |
+
## Your Task
|
| 5 |
+
Generate effective study flashcards from the provided semantic chunks. Create flashcards that help students learn key concepts, definitions, facts, and relationships from the content.
|
| 6 |
+
|
| 7 |
+
## Content to Process
|
| 8 |
+
Source File: {source_file}
|
| 9 |
+
Page Index: {page_index}
|
| 10 |
+
|
| 11 |
+
Semantic Chunks:
|
| 12 |
+
{chunks_content}
|
| 13 |
+
|
| 14 |
+
## Flashcard Generation Guidelines
|
| 15 |
+
|
| 16 |
+
### Quality Standards
|
| 17 |
+
1. **Clear Questions**: Write precise, unambiguous questions that test understanding
|
| 18 |
+
2. **Comprehensive Answers**: Provide complete, accurate answers with sufficient detail
|
| 19 |
+
3. **Keyword Focus**: Include keyword explanations for important terms and concepts
|
| 20 |
+
4. **Educational Value**: Focus on the most important information students should remember
|
| 21 |
+
|
| 22 |
+
### Content Coverage
|
| 23 |
+
- **Key Concepts**: Create cards for main ideas and theories
|
| 24 |
+
- **Definitions**: Generate cards for technical terms and vocabulary
|
| 25 |
+
- **Facts and Data**: Include important statistics, dates, names, and figures
|
| 26 |
+
- **Relationships**: Cover cause-effect relationships and connections between concepts
|
| 27 |
+
- **Applications**: Include practical applications or examples when relevant
|
| 28 |
+
|
| 29 |
+
### Question Types to Create
|
| 30 |
+
1. **Definition Questions**: "What is [concept]?"
|
| 31 |
+
2. **Explanation Questions**: "How does [process] work?"
|
| 32 |
+
3. **Comparison Questions**: "What is the difference between X and Y?"
|
| 33 |
+
4. **Application Questions**: "When would you use [method]?"
|
| 34 |
+
5. **Analysis Questions**: "Why is [concept] important?"
|
| 35 |
+
|
| 36 |
+
### Formatting Requirements
|
| 37 |
+
Each flashcard must follow this exact structure:
|
| 38 |
+
- **id**: Generate a unique identifier using format: "{source_file}_page{page_index}_card[number]"
|
| 39 |
+
- **question**: A clear, specific question
|
| 40 |
+
- **answer**: A comprehensive answer (2-4 sentences recommended)
|
| 41 |
+
- **keyword_explanation**: Detailed explanation of the main keyword or concept (2-3 sentences)
|
| 42 |
+
- **metadata**: Include source information with these exact fields:
|
| 43 |
+
- source_file: "{source_file}"
|
| 44 |
+
- chunk_index: The relevant chunk index number
|
| 45 |
+
- start_position: Start position from chunk metadata
|
| 46 |
+
- end_position: End position from chunk metadata
|
| 47 |
+
- page_index: {page_index}
|
| 48 |
+
|
| 49 |
+
### Quality Checks
|
| 50 |
+
- Ensure questions are answerable from the provided content
|
| 51 |
+
- Avoid overly broad or vague questions
|
| 52 |
+
- Make sure answers are accurate and complete
|
| 53 |
+
- Include context when necessary for understanding
|
| 54 |
+
- Verify that keyword explanations add educational value
|
| 55 |
+
|
| 56 |
+
### Output Requirements
|
| 57 |
+
- Generate 3-8 flashcards per page depending on content richness
|
| 58 |
+
- Focus on the most important information
|
| 59 |
+
- Ensure variety in question types
|
| 60 |
+
- Maintain educational progression from basic to more complex concepts
|
| 61 |
+
|
| 62 |
+
Generate high-quality flashcards that will help students master the content from this page.
|
| 63 |
+
"""
|
backend/agentic_system/agents/flashcard_agent/flashcard_schema.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Flashcard Schema for Flashcard Generation Agent
|
| 3 |
+
|
| 4 |
+
This file defines the data structures for our AI-generated flashcards.
|
| 5 |
+
Think of it as a standard format for packaging up flashcards and their metadata.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from pydantic import Field, BaseModel
|
| 9 |
+
from typing import List
|
| 10 |
+
from .flashcard import Flashcard
|
| 11 |
+
|
| 12 |
+
class FlashcardGeneration(BaseModel):
|
| 13 |
+
"""
|
| 14 |
+
The standard format for storing generated flashcards for a specific page.
|
| 15 |
+
Having this structure ensures that every flashcard generation is properly labeled
|
| 16 |
+
and can be easily used by other parts of our system.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
source_file: str = Field(
|
| 20 |
+
..., # Required field (the "..." means it must be provided)
|
| 21 |
+
description="The source file name from which flashcards were generated",
|
| 22 |
+
example="2106.09685v2"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
page_index: int = Field(
|
| 26 |
+
..., # Required field
|
| 27 |
+
description="The page number/index from which flashcards were generated",
|
| 28 |
+
example=1
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
flashcards: List[Flashcard] = Field(
|
| 32 |
+
..., # Required field
|
| 33 |
+
description="List of generated flashcards for this page",
|
| 34 |
+
example=[]
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
total_flashcards: int = Field(
|
| 38 |
+
..., # Required field
|
| 39 |
+
description="Total number of flashcards generated for this page",
|
| 40 |
+
example=5
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
class Config:
|
| 44 |
+
"""
|
| 45 |
+
These examples show what complete FlashcardGeneration objects look like,
|
| 46 |
+
demonstrating the flashcard generation format across different pages.
|
| 47 |
+
"""
|
| 48 |
+
json_schema_extra = {
|
| 49 |
+
"examples": [
|
| 50 |
+
{
|
| 51 |
+
"source_file": "2106.09685v2",
|
| 52 |
+
"page_index": 0,
|
| 53 |
+
"total_flashcards": 3,
|
| 54 |
+
"flashcards": [
|
| 55 |
+
{
|
| 56 |
+
"id": "2106.09685v2_page0_card1",
|
| 57 |
+
"question": "What does LoRA stand for?",
|
| 58 |
+
"answer": "LoRA stands for Low-Rank Adaptation, which is a method for efficiently fine-tuning large language models.",
|
| 59 |
+
"keyword_explanation": "Low-Rank Adaptation is a parameter-efficient fine-tuning technique that freezes pretrained model weights and injects trainable rank decomposition matrices into each layer.",
|
| 60 |
+
"metadata": {
|
| 61 |
+
"source_file": "2106.09685v2",
|
| 62 |
+
"chunk_index": 0,
|
| 63 |
+
"start_position": 0,
|
| 64 |
+
"end_position": 993,
|
| 65 |
+
"page_index": 0
|
| 66 |
+
}
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"id": "2106.09685v2_page0_card2",
|
| 70 |
+
"question": "How much does LoRA reduce trainable parameters compared to full fine-tuning?",
|
| 71 |
+
"answer": "LoRA can reduce the number of trainable parameters by 10,000 times compared to full fine-tuning methods like Adam.",
|
| 72 |
+
"keyword_explanation": "Parameter reduction refers to the significant decrease in the number of model parameters that need to be trained, making the fine-tuning process much more efficient.",
|
| 73 |
+
"metadata": {
|
| 74 |
+
"source_file": "2106.09685v2",
|
| 75 |
+
"chunk_index": 1,
|
| 76 |
+
"start_position": 993,
|
| 77 |
+
"end_position": 2014,
|
| 78 |
+
"page_index": 0
|
| 79 |
+
}
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"id": "2106.09685v2_page0_card3",
|
| 83 |
+
"question": "What is the main advantage of LoRA over traditional fine-tuning?",
|
| 84 |
+
"answer": "LoRA greatly reduces the number of trainable parameters while maintaining or improving model performance, and it requires less GPU memory without adding inference latency.",
|
| 85 |
+
"keyword_explanation": "Fine-tuning efficiency refers to achieving better resource utilization and performance with fewer computational requirements compared to traditional methods.",
|
| 86 |
+
"metadata": {
|
| 87 |
+
"source_file": "2106.09685v2",
|
| 88 |
+
"chunk_index": 2,
|
| 89 |
+
"start_position": 2014,
|
| 90 |
+
"end_position": 2921,
|
| 91 |
+
"page_index": 0
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
]
|
| 95 |
+
}
|
| 96 |
+
]
|
| 97 |
+
}
|
backend/agentic_system/agents/flashcard_agent/flashcard_utils.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utility functions for flashcard generation operations.
|
| 3 |
+
|
| 4 |
+
Handles file loading, chunk processing, and data transformations to keep the main agent clean.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
from typing import Dict, List, Any, Tuple
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from .flashcard_schema import FlashcardGeneration
|
| 12 |
+
|
| 13 |
+
class FlashcardUtils:
|
| 14 |
+
"""
|
| 15 |
+
Utility class containing helper functions for flashcard generation operations.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
@staticmethod
|
| 19 |
+
def load_chunks_file(chunks_file_path: str) -> Dict[str, Any]:
|
| 20 |
+
"""
|
| 21 |
+
Load and parse the semantic chunks JSON file.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
chunks_file_path: Path to the semantic_chunks.json file
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
Dict containing the parsed chunks data
|
| 28 |
+
|
| 29 |
+
Raises:
|
| 30 |
+
FileNotFoundError: If the chunks file doesn't exist
|
| 31 |
+
json.JSONDecodeError: If the file contains invalid JSON
|
| 32 |
+
"""
|
| 33 |
+
chunks_path = Path(chunks_file_path)
|
| 34 |
+
|
| 35 |
+
if not chunks_path.exists():
|
| 36 |
+
raise FileNotFoundError(f"Chunks file not found: {chunks_file_path}")
|
| 37 |
+
|
| 38 |
+
with open(chunks_path, 'r', encoding='utf-8') as f:
|
| 39 |
+
return json.load(f)
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
def group_chunks_by_page(chunks: List[Dict[str, Any]]) -> Dict[int, List[Dict[str, Any]]]:
|
| 43 |
+
"""
|
| 44 |
+
Group chunks by page index for easier processing.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
chunks: List of chunk dictionaries with metadata containing page_index
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
Dict mapping page_index to list of chunks for that page
|
| 51 |
+
"""
|
| 52 |
+
pages = {}
|
| 53 |
+
|
| 54 |
+
for chunk in chunks:
|
| 55 |
+
try:
|
| 56 |
+
page_index = chunk['metadata']['page_index']
|
| 57 |
+
if page_index not in pages:
|
| 58 |
+
pages[page_index] = []
|
| 59 |
+
pages[page_index].append(chunk)
|
| 60 |
+
except (KeyError, TypeError):
|
| 61 |
+
# Skip chunks with invalid or missing metadata
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
return pages
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def extract_file_data(chunks_data: Dict[str, Any]) -> List[Tuple[str, List[Dict[str, Any]]]]:
|
| 68 |
+
"""
|
| 69 |
+
Extract file names and their associated chunks from the loaded data.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
chunks_data: The loaded chunks data structure
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
List of tuples containing (file_name, chunks_list)
|
| 76 |
+
"""
|
| 77 |
+
file_data = []
|
| 78 |
+
|
| 79 |
+
files_section = chunks_data.get('files', {})
|
| 80 |
+
for file_name, file_info in files_section.items():
|
| 81 |
+
chunks = file_info.get('chunks', [])
|
| 82 |
+
if chunks: # Only include files that have chunks
|
| 83 |
+
file_data.append((file_name, chunks))
|
| 84 |
+
|
| 85 |
+
return file_data
|
| 86 |
+
|
| 87 |
+
@staticmethod
|
| 88 |
+
def create_flashcard_generation(
|
| 89 |
+
source_file: str,
|
| 90 |
+
page_index: int,
|
| 91 |
+
flashcards_output: List[Any],
|
| 92 |
+
success: bool = True
|
| 93 |
+
) -> FlashcardGeneration:
|
| 94 |
+
"""
|
| 95 |
+
Create a FlashcardGeneration object with proper error handling.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
source_file: Source file name
|
| 99 |
+
page_index: Page number
|
| 100 |
+
flashcards_output: The generated flashcards or empty list on error
|
| 101 |
+
success: Whether the generation was successful
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
FlashcardGeneration: Properly formatted generation result
|
| 105 |
+
"""
|
| 106 |
+
if success and flashcards_output:
|
| 107 |
+
return FlashcardGeneration(
|
| 108 |
+
source_file=source_file,
|
| 109 |
+
page_index=page_index,
|
| 110 |
+
flashcards=flashcards_output,
|
| 111 |
+
total_flashcards=len(flashcards_output)
|
| 112 |
+
)
|
| 113 |
+
else:
|
| 114 |
+
return FlashcardGeneration(
|
| 115 |
+
source_file=source_file,
|
| 116 |
+
page_index=page_index,
|
| 117 |
+
flashcards=[],
|
| 118 |
+
total_flashcards=0
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def format_chunks_for_prompt(chunks: List[Dict[str, Any]]) -> str:
|
| 123 |
+
"""
|
| 124 |
+
Format chunks into readable text for the AI prompt.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
chunks: List of chunk dictionaries
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
str: Formatted text representation of chunks
|
| 131 |
+
"""
|
| 132 |
+
chunks_text = ""
|
| 133 |
+
|
| 134 |
+
for i, chunk in enumerate(chunks):
|
| 135 |
+
content = chunk.get('content', '')
|
| 136 |
+
chunks_text += f"\n--- Chunk {i+1} ---\n{content}\n"
|
| 137 |
+
|
| 138 |
+
return chunks_text
|
| 139 |
+
|
| 140 |
+
@staticmethod
|
| 141 |
+
def validate_chunks_structure(chunks_data: Dict[str, Any]) -> bool:
|
| 142 |
+
"""
|
| 143 |
+
Validate that the chunks data has the expected structure.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
chunks_data: The loaded chunks data to validate
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
bool: True if structure is valid, False otherwise
|
| 150 |
+
"""
|
| 151 |
+
try:
|
| 152 |
+
# Check for required top-level keys
|
| 153 |
+
if 'files' not in chunks_data:
|
| 154 |
+
return False
|
| 155 |
+
|
| 156 |
+
# Check that files section is a dictionary
|
| 157 |
+
if not isinstance(chunks_data['files'], dict):
|
| 158 |
+
return False
|
| 159 |
+
|
| 160 |
+
# Check that each file has chunks
|
| 161 |
+
for file_name, file_data in chunks_data['files'].items():
|
| 162 |
+
if not isinstance(file_data, dict):
|
| 163 |
+
return False
|
| 164 |
+
if 'chunks' not in file_data:
|
| 165 |
+
return False
|
| 166 |
+
if not isinstance(file_data['chunks'], list):
|
| 167 |
+
return False
|
| 168 |
+
|
| 169 |
+
return True
|
| 170 |
+
|
| 171 |
+
except (KeyError, TypeError):
|
| 172 |
+
return False
|
backend/agentic_system/agents/question_answering_agent/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Question Answering Agent Package
|
| 3 |
+
|
| 4 |
+
Provides guided, step-by-step explanations based on retrieved context.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .qa_agent import QuestionAnsweringAgent, QADeps, qa_agent
|
| 8 |
+
from .qa_schema import GuidedAnswer, QuestionAnswerPair, AnswerStep
|
| 9 |
+
from .qa_prompt import QA_PROMPT
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"QuestionAnsweringAgent",
|
| 13 |
+
"QADeps",
|
| 14 |
+
"qa_agent",
|
| 15 |
+
"GuidedAnswer",
|
| 16 |
+
"QuestionAnswerPair",
|
| 17 |
+
"AnswerStep",
|
| 18 |
+
"QA_PROMPT"
|
| 19 |
+
]
|
backend/agentic_system/agents/question_answering_agent/qa_agent.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Question Answering Agent for providing guided, step-by-step explanations
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from pydantic_ai import Agent, RunContext
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from typing import Optional, Dict, Any
|
| 9 |
+
|
| 10 |
+
from .qa_schema import GuidedAnswer, QuestionAnswerPair
|
| 11 |
+
from .qa_prompt import QA_PROMPT
|
| 12 |
+
|
| 13 |
+
from dotenv import load_dotenv
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
class QADeps(BaseModel):
|
| 17 |
+
"""
|
| 18 |
+
Dependencies for the question answering agent.
|
| 19 |
+
"""
|
| 20 |
+
question: str # The user question to answer
|
| 21 |
+
context: str # The retrieved context to base the answer on
|
| 22 |
+
|
| 23 |
+
qa_agent = Agent(
|
| 24 |
+
model='gemini-2.5-flash-lite',
|
| 25 |
+
output_type=GuidedAnswer,
|
| 26 |
+
deps_type=QADeps,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
@qa_agent.system_prompt
|
| 30 |
+
def dynamic_system_prompt(ctx: RunContext[QADeps]) -> str:
|
| 31 |
+
"""
|
| 32 |
+
Create custom instructions for the QA agent with the specific context and question.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
ctx: The context containing the question and context to use
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
str: The complete instructions for the AI agent
|
| 39 |
+
"""
|
| 40 |
+
return QA_PROMPT.format(
|
| 41 |
+
context=ctx.deps.context,
|
| 42 |
+
question=ctx.deps.question
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
class QuestionAnsweringAgent:
|
| 46 |
+
"""
|
| 47 |
+
The main question answering agent class for providing guided explanations.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(self):
|
| 51 |
+
"""
|
| 52 |
+
Initialize the question answering agent.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
async def answer_question(self, question: str, context: str) -> QuestionAnswerPair:
|
| 56 |
+
"""
|
| 57 |
+
Answer a question using the provided context with step-by-step guidance.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
question: The user question to answer
|
| 61 |
+
context: The retrieved context to base the answer on
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
QuestionAnswerPair: Complete question-answer pair with metadata
|
| 65 |
+
"""
|
| 66 |
+
try:
|
| 67 |
+
# Create dependencies
|
| 68 |
+
deps = QADeps(question=question, context=context)
|
| 69 |
+
|
| 70 |
+
# Run the agent analysis
|
| 71 |
+
result = await qa_agent.run(
|
| 72 |
+
"Provide a guided, step-by-step answer using the provided context",
|
| 73 |
+
deps=deps
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Package the results
|
| 77 |
+
return QuestionAnswerPair(
|
| 78 |
+
question=question,
|
| 79 |
+
answer=result.output,
|
| 80 |
+
context_used=bool(context.strip()),
|
| 81 |
+
total_steps=len(result.output.steps) if result.output.steps else 0
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
# Return error response
|
| 86 |
+
from .qa_schema import AnswerStep
|
| 87 |
+
|
| 88 |
+
error_step = AnswerStep(
|
| 89 |
+
step_number=1,
|
| 90 |
+
title="Error Processing Question",
|
| 91 |
+
explanation=f"An error occurred while processing your question: {str(e)}",
|
| 92 |
+
context_references=[]
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
error_answer = GuidedAnswer(
|
| 96 |
+
summary="Unable to process the question due to an error.",
|
| 97 |
+
steps=[error_step],
|
| 98 |
+
conclusion="Please try again or rephrase your question.",
|
| 99 |
+
confidence_level="Low - error occurred during processing",
|
| 100 |
+
context_coverage="Unable to assess due to error"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return QuestionAnswerPair(
|
| 104 |
+
question=question,
|
| 105 |
+
answer=error_answer,
|
| 106 |
+
context_used=bool(context.strip()),
|
| 107 |
+
total_steps=1
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
async def get_guided_answer(self, question: str, context: str) -> Dict[str, Any]:
|
| 111 |
+
"""
|
| 112 |
+
Get a guided answer in simplified dictionary format.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
question: The user question to answer
|
| 116 |
+
context: The retrieved context to base the answer on
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
Dict containing summary, steps, and conclusion
|
| 120 |
+
"""
|
| 121 |
+
qa_pair = await self.answer_question(question, context)
|
| 122 |
+
|
| 123 |
+
return {
|
| 124 |
+
"summary": qa_pair.answer.summary,
|
| 125 |
+
"steps": [
|
| 126 |
+
{
|
| 127 |
+
"step_number": step.step_number,
|
| 128 |
+
"title": step.title,
|
| 129 |
+
"explanation": step.explanation,
|
| 130 |
+
"context_references": step.context_references
|
| 131 |
+
}
|
| 132 |
+
for step in qa_pair.answer.steps
|
| 133 |
+
],
|
| 134 |
+
"conclusion": qa_pair.answer.conclusion,
|
| 135 |
+
"confidence_level": qa_pair.answer.confidence_level,
|
| 136 |
+
"context_coverage": qa_pair.answer.context_coverage,
|
| 137 |
+
"total_steps": qa_pair.total_steps
|
| 138 |
+
}
|
backend/agentic_system/agents/question_answering_agent/qa_prompt.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
QA_PROMPT = """
|
| 2 |
+
### **Role and Goal**
|
| 3 |
+
|
| 4 |
+
You are an expert **Knowledge Synthesizer and Educator Agent**. Your primary function is to construct a detailed, coherent, and educational step-by-step explanation for the user's question. You must base your answer **EXCLUSIVELY** on the provided, structured context, which includes Entities, Relationships, and Document Chunks. Your goal is to act as a teacher, building the user's understanding from foundational concepts to complex conclusions, synthesizing all available information into a clear narrative.
|
| 5 |
+
|
| 6 |
+
### **Critical Rules**
|
| 7 |
+
|
| 8 |
+
1. **CONTEXT-ONLY RULE**: You MUST ONLY use information from the provided `{context}`. Do not add any external knowledge, assumptions, or information. Your world is defined by the text you are given.
|
| 9 |
+
2. **STEP-BY-STEP NARRATIVE**: Your answer is not a list of facts; it is a story that educates. Each step must logically build upon the previous one, guiding the user through the topic.
|
| 10 |
+
3. **SOURCE CITATION**: For each piece of information, you must reference its source (e.g., "From Entity: 'LoRA'", "From Relationship: 'LoRA -> QLORA'", "From Document Chunk: 1"). This is non-negotiable.
|
| 11 |
+
4. **BE DETAILED AND EDUCATIONAL**: Your goal is to teach the user, not just answer the question. Each step should be thorough, well-explained, and add significant value. **Do not provide short, superficial answers.** Assume the user is intelligent but new to the topic.
|
| 12 |
+
5. **ACKNOWLEDGE LIMITATIONS**: If the context is insufficient, explicitly state what information is missing. Do not invent answers.
|
| 13 |
+
6. **SYNTHESIZE, DON'T REGURGITATE**: Do not just copy-paste chunks. Weave together information from the Entities, Relationships, and Document Chunks to form a coherent explanation. For instance, use an Entity description for a definition, a Relationship to show how it connects to another concept, and a Document Chunk for the in-depth explanation.
|
| 14 |
+
|
| 15 |
+
### **Internal Thought Process (Chain of Thought)**
|
| 16 |
+
|
| 17 |
+
Before generating the final JSON output, you MUST follow this internal process:
|
| 18 |
+
|
| 19 |
+
**Step A: Deconstruct the User's Query**
|
| 20 |
+
- First, I will identify the core components of the user's question. For example, "History of LoRA and its components?" breaks down into two main parts: 1) The origin, motivation, and timeline (History), and 2) The technical breakdown of how it works (Components).
|
| 21 |
+
|
| 22 |
+
**Step B: Context Triage and Information Mapping**
|
| 23 |
+
- Next, I will systematically scan all three parts of the provided context:
|
| 24 |
+
1. **Entities (KG):** I will treat this as my **Glossary**. I'll identify all key terms and their definitions (e.g., what is LoRA? What is QLORA?).
|
| 25 |
+
2. **Relationships (KG):** I will treat this as my **Connection Map**. I'll understand how the entities relate to each other (e.g., LoRA is a component of LoRA+PL; LoRA is an alternative to Adapter Layers). This helps me build the narrative structure.
|
| 26 |
+
3. **Document Chunks (DC):** I will treat this as my **Primary Source Narrative**. This contains the detailed explanations, the "why" behind the concepts, and the authors' own words (e.g., the abstract from the paper, the hypothesis about "intrinsic rank").
|
| 27 |
+
|
| 28 |
+
**Step C: Outline the Educational Narrative**
|
| 29 |
+
- Based on my analysis, I will outline the story I'm going to tell in the `Step-by-Step Explanation`. For a query about history and components, my outline will look like this:
|
| 30 |
+
1. **The Problem:** What challenge led to the creation of this technology? (e.g., fine-tuning large models like GPT-3 is expensive).
|
| 31 |
+
2. **The Core Idea/Hypothesis:** What was the key insight? (e.g., weight updates have a low "intrinsic rank").
|
| 32 |
+
3. **The Solution & Key Figures:** How was the idea implemented and who created it? (e.g., a paper by Edward Hu et al. from Microsoft).
|
| 33 |
+
4. **The Technical Components:** What are the building blocks? (e.g., freezing pre-trained weights, injecting trainable rank decomposition matrices).
|
| 34 |
+
5. **Context and Comparisons:** How does it relate to other technologies? (e.g., QLORA, Adapter Layers).
|
| 35 |
+
|
| 36 |
+
**Step D: Draft the Full Response**
|
| 37 |
+
- I will now write out the full explanation for each step in my outline, carefully weaving together the information I mapped in Step B. I will ensure each explanation is detailed and cites its sources clearly. I will force myself to write multiple sentences per explanation, elaborating on the core point of each step, I will ensure to write Extensive steps per major conecpt and build up .
|
| 38 |
+
|
| 39 |
+
**Step E: Final Review and Formatting**
|
| 40 |
+
- Finally, I will review my drafted response against the Critical Rules and the required JSON schema. I will check for accuracy, clarity, and ensure I haven't cut any corners before generating the final output.
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
### **Your Task**
|
| 45 |
+
|
| 46 |
+
Now, apply this entire thought process to the provided context and user question. Generate a `GuidedAnswer` JSON object that is comprehensive, educational, and strictly follows the schema. Remember to build a rich narrative, not just a list of facts.
|
| 47 |
+
|
| 48 |
+
### **Your Context**
|
| 49 |
+
{context}
|
| 50 |
+
### **User Question**
|
| 51 |
+
{question}
|
| 52 |
+
"""
|
backend/agentic_system/agents/question_answering_agent/qa_schema.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Question Answering Schema for Guided Response Agent
|
| 3 |
+
|
| 4 |
+
Defines the data structures for providing step-by-step explanations based on context.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from pydantic import Field, BaseModel
|
| 8 |
+
from typing import List, Optional
|
| 9 |
+
|
| 10 |
+
class AnswerStep(BaseModel):
|
| 11 |
+
"""
|
| 12 |
+
A single step in the guided explanation.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
step_number: int = Field(
|
| 16 |
+
...,
|
| 17 |
+
description="The sequential number of this step",
|
| 18 |
+
example=1,
|
| 19 |
+
ge=1
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
title: str = Field(
|
| 23 |
+
...,
|
| 24 |
+
description="Brief title describing what this step covers",
|
| 25 |
+
example="Understanding LoRA Fundamentals"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
explanation: str = Field(
|
| 29 |
+
...,
|
| 30 |
+
description="Detailed explanation for this step based on the provided context",
|
| 31 |
+
example="LoRA (Low-Rank Adaptation) is a parameter-efficient fine-tuning method..."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
context_references: List[str] = Field(
|
| 35 |
+
default_factory=list,
|
| 36 |
+
description="References to specific parts of the context used in this step",
|
| 37 |
+
example=["From document chunk 1: LoRA definition", "From entity description: Parameter efficiency"]
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
class GuidedAnswer(BaseModel):
|
| 41 |
+
"""
|
| 42 |
+
A complete guided answer with step-by-step explanation.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
summary: str = Field(
|
| 46 |
+
...,
|
| 47 |
+
description="Brief summary of the answer in one or two sentences",
|
| 48 |
+
example="LoRA is a parameter-efficient fine-tuning method that reduces trainable parameters while maintaining performance."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
steps: List[AnswerStep] = Field(
|
| 52 |
+
...,
|
| 53 |
+
description="Step-by-step breakdown of the explanation",
|
| 54 |
+
min_items=1
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
conclusion: str = Field(
|
| 58 |
+
...,
|
| 59 |
+
description="Concluding remarks that tie the steps together",
|
| 60 |
+
example="In conclusion, LoRA provides an efficient way to adapt large models without full fine-tuning."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
confidence_level: str = Field(
|
| 64 |
+
...,
|
| 65 |
+
description="Confidence level based on context quality",
|
| 66 |
+
example="High - based on comprehensive technical documentation"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
context_coverage: str = Field(
|
| 70 |
+
...,
|
| 71 |
+
description="Assessment of how well the context covers the question",
|
| 72 |
+
example="Excellent - context contains detailed technical specifications and examples"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
class QuestionAnswerPair(BaseModel):
|
| 76 |
+
"""
|
| 77 |
+
Complete question-answer package with metadata.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
question: str = Field(
|
| 81 |
+
...,
|
| 82 |
+
description="The original question asked by the user",
|
| 83 |
+
example="How does LoRA work?"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
answer: GuidedAnswer = Field(
|
| 87 |
+
...,
|
| 88 |
+
description="The guided answer with step-by-step explanation"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
context_used: bool = Field(
|
| 92 |
+
...,
|
| 93 |
+
description="Whether the answer was derived from provided context",
|
| 94 |
+
example=True
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
total_steps: int = Field(
|
| 98 |
+
...,
|
| 99 |
+
description="Total number of explanation steps",
|
| 100 |
+
example=3,
|
| 101 |
+
ge=1
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
class Config:
|
| 105 |
+
"""
|
| 106 |
+
Configuration with example showing complete QA structure.
|
| 107 |
+
"""
|
| 108 |
+
json_schema_extra = {
|
| 109 |
+
"examples": [
|
| 110 |
+
{
|
| 111 |
+
"question": "How does LoRA work?",
|
| 112 |
+
"answer": {
|
| 113 |
+
"summary": "LoRA works by freezing pre-trained weights and adding trainable low-rank matrices to adapt the model efficiently.",
|
| 114 |
+
"steps": [
|
| 115 |
+
{
|
| 116 |
+
"step_number": 1,
|
| 117 |
+
"title": "Understanding the Core Concept",
|
| 118 |
+
"explanation": "LoRA (Low-Rank Adaptation) is based on the hypothesis that weight updates during adaptation have a low intrinsic rank.",
|
| 119 |
+
"context_references": ["From technical paper: low intrinsic dimension hypothesis"]
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"step_number": 2,
|
| 123 |
+
"title": "Implementation Mechanism",
|
| 124 |
+
"explanation": "Instead of updating all model parameters, LoRA freezes the original weights and adds small trainable matrices A and B.",
|
| 125 |
+
"context_references": ["From architecture description: rank decomposition matrices"]
|
| 126 |
+
}
|
| 127 |
+
],
|
| 128 |
+
"conclusion": "This approach dramatically reduces the number of trainable parameters while maintaining model performance.",
|
| 129 |
+
"confidence_level": "High - based on technical documentation",
|
| 130 |
+
"context_coverage": "Comprehensive - detailed technical specifications provided"
|
| 131 |
+
},
|
| 132 |
+
"context_used": True,
|
| 133 |
+
"total_steps": 2
|
| 134 |
+
}
|
| 135 |
+
]
|
| 136 |
+
}
|
backend/agentic_system/agents/question_generation_agent/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Question Generation Agent for research paper exploration
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from .question_generation_agent import QuestionGenerationAgent
|
| 6 |
+
from .question_generation_schema import (
|
| 7 |
+
ResearchQuestion,
|
| 8 |
+
QuestionCategory,
|
| 9 |
+
QuestionSet,
|
| 10 |
+
QuestionGenerationRequest
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"QuestionGenerationAgent",
|
| 15 |
+
"ResearchQuestion",
|
| 16 |
+
"QuestionCategory",
|
| 17 |
+
"QuestionSet",
|
| 18 |
+
"QuestionGenerationRequest"
|
| 19 |
+
]
|
backend/agentic_system/agents/question_generation_agent/question_generation_agent.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Question Generation Agent for systematic research paper exploration.
|
| 3 |
+
|
| 4 |
+
Generates comprehensive research questions following academic methodology frameworks
|
| 5 |
+
to enable deep understanding through systematic inquiry.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
from typing import List, Optional
|
| 10 |
+
from pydantic_ai import Agent, RunContext
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
|
| 13 |
+
from .question_generation_schema import (
|
| 14 |
+
QuestionSet,
|
| 15 |
+
QuestionGenerationRequest,
|
| 16 |
+
QuestionCategory,
|
| 17 |
+
ResearchQuestion
|
| 18 |
+
)
|
| 19 |
+
from .question_generation_prompt import QUESTION_GENERATION_PROMPT
|
| 20 |
+
|
| 21 |
+
from dotenv import load_dotenv
|
| 22 |
+
load_dotenv()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class QuestionGenerationDeps(BaseModel):
|
| 26 |
+
"""Dependencies for the question generation agent."""
|
| 27 |
+
|
| 28 |
+
topic: str
|
| 29 |
+
max_questions: int = 5
|
| 30 |
+
focus_areas: Optional[List[QuestionCategory]] = None
|
| 31 |
+
depth_level: str = "comprehensive"
|
| 32 |
+
paper_type: Optional[str] = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
question_generation_agent = Agent(
|
| 36 |
+
model='gemini-2.5-flash-lite',
|
| 37 |
+
output_type=QuestionSet,
|
| 38 |
+
deps_type=QuestionGenerationDeps,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@question_generation_agent.system_prompt
|
| 43 |
+
def dynamic_system_prompt(ctx: RunContext[QuestionGenerationDeps]) -> str:
|
| 44 |
+
"""
|
| 45 |
+
Create custom instructions for the question generation agent.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
ctx: The context containing the research topic and parameters
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
str: The complete instructions for the AI agent
|
| 52 |
+
"""
|
| 53 |
+
return QUESTION_GENERATION_PROMPT.format(
|
| 54 |
+
topic=ctx.deps.topic,
|
| 55 |
+
max_questions=ctx.deps.max_questions
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class QuestionGenerationAgent:
|
| 60 |
+
"""
|
| 61 |
+
The main question generation agent for systematic research exploration.
|
| 62 |
+
|
| 63 |
+
Generates comprehensive sets of research questions to enable deep understanding
|
| 64 |
+
of academic papers and research topics through systematic inquiry.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self):
|
| 68 |
+
"""Initialize the question generation agent."""
|
| 69 |
+
# Set up API key
|
| 70 |
+
os.environ.setdefault("OPENAI_API_KEY", os.getenv("OPENAI_API_KEY", ""))
|
| 71 |
+
|
| 72 |
+
async def generate_research_questions(self, request: QuestionGenerationRequest) -> QuestionSet:
|
| 73 |
+
"""
|
| 74 |
+
Generate a comprehensive set of research questions for a topic.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
request: The question generation request with topic and parameters
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
QuestionSet: Organized set of research questions with priorities
|
| 81 |
+
"""
|
| 82 |
+
try:
|
| 83 |
+
# Create dependencies
|
| 84 |
+
deps = QuestionGenerationDeps(
|
| 85 |
+
topic=request.topic,
|
| 86 |
+
max_questions=request.max_questions,
|
| 87 |
+
focus_areas=request.focus_areas,
|
| 88 |
+
depth_level=request.depth_level,
|
| 89 |
+
paper_type=request.paper_type
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Run the agent to generate questions
|
| 93 |
+
result = await question_generation_agent.run(
|
| 94 |
+
"Generate systematic research questions for comprehensive understanding",
|
| 95 |
+
deps=deps
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
return result.output
|
| 99 |
+
|
| 100 |
+
except Exception as e:
|
| 101 |
+
# Return minimal question set on error
|
| 102 |
+
return QuestionSet(
|
| 103 |
+
topic=request.topic,
|
| 104 |
+
questions=[
|
| 105 |
+
ResearchQuestion(
|
| 106 |
+
question=f"What is the main contribution of research on {request.topic}?",
|
| 107 |
+
category=QuestionCategory.OVERVIEW,
|
| 108 |
+
priority=8,
|
| 109 |
+
rationale="Essential for basic understanding"
|
| 110 |
+
)
|
| 111 |
+
],
|
| 112 |
+
total_questions=1,
|
| 113 |
+
categories_covered=[QuestionCategory.OVERVIEW]
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
async def generate_questions_for_topic(
|
| 117 |
+
self,
|
| 118 |
+
topic: str,
|
| 119 |
+
max_questions: int = 15,
|
| 120 |
+
focus_areas: Optional[List[QuestionCategory]] = None
|
| 121 |
+
) -> QuestionSet:
|
| 122 |
+
"""
|
| 123 |
+
Simplified interface for generating questions about a research topic.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
topic: The research topic to explore
|
| 127 |
+
max_questions: Maximum number of questions to generate
|
| 128 |
+
focus_areas: Specific categories to focus on (optional)
|
| 129 |
+
|
| 130 |
+
Returns:
|
| 131 |
+
QuestionSet: Generated research questions
|
| 132 |
+
"""
|
| 133 |
+
request = QuestionGenerationRequest(
|
| 134 |
+
topic=topic,
|
| 135 |
+
max_questions=max_questions,
|
| 136 |
+
focus_areas=focus_areas
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
return await self.generate_research_questions(request)
|
| 140 |
+
|
| 141 |
+
async def generate_questions_by_category(
|
| 142 |
+
self,
|
| 143 |
+
topic: str,
|
| 144 |
+
categories: List[QuestionCategory]
|
| 145 |
+
) -> QuestionSet:
|
| 146 |
+
"""
|
| 147 |
+
Generate questions focused on specific research categories.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
topic: The research topic to explore
|
| 151 |
+
categories: Specific question categories to focus on
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
QuestionSet: Questions focused on specified categories
|
| 155 |
+
"""
|
| 156 |
+
# Calculate questions per category
|
| 157 |
+
questions_per_category = max(1, 15 // len(categories))
|
| 158 |
+
total_questions = questions_per_category * len(categories)
|
| 159 |
+
|
| 160 |
+
request = QuestionGenerationRequest(
|
| 161 |
+
topic=topic,
|
| 162 |
+
max_questions=total_questions,
|
| 163 |
+
focus_areas=categories,
|
| 164 |
+
depth_level="detailed"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
return await self.generate_research_questions(request)
|
| 168 |
+
|
| 169 |
+
# HELPER FUNCTIONS
|
| 170 |
+
|
| 171 |
+
def _validate_question_set(self, question_set: QuestionSet) -> bool:
|
| 172 |
+
"""
|
| 173 |
+
Validate that a question set meets quality standards.
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
question_set: The question set to validate
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
bool: True if valid, False otherwise
|
| 180 |
+
"""
|
| 181 |
+
if not question_set.questions:
|
| 182 |
+
return False
|
| 183 |
+
|
| 184 |
+
# Check for minimum high-priority questions
|
| 185 |
+
high_priority_count = len([q for q in question_set.questions if q.priority >= 7])
|
| 186 |
+
if high_priority_count < 3:
|
| 187 |
+
return False
|
| 188 |
+
|
| 189 |
+
# Check for category diversity
|
| 190 |
+
if len(question_set.categories_covered) < 3:
|
| 191 |
+
return False
|
| 192 |
+
|
| 193 |
+
return True
|
backend/agentic_system/agents/question_generation_agent/question_generation_prompt.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
System prompt for generating systematic research questions.
|
| 3 |
+
|
| 4 |
+
Contains the complete research methodology framework for generating
|
| 5 |
+
comprehensive questions about academic papers and research topics.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
QUESTION_GENERATION_PROMPT = """
|
| 9 |
+
You are a Research Question Generation Specialist, expert in academic methodology and systematic research exploration.
|
| 10 |
+
|
| 11 |
+
Your mission is to generate comprehensive, well-structured research questions that help users deeply understand research papers and topics through systematic inquiry.
|
| 12 |
+
|
| 13 |
+
## Core Research Question Categories
|
| 14 |
+
|
| 15 |
+
### 1. OVERVIEW (High-Level Understanding)
|
| 16 |
+
Purpose: Establish foundational understanding
|
| 17 |
+
Examples:
|
| 18 |
+
- "What is the main contribution of this research?"
|
| 19 |
+
- "What problem does this work address?"
|
| 20 |
+
- "What is the key innovation presented?"
|
| 21 |
+
|
| 22 |
+
### 2. METHODOLOGY (How It Works)
|
| 23 |
+
Purpose: Understand the technical approach
|
| 24 |
+
Examples:
|
| 25 |
+
- "What methodology is used to solve the problem?"
|
| 26 |
+
- "What are the key algorithmic components?"
|
| 27 |
+
- "How does the proposed approach work step-by-step?"
|
| 28 |
+
|
| 29 |
+
### 3. INNOVATION (What's Novel)
|
| 30 |
+
Purpose: Identify unique contributions
|
| 31 |
+
Examples:
|
| 32 |
+
- "What makes this approach different from existing work?"
|
| 33 |
+
- "What is the key novelty or breakthrough?"
|
| 34 |
+
- "How does this advance the state-of-the-art?"
|
| 35 |
+
|
| 36 |
+
### 4. EVALUATION (Testing & Validation)
|
| 37 |
+
Purpose: Understand how claims are supported
|
| 38 |
+
Examples:
|
| 39 |
+
- "How was the approach evaluated?"
|
| 40 |
+
- "What datasets or benchmarks were used?"
|
| 41 |
+
- "What metrics demonstrate effectiveness?"
|
| 42 |
+
|
| 43 |
+
### 5. RESULTS (Key Findings)
|
| 44 |
+
Purpose: Extract main outcomes
|
| 45 |
+
Examples:
|
| 46 |
+
- "What are the key experimental results?"
|
| 47 |
+
- "What performance improvements were achieved?"
|
| 48 |
+
- "What insights emerged from the analysis?"
|
| 49 |
+
|
| 50 |
+
### 6. LIMITATIONS (Constraints & Boundaries)
|
| 51 |
+
Purpose: Understand scope and constraints
|
| 52 |
+
Examples:
|
| 53 |
+
- "What are the acknowledged limitations?"
|
| 54 |
+
- "Where might this approach fail or struggle?"
|
| 55 |
+
- "What assumptions does the work rely on?"
|
| 56 |
+
|
| 57 |
+
### 7. APPLICATIONS (Practical Use)
|
| 58 |
+
Purpose: Understand real-world relevance
|
| 59 |
+
Examples:
|
| 60 |
+
- "What are the practical applications?"
|
| 61 |
+
- "In what domains could this be applied?"
|
| 62 |
+
- "What impact might this have on the field?"
|
| 63 |
+
|
| 64 |
+
### 8. FUTURE_WORK (Research Directions)
|
| 65 |
+
Purpose: Identify next steps and opportunities
|
| 66 |
+
Examples:
|
| 67 |
+
- "What future research directions are suggested?"
|
| 68 |
+
- "What extensions or improvements are proposed?"
|
| 69 |
+
- "What open questions remain?"
|
| 70 |
+
|
| 71 |
+
### 9. COMPARISON (Relationship to Other Work)
|
| 72 |
+
Purpose: Contextualize within broader research
|
| 73 |
+
Examples:
|
| 74 |
+
- "How does this compare to previous approaches?"
|
| 75 |
+
- "What advantages does this have over alternatives?"
|
| 76 |
+
- "How does this build on or differ from related work?"
|
| 77 |
+
|
| 78 |
+
### 10. IMPLEMENTATION (How to Build)
|
| 79 |
+
Purpose: Understand practical implementation
|
| 80 |
+
Examples:
|
| 81 |
+
- "How could this be implemented in practice?"
|
| 82 |
+
- "What resources or tools are needed?"
|
| 83 |
+
- "What are the computational requirements?"
|
| 84 |
+
|
| 85 |
+
## Question Quality Guidelines
|
| 86 |
+
|
| 87 |
+
### Characteristics of Excellent Research Questions:
|
| 88 |
+
1. **Specific and Focused**: Target particular aspects rather than being too broad
|
| 89 |
+
2. **Actionable**: Can be answered through analysis of the research
|
| 90 |
+
3. **Insightful**: Reveal important understanding about the work
|
| 91 |
+
4. **Progressive**: Build from basic to advanced understanding
|
| 92 |
+
5. **Balanced**: Cover both technical and conceptual aspects
|
| 93 |
+
|
| 94 |
+
### Prioritization Criteria (1-10 scale):
|
| 95 |
+
- **Priority 9-10**: Essential for core understanding
|
| 96 |
+
- **Priority 7-8**: Important for comprehensive grasp
|
| 97 |
+
- **Priority 5-6**: Useful for deeper insight
|
| 98 |
+
- **Priority 3-4**: Interesting but not critical
|
| 99 |
+
- **Priority 1-2**: Nice-to-know details
|
| 100 |
+
|
| 101 |
+
## Instructions for Topic: "{topic}"
|
| 102 |
+
|
| 103 |
+
Generate {max_questions} research questions following these guidelines:
|
| 104 |
+
|
| 105 |
+
1. **Analyze the Topic**: Understand what type of research this is (theoretical, empirical, survey, etc.)
|
| 106 |
+
|
| 107 |
+
2. **Select Categories**: Choose the most relevant question categories for this topic
|
| 108 |
+
|
| 109 |
+
3. **Generate Questions**: Create specific, well-formulated questions for each category
|
| 110 |
+
|
| 111 |
+
4. **Assign Priorities**: Rate each question 1-10 based on importance for understanding
|
| 112 |
+
|
| 113 |
+
5. **Provide Rationale**: Briefly explain why each high-priority question is important
|
| 114 |
+
|
| 115 |
+
## Output Requirements:
|
| 116 |
+
|
| 117 |
+
Return a well-structured QuestionSet with:
|
| 118 |
+
- Clear, specific questions for each relevant category
|
| 119 |
+
- Appropriate priority assignments (focusing on 7-10 for essential questions)
|
| 120 |
+
- Brief rationales for high-priority questions
|
| 121 |
+
- Balanced coverage across different aspects of the research
|
| 122 |
+
|
| 123 |
+
Focus on questions that would help someone gain deep, systematic understanding of the research topic through your existing QA workflow system.
|
| 124 |
+
"""
|
backend/agentic_system/agents/question_generation_agent/question_generation_schema.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Schema definitions for research question generation.
|
| 3 |
+
|
| 4 |
+
Defines the data structures for systematic research paper exploration,
|
| 5 |
+
including question categories, individual questions, and question sets.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import List, Optional
|
| 9 |
+
from enum import Enum
|
| 10 |
+
from pydantic import BaseModel, Field
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class QuestionCategory(str, Enum):
|
| 14 |
+
"""Research question categories following academic methodology frameworks."""
|
| 15 |
+
|
| 16 |
+
OVERVIEW = "overview" # What is this about? High-level understanding
|
| 17 |
+
METHODOLOGY = "methodology" # How does the approach work?
|
| 18 |
+
INNOVATION = "innovation" # What's novel about this research?
|
| 19 |
+
EVALUATION = "evaluation" # How was it tested and validated?
|
| 20 |
+
RESULTS = "results" # What were the key findings?
|
| 21 |
+
LIMITATIONS = "limitations" # What are the known constraints?
|
| 22 |
+
APPLICATIONS = "applications" # Where is this used in practice?
|
| 23 |
+
FUTURE_WORK = "future_work" # What directions are suggested?
|
| 24 |
+
COMPARISON = "comparison" # How does this compare to other work?
|
| 25 |
+
IMPLEMENTATION = "implementation" # How can this be implemented?
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ResearchQuestion(BaseModel):
|
| 29 |
+
"""Individual research question with metadata."""
|
| 30 |
+
|
| 31 |
+
question: str = Field(..., description="The actual question text")
|
| 32 |
+
category: QuestionCategory = Field(..., description="Question category")
|
| 33 |
+
priority: int = Field(default=5, ge=1, le=10, description="Priority (1=low, 10=high)")
|
| 34 |
+
rationale: Optional[str] = Field(None, description="Why this question is important")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class QuestionSet(BaseModel):
|
| 38 |
+
"""Complete set of generated research questions organized by category."""
|
| 39 |
+
|
| 40 |
+
topic: str = Field(..., description="The research topic being explored")
|
| 41 |
+
questions: List[ResearchQuestion] = Field(..., description="Generated questions")
|
| 42 |
+
total_questions: int = Field(..., description="Total number of questions generated")
|
| 43 |
+
categories_covered: List[QuestionCategory] = Field(..., description="Question categories included")
|
| 44 |
+
|
| 45 |
+
def get_questions_by_category(self, category: QuestionCategory) -> List[ResearchQuestion]:
|
| 46 |
+
"""Get all questions for a specific category."""
|
| 47 |
+
return [q for q in self.questions if q.category == category]
|
| 48 |
+
|
| 49 |
+
def get_high_priority_questions(self, min_priority: int = 7) -> List[ResearchQuestion]:
|
| 50 |
+
"""Get questions above a priority threshold."""
|
| 51 |
+
return [q for q in self.questions if q.priority >= min_priority]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class QuestionGenerationRequest(BaseModel):
|
| 55 |
+
"""Request for generating research questions about a topic."""
|
| 56 |
+
|
| 57 |
+
topic: str = Field(..., description="Research topic or paper to explore")
|
| 58 |
+
focus_areas: Optional[List[QuestionCategory]] = Field(
|
| 59 |
+
None,
|
| 60 |
+
description="Specific categories to focus on (if None, covers all)"
|
| 61 |
+
)
|
| 62 |
+
max_questions: int = Field(
|
| 63 |
+
default=2,
|
| 64 |
+
ge=2,
|
| 65 |
+
description="Maximum number of questions to generate"
|
| 66 |
+
)
|
| 67 |
+
depth_level: str = Field(
|
| 68 |
+
default="comprehensive",
|
| 69 |
+
description="Level of detail: 'overview', 'detailed', 'comprehensive'"
|
| 70 |
+
)
|
| 71 |
+
paper_type: Optional[str] = Field(
|
| 72 |
+
None,
|
| 73 |
+
description="Type of paper: 'theoretical', 'empirical', 'survey', 'experimental'"
|
| 74 |
+
)
|
backend/agentic_system/agents/retrieval_strategy_agent/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retrieval Strategy Agent Package
|
| 3 |
+
|
| 4 |
+
Provides intelligent query analysis to determine optimal retrieval parameters for knowledge retrieval systems.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .retrieval_strategy_agent import RetrievalStrategyAgent, RetrievalStrategyDeps, retrieval_strategy_agent
|
| 8 |
+
from .retrieval_strategy_schema import RetrievalStrategy, QueryAnalysis
|
| 9 |
+
from .retrieval_strategy_prompt import RETRIEVAL_STRATEGY_PROMPT
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"RetrievalStrategyAgent",
|
| 13 |
+
"RetrievalStrategyDeps",
|
| 14 |
+
"retrieval_strategy_agent",
|
| 15 |
+
"RetrievalStrategy",
|
| 16 |
+
"QueryAnalysis",
|
| 17 |
+
"RETRIEVAL_STRATEGY_PROMPT"
|
| 18 |
+
]
|
backend/agentic_system/agents/retrieval_strategy_agent/retrieval_strategy_agent.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retrieval Strategy Agent for analyzing queries and determining optimal retrieval parameters
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from pydantic_ai import Agent, RunContext
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from typing import Optional, Dict, Any
|
| 9 |
+
|
| 10 |
+
from .retrieval_strategy_schema import RetrievalStrategy, QueryAnalysis
|
| 11 |
+
from .retrieval_strategy_prompt import RETRIEVAL_STRATEGY_PROMPT
|
| 12 |
+
|
| 13 |
+
import asyncio
|
| 14 |
+
from dotenv import load_dotenv
|
| 15 |
+
load_dotenv()
|
| 16 |
+
|
| 17 |
+
class RetrievalStrategyDeps(BaseModel):
|
| 18 |
+
"""
|
| 19 |
+
Dependencies for the retrieval strategy agent.
|
| 20 |
+
"""
|
| 21 |
+
query: str # The user query to analyze
|
| 22 |
+
|
| 23 |
+
retrieval_strategy_agent = Agent(
|
| 24 |
+
model='gemini-2.5-flash-lite',
|
| 25 |
+
output_type=RetrievalStrategy,
|
| 26 |
+
deps_type=RetrievalStrategyDeps,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
@retrieval_strategy_agent.system_prompt
|
| 30 |
+
def dynamic_system_prompt(ctx: RunContext[RetrievalStrategyDeps]) -> str:
|
| 31 |
+
"""
|
| 32 |
+
Create custom instructions for the retrieval strategy agent.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
ctx: The context containing the query to analyze
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
str: The complete instructions for the AI agent
|
| 39 |
+
"""
|
| 40 |
+
return RETRIEVAL_STRATEGY_PROMPT.format(query=ctx.deps.query)
|
| 41 |
+
|
| 42 |
+
class RetrievalStrategyAgent:
|
| 43 |
+
"""
|
| 44 |
+
The main retrieval strategy agent class for analyzing queries and determining retrieval parameters.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(self):
|
| 48 |
+
"""
|
| 49 |
+
Initialize the retrieval strategy agent.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
async def analyze_query(self, query: str) -> QueryAnalysis:
|
| 53 |
+
"""
|
| 54 |
+
Analyze a user query and determine optimal retrieval parameters.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
query: The user query to analyze
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
QueryAnalysis: Complete analysis with query and retrieval strategy
|
| 61 |
+
"""
|
| 62 |
+
try:
|
| 63 |
+
# Create dependencies
|
| 64 |
+
deps = RetrievalStrategyDeps(query=query)
|
| 65 |
+
|
| 66 |
+
# Run the agent analysis
|
| 67 |
+
result = await retrieval_strategy_agent.run(
|
| 68 |
+
"Analyze this query and determine the optimal retrieval parameters",
|
| 69 |
+
deps=deps
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Package the results
|
| 73 |
+
return QueryAnalysis(
|
| 74 |
+
query=query,
|
| 75 |
+
strategy=result.output
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
# Return default strategy on error
|
| 80 |
+
return QueryAnalysis(
|
| 81 |
+
query=query,
|
| 82 |
+
strategy=RetrievalStrategy(
|
| 83 |
+
analysis=f"Error analyzing query: {e}. Using default balanced strategy.",
|
| 84 |
+
query_category="Balanced / Complex",
|
| 85 |
+
top_k=5,
|
| 86 |
+
chunk_top_k=2
|
| 87 |
+
)
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
async def get_retrieval_parameters(self, query: str) -> Dict[str, Any]:
|
| 91 |
+
"""
|
| 92 |
+
Get just the retrieval parameters for a query (simplified interface).
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
query: The user query to analyze
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
Dict with top_k and chunk_top_k parameters
|
| 99 |
+
"""
|
| 100 |
+
analysis = await self.analyze_query(query)
|
| 101 |
+
return {
|
| 102 |
+
"top_k": analysis.strategy.top_k,
|
| 103 |
+
"chunk_top_k": analysis.strategy.chunk_top_k,
|
| 104 |
+
"query_category": analysis.strategy.query_category,
|
| 105 |
+
"analysis": analysis.strategy.analysis
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
async def analyze_query(query: str) -> QueryAnalysis:
|
| 110 |
+
"""
|
| 111 |
+
Analyze a user query and determine optimal retrieval parameters.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
query: The user query to analyze
|
| 115 |
+
|
| 116 |
+
Returns:
|
| 117 |
+
QueryAnalysis: Complete analysis with query and retrieval strategy
|
| 118 |
+
"""
|
| 119 |
+
agent = RetrievalStrategyAgent()
|
| 120 |
+
response = await agent.analyze_query(query='Hello, what is data science and its correlation to machine learning and deep learning and how can i learn them`? ')
|
| 121 |
+
print(f"Analysis for query '{query}': {response}")
|
| 122 |
+
return await agent.analyze_query(query)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
asyncio.run(analyze_query("What is the history of LoRA and its components?"))
|
backend/agentic_system/agents/retrieval_strategy_agent/retrieval_strategy_prompt.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retrieval Strategy Prompt for Query Analysis Agent
|
| 3 |
+
|
| 4 |
+
Contains the system prompt for analyzing queries and determining optimal retrieval parameters.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
RETRIEVAL_STRATEGY_PROMPT = """
|
| 8 |
+
### **Role and Goal**
|
| 9 |
+
|
| 10 |
+
You are an expert **Retrieval Strategist Agent**. Your primary function is to analyze a user's query and determine the optimal parameters (`top_k`, `chunk_top_k`) for a knowledge retrieval system. Your goal is to balance **completeness** (recall) with **conciseness** (precision) to provide the most useful context for answering the user's query.
|
| 11 |
+
|
| 12 |
+
### **Core Logic: The Query Specificity Spectrum**
|
| 13 |
+
|
| 14 |
+
You must categorize each user query based on its **breadth**. A broad query requires more context from more documents, while a specific query can be answered with a few precise chunks. Use the following table as your guide:
|
| 15 |
+
|
| 16 |
+
| Query Category | Description & Keywords | `top_k` | `chunk_top_k` | Reasoning |
|
| 17 |
+
| :--- | :--- | :--- | :--- | :--- |
|
| 18 |
+
| **Highly Specific** | A single, factual question. (e.g., "Who...", "What is the date...", "Define...") | **2** | **1** | **Surgical Strike:** Find the single best document and the single best chunk. High precision is key; extra context is noise. |
|
| 19 |
+
| **Specific** | A question about a single entity, but may require some context. (e.g., "How does X work?", "What are the features of Y?") | **3** | **2** | **Focused Inquiry:** Retrieve a few core documents to get a solid definition and some surrounding detail without getting sidetracked. |
|
| 20 |
+
| **Balanced / Complex**| A multi-faceted question requiring synthesis of information. (e.g., "History of X **and** its components?", "Explain the relationship between X and Y.") | **5** | **2** | **Comprehensive Overview:** This is a strong default. It's broad enough to capture multiple facets of the query from different sources without significant noise. |
|
| 21 |
+
| **Concept Connection** | Questions asking to connect/integrate different concepts or technologies. (e.g., "How can I use X with Y?", "What's the connection between X and Y?", "How do X and Y work together?") | **12** | **5** | **Deep Concept Mining:** These queries require extensive context from multiple sources to find connections, patterns, or integration possibilities that may not be explicitly stated. Need maximum context for brainstorming potential connections. |
|
| 22 |
+
| **Broad / Comparative** | An open-ended, comparative, or list-based question. (e.g., "Compare X, Y, and Z", "What are all the methods for...", "Explain the impact of X on the field of Y.") | **10** | **4** | **Maximum Recall:** The query *demands* a wide range of information. We need to retrieve many documents and more chunks from each to ensure we don't miss any relevant methods, comparisons, or contextual details. |
|
| 23 |
+
|
| 24 |
+
### **Analysis Process**
|
| 25 |
+
|
| 26 |
+
1. **Read the query carefully** and identify key indicators:
|
| 27 |
+
- Is it asking for a single fact or definition?
|
| 28 |
+
- Does it have multiple parts (e.g., "X and Y")?
|
| 29 |
+
- Is it comparative ("compare", "differences", "similarities")?
|
| 30 |
+
- Is it asking for concept connections or integration ("use X with Y", "connect", "work together")?
|
| 31 |
+
- Is it asking for a list or comprehensive overview?
|
| 32 |
+
|
| 33 |
+
2. **Pay special attention to concept connection queries** that seek to:
|
| 34 |
+
- Integrate different technologies or methods
|
| 35 |
+
- Find relationships between separate concepts
|
| 36 |
+
- Explore how concepts might work together
|
| 37 |
+
- Brainstorm connections that may not be explicitly documented
|
| 38 |
+
|
| 39 |
+
3. **Categorize the query** based on the table above.
|
| 40 |
+
|
| 41 |
+
4. **Provide your analysis** explaining why you chose the category and parameters.
|
| 42 |
+
|
| 43 |
+
5. **Return the structured response** with the analysis, category, and retrieval parameters.
|
| 44 |
+
|
| 45 |
+
### **Examples**
|
| 46 |
+
|
| 47 |
+
**Query:** "Who invented LoRA?"
|
| 48 |
+
**Analysis:** "The query is a highly specific factual question asking for a person or group, requiring maximum precision."
|
| 49 |
+
**Category:** "Highly Specific"
|
| 50 |
+
**Parameters:** top_k=2, chunk_top_k=1
|
| 51 |
+
|
| 52 |
+
**Query:** "History of lora and it's components?"
|
| 53 |
+
**Analysis:** "The query is complex, asking for two distinct types of information (history AND components), requiring a balanced retrieval of context from several documents."
|
| 54 |
+
**Category:** "Balanced / Complex"
|
| 55 |
+
**Parameters:** top_k=10, chunk_top_k=7
|
| 56 |
+
|
| 57 |
+
**Query:** "How can I use LoRA and QLoRA with GraphRAG? Is there a connection between them?"
|
| 58 |
+
**Analysis:** "The query seeks to connect different concepts (LoRA/QLoRA and GraphRAG) that may not be explicitly linked in the literature. This requires extensive context mining to find potential integration points, architectural similarities, or brainstorm novel connections."
|
| 59 |
+
**Category:** "Concept Connection"
|
| 60 |
+
**Parameters:** top_k=22, chunk_top_k=10
|
| 61 |
+
|
| 62 |
+
**Query:** "Explain the differences and similarities between all the parameter-efficient fine-tuning methods like LoRA, Adapters, and Prefix Tuning."
|
| 63 |
+
**Analysis:** "The query is broad and comparative, requiring context from many documents to ensure all mentioned methods and their comparisons are found."
|
| 64 |
+
**Category:** "Broad / Comparative"
|
| 65 |
+
**Parameters:** top_k=25, chunk_top_k=15
|
| 66 |
+
|
| 67 |
+
### **Your Task**
|
| 68 |
+
|
| 69 |
+
Analyze the user's query: "{query}"
|
| 70 |
+
|
| 71 |
+
Provide a structured analysis following the schema format with:
|
| 72 |
+
- A clear analysis explaining your reasoning
|
| 73 |
+
- The appropriate query category
|
| 74 |
+
- The optimal top_k and chunk_top_k parameters
|
| 75 |
+
"""
|
backend/agentic_system/agents/retrieval_strategy_agent/retrieval_strategy_schema.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retrieval Strategy Schema for Query Analysis Agent
|
| 3 |
+
|
| 4 |
+
Defines the data structures for analyzing queries and determining optimal retrieval parameters.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from pydantic import Field, BaseModel
|
| 8 |
+
from typing import Literal
|
| 9 |
+
|
| 10 |
+
class RetrievalStrategy(BaseModel):
|
| 11 |
+
"""
|
| 12 |
+
Schema for the retrieval strategy analysis output.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
analysis: str = Field(
|
| 16 |
+
...,
|
| 17 |
+
description="Analysis of the query explaining why certain parameters were chosen",
|
| 18 |
+
example="The query is a highly specific factual question asking for a person or group, requiring maximum precision."
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
query_category: Literal["Highly Specific", "Specific", "Balanced / Complex", "Concept Connection", "Broad / Comparative"] = Field(
|
| 22 |
+
...,
|
| 23 |
+
description="Category of the query based on its breadth and complexity",
|
| 24 |
+
example="Highly Specific"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
top_k: int = Field(
|
| 28 |
+
...,
|
| 29 |
+
description="Number of top documents to retrieve",
|
| 30 |
+
example=2,
|
| 31 |
+
ge=1,
|
| 32 |
+
le=20
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
chunk_top_k: int = Field(
|
| 36 |
+
...,
|
| 37 |
+
description="Number of chunks to retrieve from each document",
|
| 38 |
+
example=1,
|
| 39 |
+
ge=1,
|
| 40 |
+
le=10
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
class Config:
|
| 44 |
+
"""
|
| 45 |
+
Configuration with examples showing different query categories and their parameters.
|
| 46 |
+
"""
|
| 47 |
+
json_schema_extra = {
|
| 48 |
+
"examples": [
|
| 49 |
+
{
|
| 50 |
+
"analysis": "The query is a highly specific factual question asking for a person or group, requiring maximum precision.",
|
| 51 |
+
"query_category": "Highly Specific",
|
| 52 |
+
"top_k": 2,
|
| 53 |
+
"chunk_top_k": 1
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"analysis": "The query is complex, asking for two distinct types of information (history AND components), requiring a balanced retrieval of context from several documents.",
|
| 57 |
+
"query_category": "Balanced / Complex",
|
| 58 |
+
"top_k": 5,
|
| 59 |
+
"chunk_top_k": 2
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"analysis": "The query is broad and comparative, requiring context from many documents to ensure all mentioned methods and their comparisons are found.",
|
| 63 |
+
"query_category": "Broad / Comparative",
|
| 64 |
+
"top_k": 10,
|
| 65 |
+
"chunk_top_k": 4
|
| 66 |
+
}
|
| 67 |
+
]
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
class QueryAnalysis(BaseModel):
|
| 71 |
+
"""
|
| 72 |
+
Complete analysis package containing the original query and its retrieval strategy.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
query: str = Field(
|
| 76 |
+
...,
|
| 77 |
+
description="The original user query to be analyzed",
|
| 78 |
+
example="Who invented LoRA?"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
strategy: RetrievalStrategy = Field(
|
| 82 |
+
...,
|
| 83 |
+
description="The determined retrieval strategy for this query"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
class Config:
|
| 87 |
+
"""
|
| 88 |
+
Complete example of query analysis output.
|
| 89 |
+
"""
|
| 90 |
+
json_schema_extra = {
|
| 91 |
+
"examples": [
|
| 92 |
+
{
|
| 93 |
+
"query": "Who invented LoRA?",
|
| 94 |
+
"strategy": {
|
| 95 |
+
"analysis": "The query is a highly specific factual question asking for a person or group, requiring maximum precision.",
|
| 96 |
+
"query_category": "Highly Specific",
|
| 97 |
+
"top_k": 2,
|
| 98 |
+
"chunk_top_k": 1
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
]
|
| 102 |
+
}
|
backend/agentic_system/flashcard_processor.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Parallel Flashcard Processor
|
| 3 |
+
|
| 4 |
+
This module processes semantic chunks using multiple flashcard agents concurrently
|
| 5 |
+
to generate flashcards efficiently from large documents.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import json
|
| 10 |
+
import asyncio
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
from typing import List, Dict, Any, Optional
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import logging
|
| 15 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 16 |
+
|
| 17 |
+
from agents.flashcard_agent import FlashcardAgent, FlashcardGeneration
|
| 18 |
+
|
| 19 |
+
# Set up logging
|
| 20 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
class ParallelFlashcardProcessor:
|
| 24 |
+
"""
|
| 25 |
+
Processes semantic chunks using multiple concurrent flashcard agents.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(self, max_concurrent_agents: int = 10):
|
| 29 |
+
"""
|
| 30 |
+
Initialize the parallel processor.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
max_concurrent_agents: Maximum number of concurrent flashcard agents to run
|
| 34 |
+
"""
|
| 35 |
+
self.max_concurrent_agents = max_concurrent_agents
|
| 36 |
+
self.semaphore = asyncio.Semaphore(max_concurrent_agents)
|
| 37 |
+
|
| 38 |
+
async def process_page_with_semaphore(self, agent: FlashcardAgent, chunks: List[Dict[str, Any]],
|
| 39 |
+
source_file: str, page_index: int) -> Optional[FlashcardGeneration]:
|
| 40 |
+
"""
|
| 41 |
+
Process a single page with semaphore control for concurrency.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
agent: FlashcardAgent instance
|
| 45 |
+
chunks: List of chunks for this page
|
| 46 |
+
source_file: Source file name
|
| 47 |
+
page_index: Page index number
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
FlashcardGeneration or None if failed
|
| 51 |
+
"""
|
| 52 |
+
async with self.semaphore:
|
| 53 |
+
try:
|
| 54 |
+
logger.info(f"Processing {source_file} page {page_index} with {len(chunks)} chunks")
|
| 55 |
+
result = await agent.generate_flashcards_for_page(chunks, source_file, page_index)
|
| 56 |
+
logger.info(f"Completed {source_file} page {page_index} - Generated {result.total_flashcards} flashcards")
|
| 57 |
+
return result
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"Failed to process {source_file} page {page_index}: {e}")
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
async def process_document(self, file_name: str, file_data: Dict[str, Any]) -> List[FlashcardGeneration]:
|
| 63 |
+
"""
|
| 64 |
+
Process all pages of a document concurrently.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
file_name: Name of the source file
|
| 68 |
+
file_data: File data containing chunks
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
List of FlashcardGeneration objects
|
| 72 |
+
"""
|
| 73 |
+
chunks = file_data.get('chunks', [])
|
| 74 |
+
if not chunks:
|
| 75 |
+
logger.warning(f"No chunks found for {file_name}")
|
| 76 |
+
return []
|
| 77 |
+
|
| 78 |
+
# Group chunks by page
|
| 79 |
+
pages = {}
|
| 80 |
+
for chunk in chunks:
|
| 81 |
+
page_index = chunk['metadata']['page_index']
|
| 82 |
+
if page_index not in pages:
|
| 83 |
+
pages[page_index] = []
|
| 84 |
+
pages[page_index].append(chunk)
|
| 85 |
+
|
| 86 |
+
logger.info(f"Processing {file_name} with {len(pages)} pages")
|
| 87 |
+
|
| 88 |
+
# Create tasks for concurrent processing
|
| 89 |
+
tasks = []
|
| 90 |
+
for page_index, page_chunks in pages.items():
|
| 91 |
+
agent = FlashcardAgent() # Create a new agent instance for each task
|
| 92 |
+
task = self.process_page_with_semaphore(agent, page_chunks, file_name, page_index)
|
| 93 |
+
tasks.append(task)
|
| 94 |
+
|
| 95 |
+
# Process all pages concurrently
|
| 96 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 97 |
+
|
| 98 |
+
# Filter out None results and exceptions
|
| 99 |
+
valid_results = []
|
| 100 |
+
for result in results:
|
| 101 |
+
if isinstance(result, FlashcardGeneration):
|
| 102 |
+
valid_results.append(result)
|
| 103 |
+
elif isinstance(result, Exception):
|
| 104 |
+
logger.error(f"Task failed with exception: {result}")
|
| 105 |
+
|
| 106 |
+
logger.info(f"Completed {file_name} - Generated flashcards for {len(valid_results)} pages")
|
| 107 |
+
return valid_results
|
| 108 |
+
|
| 109 |
+
async def process_all_documents(self, chunks_file_path: str, output_file_path: str) -> Dict[str, Any]:
|
| 110 |
+
"""
|
| 111 |
+
Process all documents from the semantic chunks file.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
chunks_file_path: Path to semantic_chunks.json
|
| 115 |
+
output_file_path: Path to save the generated flashcards
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
Dictionary containing processing results and statistics
|
| 119 |
+
"""
|
| 120 |
+
try:
|
| 121 |
+
# Load semantic chunks
|
| 122 |
+
logger.info(f"Loading semantic chunks from {chunks_file_path}")
|
| 123 |
+
with open(chunks_file_path, 'r', encoding='utf-8') as f:
|
| 124 |
+
data = json.load(f)
|
| 125 |
+
|
| 126 |
+
files_data = data.get('files', {})
|
| 127 |
+
if not files_data:
|
| 128 |
+
logger.error("No files found in semantic chunks data")
|
| 129 |
+
return {"error": "No files found"}
|
| 130 |
+
|
| 131 |
+
logger.info(f"Found {len(files_data)} files to process")
|
| 132 |
+
|
| 133 |
+
# Process all documents
|
| 134 |
+
all_results = []
|
| 135 |
+
total_flashcards = 0
|
| 136 |
+
|
| 137 |
+
for file_name, file_data in files_data.items():
|
| 138 |
+
document_results = await self.process_document(file_name, file_data)
|
| 139 |
+
all_results.extend(document_results)
|
| 140 |
+
total_flashcards += sum(result.total_flashcards for result in document_results)
|
| 141 |
+
|
| 142 |
+
# Prepare output data
|
| 143 |
+
output_data = {
|
| 144 |
+
"processing_info": {
|
| 145 |
+
"processed_at": datetime.now().isoformat(),
|
| 146 |
+
"total_documents": len(files_data),
|
| 147 |
+
"total_pages_processed": len(all_results),
|
| 148 |
+
"total_flashcards_generated": total_flashcards,
|
| 149 |
+
"max_concurrent_agents": self.max_concurrent_agents
|
| 150 |
+
},
|
| 151 |
+
"flashcard_generations": []
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
# Convert results to dictionaries for JSON serialization
|
| 155 |
+
for result in all_results:
|
| 156 |
+
flashcard_dicts = []
|
| 157 |
+
for flashcard in result.flashcards:
|
| 158 |
+
flashcard_dicts.append({
|
| 159 |
+
"id": flashcard.id,
|
| 160 |
+
"question": flashcard.question,
|
| 161 |
+
"answer": flashcard.answer,
|
| 162 |
+
"keyword_explanation": flashcard.keyword_explanation,
|
| 163 |
+
"metadata": flashcard.metadata
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
output_data["flashcard_generations"].append({
|
| 167 |
+
"source_file": result.source_file,
|
| 168 |
+
"page_index": result.page_index,
|
| 169 |
+
"total_flashcards": result.total_flashcards,
|
| 170 |
+
"flashcards": flashcard_dicts
|
| 171 |
+
})
|
| 172 |
+
|
| 173 |
+
# Save results to file
|
| 174 |
+
logger.info(f"Saving results to {output_file_path}")
|
| 175 |
+
os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
|
| 176 |
+
|
| 177 |
+
with open(output_file_path, 'w', encoding='utf-8') as f:
|
| 178 |
+
json.dump(output_data, f, indent=2, ensure_ascii=False)
|
| 179 |
+
|
| 180 |
+
logger.info(f"Processing complete! Generated {total_flashcards} flashcards from {len(all_results)} pages")
|
| 181 |
+
|
| 182 |
+
return {
|
| 183 |
+
"success": True,
|
| 184 |
+
"total_documents": len(files_data),
|
| 185 |
+
"total_pages": len(all_results),
|
| 186 |
+
"total_flashcards": total_flashcards,
|
| 187 |
+
"output_file": output_file_path
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
except Exception as e:
|
| 191 |
+
logger.error(f"Error in processing all documents: {e}")
|
| 192 |
+
return {"error": str(e)}
|
| 193 |
+
|
| 194 |
+
def process_chunks_sync(self, chunks_file_path: str, output_file_path: str) -> Dict[str, Any]:
|
| 195 |
+
"""
|
| 196 |
+
Synchronous wrapper for processing chunks.
|
| 197 |
+
|
| 198 |
+
Args:
|
| 199 |
+
chunks_file_path: Path to semantic_chunks.json
|
| 200 |
+
output_file_path: Path to save the generated flashcards
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
Dictionary containing processing results
|
| 204 |
+
"""
|
| 205 |
+
return asyncio.run(self.process_all_documents(chunks_file_path, output_file_path))
|
| 206 |
+
|
| 207 |
+
async def main():
|
| 208 |
+
"""
|
| 209 |
+
Main function to run the flashcard processor.
|
| 210 |
+
"""
|
| 211 |
+
# Define paths
|
| 212 |
+
current_dir = Path(__file__).parent
|
| 213 |
+
chunks_file = current_dir / "../ingestion_pipeline/chunked_output/semantic_chunks.json"
|
| 214 |
+
output_file = current_dir / "output/generated_flashcards.json"
|
| 215 |
+
|
| 216 |
+
# Create processor and run
|
| 217 |
+
processor = ParallelFlashcardProcessor(max_concurrent_agents=10)
|
| 218 |
+
|
| 219 |
+
logger.info("Starting parallel flashcard processing...")
|
| 220 |
+
result = await processor.process_all_documents(str(chunks_file), str(output_file))
|
| 221 |
+
|
| 222 |
+
if "error" in result:
|
| 223 |
+
logger.error(f"Processing failed: {result['error']}")
|
| 224 |
+
else:
|
| 225 |
+
logger.info(f"Processing completed successfully: {result}")
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
asyncio.run(main())
|
backend/agentic_system/graphs/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Graphs package for the agentic system.
|
| 3 |
+
|
| 4 |
+
Contains LangGraph workflows for orchestrating multi-step processes.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .qa_workflow import QAWorkflow
|
| 8 |
+
from .state_schema import WorkflowState, StreamingState
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"QAWorkflow",
|
| 12 |
+
"WorkflowState",
|
| 13 |
+
"StreamingState"
|
| 14 |
+
]
|
backend/agentic_system/graphs/qa_workflow.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Question Answering Workflow using LangGraph.
|
| 3 |
+
|
| 4 |
+
Orchestrates the complete pipeline from query analysis to final answer generation.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import time
|
| 8 |
+
from typing import Dict, Any, AsyncGenerator
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from langgraph.graph import StateGraph, END
|
| 11 |
+
from langgraph.checkpoint.memory import MemorySaver
|
| 12 |
+
|
| 13 |
+
from .state_schema import WorkflowState, StreamingState
|
| 14 |
+
from ..nodes.retrieval_strategy_node import RetrievalStrategyNode
|
| 15 |
+
from ..nodes.fetching_node import FetchingNode
|
| 16 |
+
from ..nodes.qa_node import QANode
|
| 17 |
+
|
| 18 |
+
class QAWorkflow:
|
| 19 |
+
"""
|
| 20 |
+
Complete Question Answering workflow using LangGraph.
|
| 21 |
+
|
| 22 |
+
Manages the flow from query analysis β context retrieval β answer generation.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self):
|
| 26 |
+
"""Initialize the workflow with all nodes and graph structure."""
|
| 27 |
+
# Initialize nodes
|
| 28 |
+
self.strategy_node = RetrievalStrategyNode()
|
| 29 |
+
self.fetching_node = FetchingNode()
|
| 30 |
+
self.qa_node = QANode()
|
| 31 |
+
|
| 32 |
+
# Build the graph
|
| 33 |
+
self.graph = self._build_graph()
|
| 34 |
+
self.app = self.graph.compile(checkpointer=MemorySaver())
|
| 35 |
+
|
| 36 |
+
def _build_graph(self) -> StateGraph:
|
| 37 |
+
"""
|
| 38 |
+
Build the LangGraph workflow structure.
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
StateGraph: The compiled workflow graph
|
| 42 |
+
"""
|
| 43 |
+
# Create the graph with our state schema
|
| 44 |
+
workflow = StateGraph(WorkflowState)
|
| 45 |
+
|
| 46 |
+
# Add nodes directly
|
| 47 |
+
workflow.add_node("analyze_query", self.strategy_node.process)
|
| 48 |
+
workflow.add_node("fetch_context", self.fetching_node.process)
|
| 49 |
+
workflow.add_node("generate_answer", self.qa_node.process)
|
| 50 |
+
|
| 51 |
+
# Define the flow
|
| 52 |
+
workflow.set_entry_point("analyze_query")
|
| 53 |
+
workflow.add_edge("analyze_query", "fetch_context")
|
| 54 |
+
workflow.add_edge("fetch_context", "generate_answer")
|
| 55 |
+
workflow.add_edge("generate_answer", END)
|
| 56 |
+
|
| 57 |
+
return workflow
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def process_question(self, question: str) -> WorkflowState:
|
| 61 |
+
"""
|
| 62 |
+
Process a single question through the complete workflow.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
question: The user question to process
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
WorkflowState: Final state with complete answer
|
| 69 |
+
"""
|
| 70 |
+
try:
|
| 71 |
+
# Initialize state
|
| 72 |
+
initial_state = WorkflowState(
|
| 73 |
+
question=question,
|
| 74 |
+
workflow_start_time=datetime.now()
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Run the workflow
|
| 78 |
+
config = {"configurable": {"thread_id": f"qa_{int(time.time())}"}}
|
| 79 |
+
result = await self.app.ainvoke(initial_state.dict(), config)
|
| 80 |
+
|
| 81 |
+
return WorkflowState(**result)
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
# Return error state
|
| 85 |
+
return WorkflowState(
|
| 86 |
+
question=question,
|
| 87 |
+
error=f"Workflow error: {str(e)}",
|
| 88 |
+
status="error",
|
| 89 |
+
workflow_start_time=datetime.now(),
|
| 90 |
+
workflow_end_time=datetime.now()
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
backend/agentic_system/graphs/state_schema.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
State Schema for LangGraph Question Answering Workflow.
|
| 3 |
+
|
| 4 |
+
Defines the state structure that maintains information across workflow invocations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
from typing import Optional, Dict, Any, List
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
from ..agents.retrieval_strategy_agent.retrieval_strategy_schema import QueryAnalysis
|
| 12 |
+
from ..agents.question_answering_agent.qa_schema import QuestionAnswerPair, GuidedAnswer
|
| 13 |
+
from ...search_engine.models import RetrievalResult
|
| 14 |
+
|
| 15 |
+
class WorkflowState(BaseModel):
|
| 16 |
+
"""
|
| 17 |
+
State schema that maintains information across all workflow steps.
|
| 18 |
+
|
| 19 |
+
This state is passed between nodes and accumulates information as the workflow progresses.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
# Input
|
| 23 |
+
question: str = Field(
|
| 24 |
+
...,
|
| 25 |
+
description="The original user question",
|
| 26 |
+
example="How does LoRA work?"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Strategy Analysis Step
|
| 30 |
+
query_analysis: Optional[QueryAnalysis] = Field(
|
| 31 |
+
default=None,
|
| 32 |
+
description="Complete query analysis from retrieval strategy agent"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
retrieval_params: Optional[Dict[str, Any]] = Field(
|
| 36 |
+
default=None,
|
| 37 |
+
description="Determined retrieval parameters (top_k, chunk_top_k, mode)",
|
| 38 |
+
example={"top_k": 5, "chunk_top_k": 2, "mode": "hybrid"}
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
query_category: Optional[str] = Field(
|
| 42 |
+
default=None,
|
| 43 |
+
description="Category of the query (Highly Specific, Specific, Balanced/Complex, Broad/Comparative)"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
analysis_reasoning: Optional[str] = Field(
|
| 47 |
+
default=None,
|
| 48 |
+
description="Reasoning behind the parameter selection"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Retrieval Step
|
| 52 |
+
context: Optional[str] = Field(
|
| 53 |
+
default=None,
|
| 54 |
+
description="Retrieved context from the knowledge base"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
context_length: Optional[int] = Field(
|
| 58 |
+
default=None,
|
| 59 |
+
description="Length of the retrieved context in characters"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
retrieval_result: Optional[RetrievalResult] = Field(
|
| 63 |
+
default=None,
|
| 64 |
+
description="Complete retrieval result object"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Question Answering Step
|
| 68 |
+
answer: Optional[GuidedAnswer] = Field(
|
| 69 |
+
default=None,
|
| 70 |
+
description="The guided answer with step-by-step explanation"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
qa_pair: Optional[QuestionAnswerPair] = Field(
|
| 74 |
+
default=None,
|
| 75 |
+
description="Complete question-answer pair with metadata"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
total_steps: Optional[int] = Field(
|
| 79 |
+
default=None,
|
| 80 |
+
description="Total number of explanation steps in the answer"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
context_used: Optional[bool] = Field(
|
| 84 |
+
default=None,
|
| 85 |
+
description="Whether context was successfully used in the answer"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Status Tracking
|
| 89 |
+
status: str = Field(
|
| 90 |
+
default="initialized",
|
| 91 |
+
description="Overall workflow status"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
strategy_status: Optional[str] = Field(
|
| 95 |
+
default=None,
|
| 96 |
+
description="Status of strategy analysis step"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
retrieval_status: Optional[str] = Field(
|
| 100 |
+
default=None,
|
| 101 |
+
description="Status of context retrieval step"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
qa_status: Optional[str] = Field(
|
| 105 |
+
default=None,
|
| 106 |
+
description="Status of question answering step"
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Error Handling
|
| 110 |
+
error: Optional[str] = Field(
|
| 111 |
+
default=None,
|
| 112 |
+
description="Error message if something goes wrong"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Metadata
|
| 116 |
+
workflow_start_time: Optional[datetime] = Field(
|
| 117 |
+
default_factory=datetime.now,
|
| 118 |
+
description="When the workflow started"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
workflow_end_time: Optional[datetime] = Field(
|
| 122 |
+
default=None,
|
| 123 |
+
description="When the workflow completed"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
processing_time: Optional[float] = Field(
|
| 127 |
+
default=None,
|
| 128 |
+
description="Total processing time in seconds"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
class Config:
|
| 132 |
+
"""
|
| 133 |
+
Configuration for the state schema.
|
| 134 |
+
"""
|
| 135 |
+
arbitrary_types_allowed = True # Allow complex types like RetrievalResult
|
| 136 |
+
json_schema_extra = {
|
| 137 |
+
"examples": [
|
| 138 |
+
{
|
| 139 |
+
"question": "How does LoRA work?",
|
| 140 |
+
"query_category": "Specific",
|
| 141 |
+
"retrieval_params": {
|
| 142 |
+
"top_k": 3,
|
| 143 |
+
"chunk_top_k": 2,
|
| 144 |
+
"mode": "hybrid"
|
| 145 |
+
},
|
| 146 |
+
"context_length": 5420,
|
| 147 |
+
"total_steps": 3,
|
| 148 |
+
"context_used": True,
|
| 149 |
+
"status": "completed"
|
| 150 |
+
}
|
| 151 |
+
]
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
class StreamingState(BaseModel):
|
| 155 |
+
"""
|
| 156 |
+
Lightweight state for streaming responses.
|
| 157 |
+
|
| 158 |
+
Contains only the essential information needed for streaming updates.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
question: str = Field(..., description="The user question")
|
| 162 |
+
current_step: str = Field(..., description="Current processing step")
|
| 163 |
+
status: str = Field(..., description="Current status")
|
| 164 |
+
progress: float = Field(default=0.0, description="Progress percentage (0-100)")
|
| 165 |
+
error: Optional[str] = Field(default=None, description="Error message if any")
|
| 166 |
+
|
| 167 |
+
# Partial results for streaming
|
| 168 |
+
partial_answer: Optional[Dict[str, Any]] = Field(
|
| 169 |
+
default=None,
|
| 170 |
+
description="Partial answer data for progressive updates"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
class Config:
|
| 174 |
+
json_schema_extra = {
|
| 175 |
+
"examples": [
|
| 176 |
+
{
|
| 177 |
+
"question": "How does LoRA work?",
|
| 178 |
+
"current_step": "analyzing_query",
|
| 179 |
+
"status": "processing",
|
| 180 |
+
"progress": 33.3
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"question": "How does LoRA work?",
|
| 184 |
+
"current_step": "generating_answer",
|
| 185 |
+
"status": "processing",
|
| 186 |
+
"progress": 85.0,
|
| 187 |
+
"partial_answer": {
|
| 188 |
+
"summary": "LoRA works by...",
|
| 189 |
+
"steps_completed": 2
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
]
|
| 193 |
+
}
|
backend/agentic_system/nodes/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Nodes package for the agentic system.
|
| 3 |
+
|
| 4 |
+
Contains individual processing nodes for LangGraph workflows.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .retrieval_strategy_node import RetrievalStrategyNode
|
| 8 |
+
from .fetching_node import FetchingNode
|
| 9 |
+
from .qa_node import QANode
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"RetrievalStrategyNode",
|
| 13 |
+
"FetchingNode",
|
| 14 |
+
"QANode"
|
| 15 |
+
]
|
backend/agentic_system/nodes/base_node.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Base Node class with utility methods for LangGraph workflow nodes.
|
| 3 |
+
|
| 4 |
+
Provides common functionality for handling state whether it's a dictionary or Pydantic model.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Dict, Any, Union
|
| 8 |
+
from ..graphs.state_schema import WorkflowState
|
| 9 |
+
|
| 10 |
+
class BaseNode:
|
| 11 |
+
"""
|
| 12 |
+
Base class for all workflow nodes with common state handling methods.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def _get_state_value(self, state: Union[Dict[str, Any], WorkflowState], key: str, default: Any = None) -> Any:
|
| 16 |
+
"""
|
| 17 |
+
Get value from state whether it's a dict or Pydantic model.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
state: The workflow state (dict or WorkflowState)
|
| 21 |
+
key: The key to retrieve
|
| 22 |
+
default: Default value if key not found
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
The value from the state
|
| 26 |
+
"""
|
| 27 |
+
if isinstance(state, dict):
|
| 28 |
+
return state.get(key, default)
|
| 29 |
+
else:
|
| 30 |
+
return getattr(state, key, default)
|
| 31 |
+
|
| 32 |
+
def _create_updated_state(self, state: Union[Dict[str, Any], WorkflowState], updates: Dict[str, Any]) -> Dict[str, Any]:
|
| 33 |
+
"""
|
| 34 |
+
Create updated state dict regardless of input type.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
state: The current state (dict or WorkflowState)
|
| 38 |
+
updates: Dictionary of updates to apply
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
Updated state as dictionary
|
| 42 |
+
"""
|
| 43 |
+
if isinstance(state, dict):
|
| 44 |
+
return {**state, **updates}
|
| 45 |
+
else:
|
| 46 |
+
# Convert Pydantic model to dict and update
|
| 47 |
+
state_dict = state.dict() if hasattr(state, 'dict') else state.__dict__
|
| 48 |
+
return {**state_dict, **updates}
|
backend/agentic_system/nodes/fetching_node.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fetching Node for LangGraph workflow.
|
| 3 |
+
|
| 4 |
+
Handles context retrieval using the retrieval engine with determined parameters.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Dict, Any
|
| 8 |
+
from ...search_engine.retriver import get_retrieval_engine
|
| 9 |
+
from .base_node import BaseNode
|
| 10 |
+
|
| 11 |
+
class FetchingNode(BaseNode):
|
| 12 |
+
"""
|
| 13 |
+
Node that uses the Retrieval Engine to fetch context based on determined parameters.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self):
|
| 17 |
+
"""Initialize the fetching node."""
|
| 18 |
+
self.retrieval_engine = None
|
| 19 |
+
|
| 20 |
+
async def _get_retrieval_engine(self):
|
| 21 |
+
"""Get or initialize the retrieval engine."""
|
| 22 |
+
if self.retrieval_engine is None:
|
| 23 |
+
self.retrieval_engine = await get_retrieval_engine()
|
| 24 |
+
return self.retrieval_engine
|
| 25 |
+
|
| 26 |
+
async def process(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
| 27 |
+
"""
|
| 28 |
+
Process the state to retrieve context using the determined parameters.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
state: Current workflow state containing question and retrieval parameters
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Updated state with retrieved context
|
| 35 |
+
"""
|
| 36 |
+
try:
|
| 37 |
+
# Extract required information from state using helper methods
|
| 38 |
+
question = self._get_state_value(state, "question", "")
|
| 39 |
+
retrieval_params = self._get_state_value(state, "retrieval_params", {})
|
| 40 |
+
|
| 41 |
+
if not question:
|
| 42 |
+
return self._create_updated_state(state, {"error": "No question provided for retrieval"})
|
| 43 |
+
|
| 44 |
+
if not retrieval_params:
|
| 45 |
+
return self._create_updated_state(state, {"error": "No retrieval parameters available"})
|
| 46 |
+
|
| 47 |
+
# Get parameters with defaults
|
| 48 |
+
top_k = retrieval_params.get("top_k", 5)
|
| 49 |
+
chunk_top_k = retrieval_params.get("chunk_top_k", 2)
|
| 50 |
+
mode = retrieval_params.get("mode", "mix") # Default to 'mix' for backward compatibility
|
| 51 |
+
|
| 52 |
+
# Get retrieval engine and perform retrieval
|
| 53 |
+
engine = await self._get_retrieval_engine()
|
| 54 |
+
result = await engine.retrieve(
|
| 55 |
+
query=question,
|
| 56 |
+
mode=mode, # Use the mode from parameters instead of hardcoded 'mix'
|
| 57 |
+
top_k=top_k,
|
| 58 |
+
chunk_top_k=chunk_top_k
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Create updates dictionary
|
| 62 |
+
updates = {
|
| 63 |
+
"context": result.text,
|
| 64 |
+
"retrieval_result": result,
|
| 65 |
+
"context_length": len(result.text),
|
| 66 |
+
"retrieval_status": "completed"
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
return self._create_updated_state(state, updates)
|
| 70 |
+
|
| 71 |
+
except Exception as e:
|
| 72 |
+
return self._create_updated_state(state, {
|
| 73 |
+
"error": f"Context retrieval error: {str(e)}",
|
| 74 |
+
"retrieval_status": "error"
|
| 75 |
+
})
|
| 76 |
+
|
| 77 |
+
async def retrieve_direct(self, question: str, top_k: int = 5, chunk_top_k: int = 2, mode: str = "hybrid") -> Dict[str, Any]:
|
| 78 |
+
"""
|
| 79 |
+
Direct retrieval method for standalone usage.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
question: The question to search for
|
| 83 |
+
top_k: Number of top documents to retrieve
|
| 84 |
+
chunk_top_k: Number of chunks per document
|
| 85 |
+
mode: Retrieval mode
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
Dictionary with retrieval results
|
| 89 |
+
"""
|
| 90 |
+
try:
|
| 91 |
+
engine = await self._get_retrieval_engine()
|
| 92 |
+
result = await engine.retrieve(
|
| 93 |
+
query=question,
|
| 94 |
+
mode=mode,
|
| 95 |
+
top_k=top_k,
|
| 96 |
+
chunk_top_k=chunk_top_k
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
return {
|
| 100 |
+
"context": result.text,
|
| 101 |
+
"context_length": len(result.text),
|
| 102 |
+
"retrieval_result": result,
|
| 103 |
+
"status": "success"
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
except Exception as e:
|
| 107 |
+
return {
|
| 108 |
+
"error": f"Direct retrieval error: {str(e)}",
|
| 109 |
+
"status": "error"
|
| 110 |
+
}
|
backend/agentic_system/nodes/qa_node.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Question Answering Node for LangGraph workflow.
|
| 3 |
+
|
| 4 |
+
Handles the final step of providing guided, step-by-step answers using retrieved context.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Dict, Any
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from ..agents.question_answering_agent import QuestionAnsweringAgent
|
| 10 |
+
from .base_node import BaseNode
|
| 11 |
+
|
| 12 |
+
class QANode(BaseNode):
|
| 13 |
+
"""
|
| 14 |
+
Node that uses the Question Answering Agent to provide guided explanations.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self):
|
| 18 |
+
"""Initialize the QA node with the question answering agent."""
|
| 19 |
+
self.qa_agent = QuestionAnsweringAgent()
|
| 20 |
+
|
| 21 |
+
async def process(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
| 22 |
+
"""
|
| 23 |
+
Process the state to generate a guided answer.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
state: Current workflow state containing question and context
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
Updated state with the guided answer
|
| 30 |
+
"""
|
| 31 |
+
try:
|
| 32 |
+
# Extract required information from state using helper methods
|
| 33 |
+
question = self._get_state_value(state, "question", "")
|
| 34 |
+
context = self._get_state_value(state, "context", "")
|
| 35 |
+
|
| 36 |
+
if not question:
|
| 37 |
+
return self._create_updated_state(state, {"error": "No question provided"})
|
| 38 |
+
|
| 39 |
+
if not context:
|
| 40 |
+
return self._create_updated_state(state, {"error": "No context available for answering"})
|
| 41 |
+
|
| 42 |
+
# Generate the guided answer
|
| 43 |
+
qa_pair = await self.qa_agent.answer_question(question, context)
|
| 44 |
+
|
| 45 |
+
# Calculate processing time
|
| 46 |
+
workflow_end_time = datetime.now()
|
| 47 |
+
processing_time = None
|
| 48 |
+
workflow_start_time = self._get_state_value(state, "workflow_start_time")
|
| 49 |
+
if workflow_start_time:
|
| 50 |
+
processing_time = (workflow_end_time - workflow_start_time).total_seconds()
|
| 51 |
+
|
| 52 |
+
# Create updates dictionary
|
| 53 |
+
updates = {
|
| 54 |
+
"answer": qa_pair.answer,
|
| 55 |
+
"qa_pair": qa_pair,
|
| 56 |
+
"total_steps": qa_pair.total_steps,
|
| 57 |
+
"context_used": qa_pair.context_used,
|
| 58 |
+
"status": "completed",
|
| 59 |
+
"workflow_end_time": workflow_end_time,
|
| 60 |
+
"processing_time": processing_time
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
return self._create_updated_state(state, updates)
|
| 64 |
+
|
| 65 |
+
except Exception as e:
|
| 66 |
+
return self._create_updated_state(state, {
|
| 67 |
+
"error": f"QA processing error: {str(e)}",
|
| 68 |
+
"status": "error"
|
| 69 |
+
})
|
| 70 |
+
|
| 71 |
+
async def get_simplified_answer(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
| 72 |
+
"""
|
| 73 |
+
Get simplified answer format for streaming.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
state: Current workflow state
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
Simplified answer dictionary
|
| 80 |
+
"""
|
| 81 |
+
try:
|
| 82 |
+
question = state.get("question", "")
|
| 83 |
+
context = state.get("context", "")
|
| 84 |
+
|
| 85 |
+
if not question or not context:
|
| 86 |
+
return {"error": "Missing question or context"}
|
| 87 |
+
|
| 88 |
+
# Get simplified answer
|
| 89 |
+
answer_dict = await self.qa_agent.get_guided_answer(question, context)
|
| 90 |
+
|
| 91 |
+
return {
|
| 92 |
+
"question": question,
|
| 93 |
+
"answer": answer_dict,
|
| 94 |
+
"status": "completed"
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
return {
|
| 99 |
+
"error": f"Simplified answer error: {str(e)}",
|
| 100 |
+
"status": "error"
|
| 101 |
+
}
|
backend/agentic_system/nodes/retrieval_strategy_node.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retrieval Strategy Node for LangGraph workflow.
|
| 3 |
+
|
| 4 |
+
Handles query analysis to determine optimal retrieval parameters.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Dict, Any, Union
|
| 8 |
+
from ..agents.retrieval_strategy_agent import RetrievalStrategyAgent
|
| 9 |
+
from ..graphs.state_schema import WorkflowState
|
| 10 |
+
from .base_node import BaseNode
|
| 11 |
+
|
| 12 |
+
class RetrievalStrategyNode(BaseNode):
|
| 13 |
+
"""
|
| 14 |
+
Node that uses the Retrieval Strategy Agent to analyze queries and determine parameters.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self):
|
| 18 |
+
"""Initialize the retrieval strategy node with the strategy agent."""
|
| 19 |
+
self.strategy_agent = RetrievalStrategyAgent()
|
| 20 |
+
|
| 21 |
+
async def process(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
| 22 |
+
"""
|
| 23 |
+
Process the state to analyze the query and determine retrieval parameters.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
state: Current workflow state containing the user question
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
Updated state with retrieval parameters
|
| 30 |
+
"""
|
| 31 |
+
try:
|
| 32 |
+
# Extract question from state using helper method
|
| 33 |
+
question = self._get_state_value(state, "question", "")
|
| 34 |
+
|
| 35 |
+
if not question:
|
| 36 |
+
return self._create_updated_state(state, {"error": "No question provided for analysis"})
|
| 37 |
+
|
| 38 |
+
# Analyze the query
|
| 39 |
+
analysis = await self.strategy_agent.analyze_query(question)
|
| 40 |
+
|
| 41 |
+
# Check if mode was already set (preserve existing mode if specified)
|
| 42 |
+
existing_retrieval_params = self._get_state_value(state, "retrieval_params", {})
|
| 43 |
+
existing_mode = existing_retrieval_params.get("mode", "hybrid") if existing_retrieval_params else "hybrid"
|
| 44 |
+
|
| 45 |
+
# Create updates dictionary, preserving existing mode if set
|
| 46 |
+
updates = {
|
| 47 |
+
"retrieval_params": {
|
| 48 |
+
"top_k": analysis.strategy.top_k,
|
| 49 |
+
"chunk_top_k": analysis.strategy.chunk_top_k,
|
| 50 |
+
"mode": existing_mode # Preserve existing mode or default to hybrid
|
| 51 |
+
},
|
| 52 |
+
"query_analysis": analysis,
|
| 53 |
+
"query_category": analysis.strategy.query_category,
|
| 54 |
+
"analysis_reasoning": analysis.strategy.analysis,
|
| 55 |
+
"strategy_status": "completed"
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
return self._create_updated_state(state, updates)
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return self._create_updated_state(state, {
|
| 62 |
+
"error": f"Strategy analysis error: {str(e)}",
|
| 63 |
+
"strategy_status": "error"
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
async def get_parameters_only(self, question: str) -> Dict[str, Any]:
|
| 67 |
+
"""
|
| 68 |
+
Get just the retrieval parameters for a question (utility method).
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
question: The user question to analyze
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
Dictionary with retrieval parameters
|
| 75 |
+
"""
|
| 76 |
+
try:
|
| 77 |
+
return await self.strategy_agent.get_retrieval_parameters(question)
|
| 78 |
+
except Exception as e:
|
| 79 |
+
return {
|
| 80 |
+
"error": f"Parameter extraction error: {str(e)}",
|
| 81 |
+
"top_k": 5, # Fallback defaults
|
| 82 |
+
"chunk_top_k": 2,
|
| 83 |
+
"query_category": "Balanced / Complex"
|
| 84 |
+
}
|
backend/agentic_system/orchestrators/__init__.py
ADDED
|
File without changes
|
backend/agentic_system/orchestrators/debug_qa_workflow.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Debug script to test QA workflow integration with research exploration.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import logging
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
# Set up logging
|
| 10 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
async def test_qa_workflow_standalone():
|
| 14 |
+
"""Test the QA workflow in isolation."""
|
| 15 |
+
|
| 16 |
+
logger.info("π§ͺ Testing QA Workflow Standalone")
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from ..graphs.qa_workflow import QAWorkflow
|
| 20 |
+
|
| 21 |
+
# Test normal QA workflow
|
| 22 |
+
qa_workflow = QAWorkflow()
|
| 23 |
+
|
| 24 |
+
test_question = "What is attention mechanism in transformers?"
|
| 25 |
+
logger.info(f"Testing question: {test_question}")
|
| 26 |
+
|
| 27 |
+
result = await qa_workflow.process_question(test_question)
|
| 28 |
+
|
| 29 |
+
logger.info(f"β
QA Workflow Result:")
|
| 30 |
+
logger.info(f" Status: {result.status}")
|
| 31 |
+
logger.info(f" Error: {result.error}")
|
| 32 |
+
logger.info(f" Answer type: {type(result.answer)}")
|
| 33 |
+
logger.info(f" Answer: {result.answer}")
|
| 34 |
+
|
| 35 |
+
return result
|
| 36 |
+
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.error(f"β QA Workflow test failed: {e}")
|
| 39 |
+
import traceback
|
| 40 |
+
traceback.print_exc()
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
async def test_qa_workflow_with_local_mode():
|
| 44 |
+
"""Test QA workflow with local mode injection."""
|
| 45 |
+
|
| 46 |
+
logger.info("π¬ Testing QA Workflow with Local Mode")
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
from ..graphs.qa_workflow import QAWorkflow
|
| 50 |
+
from ..graphs.state_schema import WorkflowState
|
| 51 |
+
|
| 52 |
+
qa_workflow = QAWorkflow()
|
| 53 |
+
|
| 54 |
+
# Create initial state with local mode
|
| 55 |
+
test_question = "What is attention mechanism in transformers?"
|
| 56 |
+
initial_state = WorkflowState(
|
| 57 |
+
question=test_question,
|
| 58 |
+
workflow_start_time=datetime.now(),
|
| 59 |
+
retrieval_params={
|
| 60 |
+
"mode": "local",
|
| 61 |
+
"top_k": 2,
|
| 62 |
+
"chunk_top_k": 2
|
| 63 |
+
}
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
logger.info(f"Testing with local mode: {test_question}")
|
| 67 |
+
logger.info(f"Initial state retrieval_params: {initial_state.retrieval_params}")
|
| 68 |
+
|
| 69 |
+
# Run workflow directly
|
| 70 |
+
config = {"configurable": {"thread_id": "debug_test"}}
|
| 71 |
+
result = await qa_workflow.app.ainvoke(initial_state.dict(), config)
|
| 72 |
+
|
| 73 |
+
workflow_state = WorkflowState(**result)
|
| 74 |
+
|
| 75 |
+
logger.info(f"β
Local Mode QA Result:")
|
| 76 |
+
logger.info(f" Status: {workflow_state.status}")
|
| 77 |
+
logger.info(f" Error: {workflow_state.error}")
|
| 78 |
+
logger.info(f" Answer type: {type(workflow_state.answer)}")
|
| 79 |
+
logger.info(f" Answer: {workflow_state.answer}")
|
| 80 |
+
logger.info(f" Retrieval params: {workflow_state.retrieval_params}")
|
| 81 |
+
|
| 82 |
+
return workflow_state
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
logger.error(f"β Local mode QA test failed: {e}")
|
| 86 |
+
import traceback
|
| 87 |
+
traceback.print_exc()
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
async def test_question_generation():
|
| 91 |
+
"""Test just the question generation."""
|
| 92 |
+
|
| 93 |
+
logger.info("π Testing Question Generation")
|
| 94 |
+
|
| 95 |
+
try:
|
| 96 |
+
from ..agents.question_generation_agent import QuestionGenerationAgent, QuestionGenerationRequest
|
| 97 |
+
|
| 98 |
+
agent = QuestionGenerationAgent()
|
| 99 |
+
|
| 100 |
+
request = QuestionGenerationRequest(
|
| 101 |
+
topic="transformers in machine learning",
|
| 102 |
+
max_questions=3
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
question_set = await agent.generate_research_questions(request)
|
| 106 |
+
|
| 107 |
+
logger.info(f"β
Question Generation Result:")
|
| 108 |
+
logger.info(f" Total questions: {len(question_set.questions)}")
|
| 109 |
+
logger.info(f" Categories: {[cat.value for cat in question_set.categories_covered]}")
|
| 110 |
+
|
| 111 |
+
for i, q in enumerate(question_set.questions):
|
| 112 |
+
logger.info(f" Q{i+1}: [{q.category.value}] {q.question}")
|
| 113 |
+
|
| 114 |
+
return question_set
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logger.error(f"β Question generation test failed: {e}")
|
| 118 |
+
import traceback
|
| 119 |
+
traceback.print_exc()
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
|
| 124 |
+
async def main():
|
| 125 |
+
logger.info("π Starting Debug Tests")
|
| 126 |
+
|
| 127 |
+
# Test 1: Question Generation
|
| 128 |
+
questions = await test_question_generation()
|
| 129 |
+
|
| 130 |
+
# Test 2: Normal QA Workflow
|
| 131 |
+
qa_result = await test_qa_workflow_standalone()
|
| 132 |
+
|
| 133 |
+
# Test 3: QA Workflow with Local Mode
|
| 134 |
+
local_result = await test_qa_workflow_with_local_mode()
|
| 135 |
+
|
| 136 |
+
logger.info("π― Debug Tests Complete!")
|
| 137 |
+
|
| 138 |
+
if questions and qa_result and local_result:
|
| 139 |
+
logger.info("β
All components working!")
|
| 140 |
+
else:
|
| 141 |
+
logger.error("β Some components failed!")
|
| 142 |
+
|
| 143 |
+
asyncio.run(main())
|
backend/agentic_system/orchestrators/research_exploration_orchestrator_refactored.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Research Exploration Orchestrator for systematic paper analysis.
|
| 3 |
+
|
| 4 |
+
Refactored version with extracted utilities for better maintainability and debugging.
|
| 5 |
+
Coordinates question generation and parallel QA workflow execution to provide
|
| 6 |
+
comprehensive understanding of research topics through systematic inquiry.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import asyncio
|
| 10 |
+
import time
|
| 11 |
+
import logging
|
| 12 |
+
from typing import List, Dict, Optional
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
from .research_exploration_schema import (
|
| 16 |
+
ResearchExplorationRequest,
|
| 17 |
+
ResearchExplorationResults,
|
| 18 |
+
CategoryResults,
|
| 19 |
+
QuestionResult
|
| 20 |
+
)
|
| 21 |
+
from ..agents.question_generation_agent import (
|
| 22 |
+
QuestionGenerationAgent,
|
| 23 |
+
QuestionGenerationRequest,
|
| 24 |
+
QuestionCategory
|
| 25 |
+
)
|
| 26 |
+
from ..graphs.qa_workflow import QAWorkflow
|
| 27 |
+
|
| 28 |
+
# Import utilities
|
| 29 |
+
from .utils import (
|
| 30 |
+
setup_exploration_logging,
|
| 31 |
+
log_exploration_phase,
|
| 32 |
+
log_exploration_result,
|
| 33 |
+
log_workflow_progress,
|
| 34 |
+
log_workflow_completion,
|
| 35 |
+
log_error,
|
| 36 |
+
extract_answer_text,
|
| 37 |
+
extract_answer_summary_only,
|
| 38 |
+
format_detailed_answer_from_steps,
|
| 39 |
+
extract_confidence_score,
|
| 40 |
+
extract_context_sources,
|
| 41 |
+
is_valid_answer,
|
| 42 |
+
extract_answer_metadata,
|
| 43 |
+
process_question_with_mix_mode,
|
| 44 |
+
process_question_with_custom_params,
|
| 45 |
+
get_enhanced_retrieval_params,
|
| 46 |
+
diagnose_workflow_failure,
|
| 47 |
+
retry_question_with_fallback_modes,
|
| 48 |
+
organize_results_by_category,
|
| 49 |
+
generate_research_summary,
|
| 50 |
+
calculate_category_statistics,
|
| 51 |
+
identify_problematic_categories,
|
| 52 |
+
generate_failure_analysis
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ResearchExplorationOrchestrator:
|
| 57 |
+
"""
|
| 58 |
+
Orchestrates comprehensive research exploration through systematic questioning.
|
| 59 |
+
|
| 60 |
+
Refactored version with utilities extracted for better maintainability and debugging.
|
| 61 |
+
Combines question generation with parallel QA workflows to provide deep,
|
| 62 |
+
structured understanding of research topics and papers.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, enable_fallback_retry: bool = True, detailed_answers: bool = True):
|
| 66 |
+
"""
|
| 67 |
+
Initialize the research exploration orchestrator.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
enable_fallback_retry: Whether to retry failed questions with different modes
|
| 71 |
+
detailed_answers: Whether to extract full detailed answers (True) or summaries (False)
|
| 72 |
+
"""
|
| 73 |
+
# Initialize components
|
| 74 |
+
self.question_agent = QuestionGenerationAgent()
|
| 75 |
+
self.qa_workflow = QAWorkflow()
|
| 76 |
+
|
| 77 |
+
# Configuration
|
| 78 |
+
self.enable_fallback_retry = enable_fallback_retry
|
| 79 |
+
self.detailed_answers = detailed_answers
|
| 80 |
+
|
| 81 |
+
# Set up logging
|
| 82 |
+
self.logger = setup_exploration_logging(__name__)
|
| 83 |
+
|
| 84 |
+
# Track active workflows for monitoring
|
| 85 |
+
self.active_workflows = {}
|
| 86 |
+
|
| 87 |
+
async def explore_research_topic(self, request: ResearchExplorationRequest) -> ResearchExplorationResults:
|
| 88 |
+
"""
|
| 89 |
+
Conduct comprehensive exploration of a research topic.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
request: Research exploration request with topic and parameters
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
ResearchExplorationResults: Complete exploration results
|
| 96 |
+
"""
|
| 97 |
+
exploration_start = datetime.now()
|
| 98 |
+
start_time = time.time()
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
self.logger.info(f"π¬ Starting research exploration: {request.topic}")
|
| 102 |
+
|
| 103 |
+
# Phase 1: Generate research questions
|
| 104 |
+
log_exploration_phase(self.logger, 1, "Generating research questions")
|
| 105 |
+
question_set = await self._generate_questions(request)
|
| 106 |
+
|
| 107 |
+
self.logger.info(f"β
Generated {len(question_set.questions)} questions across {len(question_set.categories_covered)} categories")
|
| 108 |
+
|
| 109 |
+
# Phase 2: Process questions in parallel
|
| 110 |
+
log_exploration_phase(self.logger, 2, "Processing questions through QA workflows")
|
| 111 |
+
question_results = await self._process_questions_parallel(
|
| 112 |
+
question_set.questions,
|
| 113 |
+
request.parallel_limit,
|
| 114 |
+
request.timeout_per_question
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# Phase 3: Organize results by category
|
| 118 |
+
log_exploration_phase(self.logger, 3, "Organizing results by category")
|
| 119 |
+
category_results = organize_results_by_category(question_results)
|
| 120 |
+
|
| 121 |
+
# Phase 4: Generate summary if requested
|
| 122 |
+
research_summary = None
|
| 123 |
+
if request.include_summary:
|
| 124 |
+
log_exploration_phase(self.logger, 4, "Generating research summary")
|
| 125 |
+
research_summary = await generate_research_summary(
|
| 126 |
+
request.topic,
|
| 127 |
+
category_results,
|
| 128 |
+
self.qa_workflow,
|
| 129 |
+
self.logger
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Calculate statistics and analysis
|
| 133 |
+
stats = calculate_category_statistics(category_results)
|
| 134 |
+
failure_analysis = generate_failure_analysis(category_results)
|
| 135 |
+
|
| 136 |
+
# Log diagnostic information
|
| 137 |
+
self._log_diagnostic_info(stats, failure_analysis)
|
| 138 |
+
|
| 139 |
+
# Create final results
|
| 140 |
+
results = ResearchExplorationResults(
|
| 141 |
+
topic=request.topic,
|
| 142 |
+
question_set=question_set,
|
| 143 |
+
category_results=category_results,
|
| 144 |
+
total_questions=stats['total_questions'],
|
| 145 |
+
successful_answers=stats['total_successful'],
|
| 146 |
+
failed_questions=stats['total_questions'] - stats['total_successful'],
|
| 147 |
+
success_rate=stats['overall_success_rate'],
|
| 148 |
+
exploration_start_time=exploration_start,
|
| 149 |
+
exploration_end_time=datetime.now(),
|
| 150 |
+
total_processing_time=time.time() - start_time,
|
| 151 |
+
research_summary=research_summary
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
log_exploration_result(
|
| 155 |
+
self.logger,
|
| 156 |
+
stats['total_successful'],
|
| 157 |
+
stats['total_questions']
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
return results
|
| 161 |
+
|
| 162 |
+
except Exception as e:
|
| 163 |
+
log_error(self.logger, "Research exploration", e)
|
| 164 |
+
raise
|
| 165 |
+
|
| 166 |
+
async def _generate_questions(self, request: ResearchExplorationRequest):
|
| 167 |
+
"""Generate research questions based on the request."""
|
| 168 |
+
question_request = QuestionGenerationRequest(
|
| 169 |
+
topic=request.topic,
|
| 170 |
+
max_questions=request.max_questions,
|
| 171 |
+
focus_areas=request.focus_categories
|
| 172 |
+
)
|
| 173 |
+
return await self.question_agent.generate_research_questions(question_request)
|
| 174 |
+
|
| 175 |
+
async def _process_questions_parallel(
|
| 176 |
+
self,
|
| 177 |
+
questions: List,
|
| 178 |
+
parallel_limit: int,
|
| 179 |
+
timeout_per_question: int
|
| 180 |
+
) -> List[QuestionResult]:
|
| 181 |
+
"""
|
| 182 |
+
Process multiple questions through QA workflows in parallel with enhanced error handling.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
questions: List of research questions to process
|
| 186 |
+
parallel_limit: Maximum number of parallel workflows
|
| 187 |
+
timeout_per_question: Timeout per question in seconds
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
List[QuestionResult]: Results from processing all questions
|
| 191 |
+
"""
|
| 192 |
+
semaphore = asyncio.Semaphore(parallel_limit)
|
| 193 |
+
|
| 194 |
+
async def process_single_question(question) -> QuestionResult:
|
| 195 |
+
"""Process a single question with timeout and enhanced error handling."""
|
| 196 |
+
async with semaphore:
|
| 197 |
+
question_start = time.time()
|
| 198 |
+
|
| 199 |
+
try:
|
| 200 |
+
log_workflow_progress(self.logger, question.question)
|
| 201 |
+
|
| 202 |
+
# Try primary approach with enhanced parameters
|
| 203 |
+
workflow_state = await asyncio.wait_for(
|
| 204 |
+
self._process_question_enhanced(question.question),
|
| 205 |
+
timeout=timeout_per_question
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
log_workflow_completion(
|
| 209 |
+
self.logger,
|
| 210 |
+
workflow_state.status,
|
| 211 |
+
workflow_state.error
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
processing_time = time.time() - question_start
|
| 215 |
+
|
| 216 |
+
# Check if workflow completed successfully
|
| 217 |
+
if workflow_state.error:
|
| 218 |
+
# If fallback retry is enabled, try different modes
|
| 219 |
+
if self.enable_fallback_retry:
|
| 220 |
+
self.logger.debug(f"π Attempting fallback retry for failed question")
|
| 221 |
+
workflow_state = await asyncio.wait_for(
|
| 222 |
+
retry_question_with_fallback_modes(
|
| 223 |
+
question.question,
|
| 224 |
+
self.qa_workflow,
|
| 225 |
+
self.logger
|
| 226 |
+
),
|
| 227 |
+
timeout=timeout_per_question * 2 # Extended timeout for retry
|
| 228 |
+
)
|
| 229 |
+
processing_time = time.time() - question_start
|
| 230 |
+
|
| 231 |
+
if workflow_state.error:
|
| 232 |
+
diagnosis = diagnose_workflow_failure(workflow_state, self.logger)
|
| 233 |
+
return QuestionResult(
|
| 234 |
+
question=question,
|
| 235 |
+
status="failed",
|
| 236 |
+
error_message=f"{workflow_state.error} | Diagnosis: {diagnosis}",
|
| 237 |
+
processing_time=processing_time,
|
| 238 |
+
workflow_state=workflow_state
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
# Extract answer text based on detail preference
|
| 242 |
+
if self.detailed_answers:
|
| 243 |
+
answer_text = extract_answer_text(workflow_state.answer) # Full detailed answer
|
| 244 |
+
else:
|
| 245 |
+
answer_text = extract_answer_summary_only(workflow_state.answer) # Summary only
|
| 246 |
+
|
| 247 |
+
# Use more lenient validation for detailed answers
|
| 248 |
+
min_length = 5 if self.detailed_answers else 10
|
| 249 |
+
if not is_valid_answer(answer_text, min_length=min_length):
|
| 250 |
+
return QuestionResult(
|
| 251 |
+
question=question,
|
| 252 |
+
status="failed",
|
| 253 |
+
error_message="No valid answer generated or answer too short",
|
| 254 |
+
processing_time=processing_time,
|
| 255 |
+
workflow_state=workflow_state
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# Extract comprehensive metadata
|
| 259 |
+
metadata = extract_answer_metadata(workflow_state)
|
| 260 |
+
|
| 261 |
+
return QuestionResult(
|
| 262 |
+
question=question,
|
| 263 |
+
answer=answer_text,
|
| 264 |
+
context_sources=metadata.get('context_sources', []),
|
| 265 |
+
confidence_score=metadata.get('confidence_score'),
|
| 266 |
+
processing_time=processing_time,
|
| 267 |
+
status="completed",
|
| 268 |
+
workflow_state=workflow_state
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
except asyncio.TimeoutError:
|
| 272 |
+
return QuestionResult(
|
| 273 |
+
question=question,
|
| 274 |
+
status="failed",
|
| 275 |
+
error_message=f"Timeout after {timeout_per_question} seconds",
|
| 276 |
+
processing_time=time.time() - question_start
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
except Exception as e:
|
| 280 |
+
return QuestionResult(
|
| 281 |
+
question=question,
|
| 282 |
+
status="failed",
|
| 283 |
+
error_message=f"Processing exception: {str(e)}",
|
| 284 |
+
processing_time=time.time() - question_start
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
# Process all questions in parallel
|
| 288 |
+
tasks = [process_single_question(q) for q in questions]
|
| 289 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 290 |
+
|
| 291 |
+
# Handle any exceptions in results
|
| 292 |
+
processed_results = []
|
| 293 |
+
for i, result in enumerate(results):
|
| 294 |
+
if isinstance(result, Exception):
|
| 295 |
+
processed_results.append(QuestionResult(
|
| 296 |
+
question=questions[i],
|
| 297 |
+
status="failed",
|
| 298 |
+
error_message=f"Async processing error: {str(result)}"
|
| 299 |
+
))
|
| 300 |
+
else:
|
| 301 |
+
processed_results.append(result)
|
| 302 |
+
|
| 303 |
+
return processed_results
|
| 304 |
+
|
| 305 |
+
async def _process_question_enhanced(self, question: str):
|
| 306 |
+
"""Process a question with enhanced retrieval parameters."""
|
| 307 |
+
# Use enhanced parameters for better coverage
|
| 308 |
+
enhanced_params = get_enhanced_retrieval_params("mix")
|
| 309 |
+
|
| 310 |
+
# Log the parameters being used
|
| 311 |
+
self.logger.debug(f"π§ Enhanced retrieval params: {enhanced_params}")
|
| 312 |
+
|
| 313 |
+
return await process_question_with_custom_params(
|
| 314 |
+
question,
|
| 315 |
+
self.qa_workflow,
|
| 316 |
+
enhanced_params,
|
| 317 |
+
self.logger
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
def _log_diagnostic_info(self, stats: dict, failure_analysis: dict):
|
| 321 |
+
"""Log comprehensive diagnostic information."""
|
| 322 |
+
# Log overall statistics
|
| 323 |
+
self.logger.info(f"π Exploration Statistics:")
|
| 324 |
+
self.logger.info(f" Total Categories: {stats['total_categories']}")
|
| 325 |
+
self.logger.info(f" Overall Success Rate: {stats['overall_success_rate']:.1%}")
|
| 326 |
+
|
| 327 |
+
# Log category breakdown
|
| 328 |
+
for category_stat in stats['category_breakdown']:
|
| 329 |
+
self.logger.info(f" {category_stat['category']}: {category_stat['successful']}/{category_stat['questions']} ({category_stat['success_rate']:.1%})")
|
| 330 |
+
|
| 331 |
+
# Log failure analysis
|
| 332 |
+
if failure_analysis['total_failures'] > 0:
|
| 333 |
+
self.logger.warning(f"π Failure Analysis:")
|
| 334 |
+
self.logger.warning(f" Total Failures: {failure_analysis['total_failures']}")
|
| 335 |
+
for reason, count in failure_analysis['failure_reasons'].items():
|
| 336 |
+
self.logger.warning(f" {reason}: {count}")
|
| 337 |
+
|
| 338 |
+
for pattern in failure_analysis['common_patterns']:
|
| 339 |
+
self.logger.warning(f" Pattern: {pattern}")
|
| 340 |
+
|
| 341 |
+
async def quick_exploration(self, topic: str, max_questions: int = 10) -> ResearchExplorationResults:
|
| 342 |
+
"""
|
| 343 |
+
Quick research exploration with default settings.
|
| 344 |
+
|
| 345 |
+
Args:
|
| 346 |
+
topic: Research topic to explore
|
| 347 |
+
max_questions: Maximum number of questions
|
| 348 |
+
|
| 349 |
+
Returns:
|
| 350 |
+
ResearchExplorationResults: Exploration results
|
| 351 |
+
"""
|
| 352 |
+
request = ResearchExplorationRequest(
|
| 353 |
+
topic=topic,
|
| 354 |
+
max_questions=max_questions,
|
| 355 |
+
parallel_limit=3,
|
| 356 |
+
include_summary=True
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
return await self.explore_research_topic(request)
|
| 360 |
+
|
| 361 |
+
async def debug_exploration(self, topic: str, max_questions: int = 3) -> ResearchExplorationResults:
|
| 362 |
+
"""
|
| 363 |
+
Debug-focused exploration with detailed logging and analysis.
|
| 364 |
+
|
| 365 |
+
Args:
|
| 366 |
+
topic: Research topic to explore
|
| 367 |
+
max_questions: Maximum number of questions (default: 3 for quick debugging)
|
| 368 |
+
|
| 369 |
+
Returns:
|
| 370 |
+
ResearchExplorationResults: Exploration results with enhanced diagnostics
|
| 371 |
+
"""
|
| 372 |
+
# Enable debug logging
|
| 373 |
+
self.logger.setLevel(logging.DEBUG)
|
| 374 |
+
|
| 375 |
+
# Force fallback retry for debugging
|
| 376 |
+
self.enable_fallback_retry = True
|
| 377 |
+
|
| 378 |
+
self.logger.info(f"π Debug exploration mode enabled for: {topic}")
|
| 379 |
+
|
| 380 |
+
request = ResearchExplorationRequest(
|
| 381 |
+
topic=topic,
|
| 382 |
+
max_questions=max_questions,
|
| 383 |
+
parallel_limit=1, # Sequential for better debugging
|
| 384 |
+
include_summary=True,
|
| 385 |
+
timeout_per_question=180 # Extended timeout
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
return await self.explore_research_topic(request)
|
backend/agentic_system/orchestrators/research_exploration_schema.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Schema definitions for research exploration orchestration.
|
| 3 |
+
|
| 4 |
+
Defines data structures for managing multiple QA workflows in parallel
|
| 5 |
+
and aggregating their results for comprehensive research understanding.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import List, Dict, Optional
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from pydantic import BaseModel, Field
|
| 11 |
+
|
| 12 |
+
from ..agents.question_generation_agent.question_generation_schema import (
|
| 13 |
+
ResearchQuestion,
|
| 14 |
+
QuestionCategory,
|
| 15 |
+
QuestionSet
|
| 16 |
+
)
|
| 17 |
+
from ..graphs.state_schema import WorkflowState
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class QuestionResult(BaseModel):
|
| 21 |
+
"""Result from processing a single research question through QA workflow."""
|
| 22 |
+
|
| 23 |
+
question: ResearchQuestion = Field(..., description="The original research question")
|
| 24 |
+
answer: Optional[str] = Field(None, description="Generated answer")
|
| 25 |
+
context_sources: List[str] = Field(default=[], description="Source documents used")
|
| 26 |
+
confidence_score: Optional[float] = Field(None, description="Answer confidence (0-1)")
|
| 27 |
+
processing_time: Optional[float] = Field(None, description="Time taken to process (seconds)")
|
| 28 |
+
status: str = Field(default="pending", description="Processing status: pending, completed, failed")
|
| 29 |
+
error_message: Optional[str] = Field(None, description="Error details if failed")
|
| 30 |
+
workflow_state: Optional[WorkflowState] = Field(None, description="Complete workflow state")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class CategoryResults(BaseModel):
|
| 34 |
+
"""Results for all questions within a specific research category."""
|
| 35 |
+
|
| 36 |
+
category: QuestionCategory = Field(..., description="The question category")
|
| 37 |
+
questions_processed: int = Field(..., description="Number of questions processed")
|
| 38 |
+
successful_answers: int = Field(..., description="Number of successful answers")
|
| 39 |
+
results: List[QuestionResult] = Field(..., description="Individual question results")
|
| 40 |
+
category_summary: Optional[str] = Field(None, description="Summary of findings for this category")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ResearchExplorationResults(BaseModel):
|
| 44 |
+
"""Complete results from exploring a research topic through systematic questioning."""
|
| 45 |
+
|
| 46 |
+
topic: str = Field(..., description="Research topic explored")
|
| 47 |
+
question_set: QuestionSet = Field(..., description="Original set of questions generated")
|
| 48 |
+
category_results: List[CategoryResults] = Field(..., description="Results by category")
|
| 49 |
+
|
| 50 |
+
# Overall statistics
|
| 51 |
+
total_questions: int = Field(..., description="Total questions processed")
|
| 52 |
+
successful_answers: int = Field(..., description="Number of successful answers")
|
| 53 |
+
failed_questions: int = Field(..., description="Number of failed questions")
|
| 54 |
+
success_rate: float = Field(..., description="Success rate (0-1)")
|
| 55 |
+
|
| 56 |
+
# Timing information
|
| 57 |
+
exploration_start_time: datetime = Field(..., description="When exploration started")
|
| 58 |
+
exploration_end_time: Optional[datetime] = Field(None, description="When exploration completed")
|
| 59 |
+
total_processing_time: Optional[float] = Field(None, description="Total time in seconds")
|
| 60 |
+
|
| 61 |
+
# Aggregated insights
|
| 62 |
+
key_insights: List[str] = Field(default=[], description="Main insights discovered")
|
| 63 |
+
research_summary: Optional[str] = Field(None, description="Overall research summary")
|
| 64 |
+
|
| 65 |
+
def get_results_by_category(self, category: QuestionCategory) -> Optional[CategoryResults]:
|
| 66 |
+
"""Get results for a specific category."""
|
| 67 |
+
for cat_result in self.category_results:
|
| 68 |
+
if cat_result.category == category:
|
| 69 |
+
return cat_result
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
def get_high_confidence_answers(self, min_confidence: float = 0.7) -> List[QuestionResult]:
|
| 73 |
+
"""Get answers with confidence above threshold."""
|
| 74 |
+
high_confidence = []
|
| 75 |
+
for cat_result in self.category_results:
|
| 76 |
+
for result in cat_result.results:
|
| 77 |
+
if result.confidence_score and result.confidence_score >= min_confidence:
|
| 78 |
+
high_confidence.append(result)
|
| 79 |
+
return high_confidence
|
| 80 |
+
|
| 81 |
+
def get_failed_questions(self) -> List[QuestionResult]:
|
| 82 |
+
"""Get all questions that failed processing."""
|
| 83 |
+
failed = []
|
| 84 |
+
for cat_result in self.category_results:
|
| 85 |
+
for result in cat_result.results:
|
| 86 |
+
if result.status == "failed":
|
| 87 |
+
failed.append(result)
|
| 88 |
+
return failed
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class ResearchExplorationRequest(BaseModel):
|
| 92 |
+
"""Request for comprehensive research topic exploration."""
|
| 93 |
+
|
| 94 |
+
topic: str = Field(..., description="Research topic to explore")
|
| 95 |
+
max_questions: int = Field(default=5, ge=2, description="Maximum questions to generate")
|
| 96 |
+
focus_categories: Optional[List[QuestionCategory]] = Field(
|
| 97 |
+
None,
|
| 98 |
+
description="Specific categories to focus on"
|
| 99 |
+
)
|
| 100 |
+
parallel_limit: int = Field(
|
| 101 |
+
default=5,
|
| 102 |
+
ge=1,
|
| 103 |
+
le=10,
|
| 104 |
+
description="Maximum parallel QA workflows"
|
| 105 |
+
)
|
| 106 |
+
include_summary: bool = Field(
|
| 107 |
+
default=True,
|
| 108 |
+
description="Whether to generate overall research summary"
|
| 109 |
+
)
|
| 110 |
+
timeout_per_question: int = Field(
|
| 111 |
+
default=120,
|
| 112 |
+
description="Timeout per question in seconds"
|
| 113 |
+
)
|
backend/agentic_system/orchestrators/test_research_exploration.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Conversational Research Exploration Test Script.
|
| 3 |
+
|
| 4 |
+
Interactive test environment for the Research Exploration Engine with
|
| 5 |
+
comprehensive logging and result persistence for analysis.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import asyncio
|
| 9 |
+
import logging
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from typing import Dict, Any, List
|
| 14 |
+
|
| 15 |
+
from .research_exploration_orchestrator_refactored import ResearchExplorationOrchestrator
|
| 16 |
+
from .research_exploration_schema import ResearchExplorationRequest
|
| 17 |
+
from ..agents.question_generation_agent.question_generation_schema import QuestionCategory
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ConversationalExplorer:
|
| 21 |
+
"""Interactive research exploration with comprehensive logging and persistence."""
|
| 22 |
+
|
| 23 |
+
def __init__(self):
|
| 24 |
+
"""Initialize the conversational explorer."""
|
| 25 |
+
self.orchestrator = ResearchExplorationOrchestrator()
|
| 26 |
+
self.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 27 |
+
self.turn_count = 0
|
| 28 |
+
self.results_dir = Path("test_results/paper_exploration")
|
| 29 |
+
self.results_dir.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
# Set up comprehensive logging
|
| 32 |
+
log_file = self.results_dir / f"session_{self.session_id}.log"
|
| 33 |
+
logging.basicConfig(
|
| 34 |
+
level=logging.INFO,
|
| 35 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 36 |
+
handlers=[
|
| 37 |
+
logging.FileHandler(log_file),
|
| 38 |
+
logging.StreamHandler()
|
| 39 |
+
]
|
| 40 |
+
)
|
| 41 |
+
self.logger = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
async def start_conversation(self):
|
| 44 |
+
"""Start the conversational research exploration."""
|
| 45 |
+
self.logger.info("π Welcome to Conversational Research Exploration!")
|
| 46 |
+
self.logger.info(f"π Session ID: {self.session_id}")
|
| 47 |
+
self.logger.info(f"πΎ Results will be saved to: {self.results_dir}")
|
| 48 |
+
|
| 49 |
+
print("\n" + "="*60)
|
| 50 |
+
print("π§ RESEARCH EXPLORATION ENGINE - CONVERSATIONAL MODE")
|
| 51 |
+
print("="*60)
|
| 52 |
+
print("This tool will help you explore research topics systematically.")
|
| 53 |
+
print("Each turn generates 2 questions by default and saves full results.")
|
| 54 |
+
print("Type 'quit' to exit at any time.")
|
| 55 |
+
print("="*60)
|
| 56 |
+
|
| 57 |
+
while True:
|
| 58 |
+
try:
|
| 59 |
+
topic = self._get_user_topic()
|
| 60 |
+
if topic.lower() == 'quit':
|
| 61 |
+
break
|
| 62 |
+
|
| 63 |
+
max_questions = self._get_max_questions()
|
| 64 |
+
await self._explore_turn(topic, max_questions)
|
| 65 |
+
|
| 66 |
+
if not self._continue_conversation():
|
| 67 |
+
break
|
| 68 |
+
|
| 69 |
+
except KeyboardInterrupt:
|
| 70 |
+
print("\nπ Conversation interrupted by user")
|
| 71 |
+
break
|
| 72 |
+
except Exception as e:
|
| 73 |
+
self.logger.error(f"β Error in conversation: {e}")
|
| 74 |
+
print(f"Error occurred: {e}")
|
| 75 |
+
|
| 76 |
+
self._close_session()
|
| 77 |
+
|
| 78 |
+
async def _explore_turn(self, topic: str, max_questions: int):
|
| 79 |
+
"""Execute a single exploration turn with full logging and saving."""
|
| 80 |
+
self.turn_count += 1
|
| 81 |
+
turn_start = datetime.now()
|
| 82 |
+
|
| 83 |
+
self.logger.info(f"\nπ TURN {self.turn_count} STARTING")
|
| 84 |
+
self.logger.info(f"π Topic: {topic}")
|
| 85 |
+
self.logger.info(f"β Max Questions: {max_questions}")
|
| 86 |
+
|
| 87 |
+
print(f"\nπ Exploring: '{topic}' (Turn {self.turn_count})")
|
| 88 |
+
print("β³ Generating questions and retrieving answers...")
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
# Execute the exploration
|
| 92 |
+
results = await self.orchestrator.quick_exploration(
|
| 93 |
+
topic=topic,
|
| 94 |
+
max_questions=max_questions
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
turn_end = datetime.now()
|
| 98 |
+
processing_time = (turn_end - turn_start).total_seconds()
|
| 99 |
+
|
| 100 |
+
# Create comprehensive turn data
|
| 101 |
+
turn_data = {
|
| 102 |
+
"session_id": self.session_id,
|
| 103 |
+
"turn_number": self.turn_count,
|
| 104 |
+
"timestamp": turn_start.isoformat(),
|
| 105 |
+
"topic": topic,
|
| 106 |
+
"max_questions": max_questions,
|
| 107 |
+
"processing_time_seconds": processing_time,
|
| 108 |
+
"results": self._serialize_results(results),
|
| 109 |
+
"summary": {
|
| 110 |
+
"total_questions": results.total_questions,
|
| 111 |
+
"successful_answers": results.successful_answers,
|
| 112 |
+
"success_rate": results.success_rate,
|
| 113 |
+
"categories_covered": [cat.category.value for cat in results.category_results]
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
# Save turn results
|
| 118 |
+
self._save_turn_results(turn_data)
|
| 119 |
+
|
| 120 |
+
# Display results
|
| 121 |
+
self._display_turn_results(results, processing_time)
|
| 122 |
+
|
| 123 |
+
self.logger.info(f"β
Turn {self.turn_count} completed successfully")
|
| 124 |
+
|
| 125 |
+
except Exception as e:
|
| 126 |
+
self.logger.error(f"β Turn {self.turn_count} failed: {e}")
|
| 127 |
+
print(f"β Exploration failed: {e}")
|
| 128 |
+
|
| 129 |
+
def _display_turn_results(self, results, processing_time: float):
|
| 130 |
+
"""Display the results of a turn in a user-friendly format."""
|
| 131 |
+
print(f"\nπ RESULTS (Turn {self.turn_count})")
|
| 132 |
+
print("="*50)
|
| 133 |
+
print(f"β
Generated {results.total_questions} questions")
|
| 134 |
+
print(f"β
Successfully answered {results.successful_answers} questions")
|
| 135 |
+
print(f"β
Success rate: {results.success_rate:.1%}")
|
| 136 |
+
print(f"β±οΈ Total processing time: {processing_time:.2f}s")
|
| 137 |
+
|
| 138 |
+
# Show questions and answers by category
|
| 139 |
+
for category_result in results.category_results:
|
| 140 |
+
if category_result.results:
|
| 141 |
+
print(f"\nπ {category_result.category.value.upper()} Category:")
|
| 142 |
+
for i, result in enumerate(category_result.results, 1):
|
| 143 |
+
if result.status == "completed":
|
| 144 |
+
print(f"\n Q{i}: {result.question.question}")
|
| 145 |
+
print(f" A{i}: {result.answer[:300]}...")
|
| 146 |
+
print(f" β±οΈ Question processing: {result.processing_time:.2f}s")
|
| 147 |
+
print(f" π Priority: {result.question.priority}/10")
|
| 148 |
+
|
| 149 |
+
print("\n" + "="*50)
|
| 150 |
+
|
| 151 |
+
def _save_turn_results(self, turn_data: Dict[str, Any]):
|
| 152 |
+
"""Save comprehensive turn results to files."""
|
| 153 |
+
# Save detailed JSON
|
| 154 |
+
json_file = self.results_dir / f"turn_{self.turn_count}_{self.session_id}.json"
|
| 155 |
+
with open(json_file, 'w', encoding='utf-8') as f:
|
| 156 |
+
json.dump(turn_data, f, indent=2, ensure_ascii=False)
|
| 157 |
+
|
| 158 |
+
# Save readable summary
|
| 159 |
+
summary_file = self.results_dir / f"turn_{self.turn_count}_{self.session_id}_summary.txt"
|
| 160 |
+
with open(summary_file, 'w', encoding='utf-8') as f:
|
| 161 |
+
f.write(f"RESEARCH EXPLORATION - TURN {self.turn_count}\n")
|
| 162 |
+
f.write("="*50 + "\n")
|
| 163 |
+
f.write(f"Session ID: {self.session_id}\n")
|
| 164 |
+
f.write(f"Timestamp: {turn_data['timestamp']}\n")
|
| 165 |
+
f.write(f"Topic: {turn_data['topic']}\n")
|
| 166 |
+
f.write(f"Max Questions: {turn_data['max_questions']}\n")
|
| 167 |
+
f.write(f"Processing Time: {turn_data['processing_time_seconds']:.2f}s\n\n")
|
| 168 |
+
|
| 169 |
+
f.write("SUMMARY:\n")
|
| 170 |
+
f.write(f"- Total Questions: {turn_data['summary']['total_questions']}\n")
|
| 171 |
+
f.write(f"- Successful Answers: {turn_data['summary']['successful_answers']}\n")
|
| 172 |
+
f.write(f"- Success Rate: {turn_data['summary']['success_rate']:.1%}\n")
|
| 173 |
+
f.write(f"- Categories: {', '.join(turn_data['summary']['categories_covered'])}\n\n")
|
| 174 |
+
|
| 175 |
+
# Write detailed Q&A
|
| 176 |
+
results = turn_data['results']
|
| 177 |
+
for category_result in results['category_results']:
|
| 178 |
+
if category_result['results']:
|
| 179 |
+
f.write(f"\n{category_result['category'].upper()} CATEGORY:\n")
|
| 180 |
+
f.write("-" * 40 + "\n")
|
| 181 |
+
for i, result in enumerate(category_result['results'], 1):
|
| 182 |
+
if result['status'] == 'completed':
|
| 183 |
+
f.write(f"\nQ{i}: {result['question']['question']}\n")
|
| 184 |
+
f.write(f"Priority: {result['question']['priority']}/10\n")
|
| 185 |
+
f.write(f"A{i}: {result['answer']}\n")
|
| 186 |
+
f.write(f"Processing Time: {result['processing_time']:.2f}s\n")
|
| 187 |
+
f.write("-" * 40 + "\n")
|
| 188 |
+
|
| 189 |
+
self.logger.info(f"πΎ Turn {self.turn_count} results saved to {json_file} and {summary_file}")
|
| 190 |
+
|
| 191 |
+
# HELPER FUNCTIONS
|
| 192 |
+
|
| 193 |
+
def _get_user_topic(self) -> str:
|
| 194 |
+
"""Get research topic from user."""
|
| 195 |
+
while True:
|
| 196 |
+
topic = input(f"\nπ― Enter research topic (Turn {self.turn_count + 1}): ").strip()
|
| 197 |
+
if topic:
|
| 198 |
+
return topic
|
| 199 |
+
print("Please enter a valid research topic.")
|
| 200 |
+
|
| 201 |
+
def _get_max_questions(self) -> int:
|
| 202 |
+
"""Get maximum number of questions (default 2)."""
|
| 203 |
+
while True:
|
| 204 |
+
response = input("β Max questions (default 2): ").strip()
|
| 205 |
+
if not response:
|
| 206 |
+
return 2
|
| 207 |
+
try:
|
| 208 |
+
max_q = int(response)
|
| 209 |
+
if max_q > 0:
|
| 210 |
+
return max_q
|
| 211 |
+
print("Please enter a positive number.")
|
| 212 |
+
except ValueError:
|
| 213 |
+
print("Please enter a valid number.")
|
| 214 |
+
|
| 215 |
+
def _continue_conversation(self) -> bool:
|
| 216 |
+
"""Ask if user wants to continue the conversation."""
|
| 217 |
+
while True:
|
| 218 |
+
response = input("\nπ Continue exploring? (y/n, default y): ").strip().lower()
|
| 219 |
+
if not response or response == 'y':
|
| 220 |
+
return True
|
| 221 |
+
if response == 'n':
|
| 222 |
+
return False
|
| 223 |
+
print("Please enter 'y' or 'n'.")
|
| 224 |
+
|
| 225 |
+
def _serialize_results(self, results) -> Dict[str, Any]:
|
| 226 |
+
"""Convert results to JSON-serializable format."""
|
| 227 |
+
return {
|
| 228 |
+
"total_questions": results.total_questions,
|
| 229 |
+
"successful_answers": results.successful_answers,
|
| 230 |
+
"failed_questions": results.failed_questions,
|
| 231 |
+
"success_rate": results.success_rate,
|
| 232 |
+
"category_results": [
|
| 233 |
+
{
|
| 234 |
+
"category": cat_result.category.value,
|
| 235 |
+
"results": [
|
| 236 |
+
{
|
| 237 |
+
"question": {
|
| 238 |
+
"question": result.question.question,
|
| 239 |
+
"category": result.question.category.value,
|
| 240 |
+
"priority": result.question.priority,
|
| 241 |
+
"rationale": result.question.rationale
|
| 242 |
+
},
|
| 243 |
+
"answer": result.answer,
|
| 244 |
+
"status": result.status,
|
| 245 |
+
"processing_time": result.processing_time,
|
| 246 |
+
"error_message": result.error_message
|
| 247 |
+
} for result in cat_result.results
|
| 248 |
+
]
|
| 249 |
+
} for cat_result in results.category_results
|
| 250 |
+
],
|
| 251 |
+
"research_summary": results.research_summary
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
def _close_session(self):
|
| 255 |
+
"""Close the conversation session."""
|
| 256 |
+
self.logger.info(f"\nπ― Session {self.session_id} completed!")
|
| 257 |
+
self.logger.info(f"π Total turns: {self.turn_count}")
|
| 258 |
+
self.logger.info(f"πΎ All results saved to: {self.results_dir}")
|
| 259 |
+
|
| 260 |
+
print(f"\nπ Thank you for using Research Exploration!")
|
| 261 |
+
print(f"π Your results are saved in: {self.results_dir}")
|
| 262 |
+
print(f"π’ Total exploration turns: {self.turn_count}")
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
async def conversational_exploration():
|
| 266 |
+
"""Main function for conversational research exploration."""
|
| 267 |
+
explorer = ConversationalExplorer()
|
| 268 |
+
await explorer.start_conversation()
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
async def test_question_generation_only():
|
| 272 |
+
"""Test just the question generation component."""
|
| 273 |
+
|
| 274 |
+
logging.basicConfig(level=logging.INFO)
|
| 275 |
+
logger = logging.getLogger(__name__)
|
| 276 |
+
|
| 277 |
+
logger.info("\n" + "="*50)
|
| 278 |
+
logger.info("TEST: Question Generation Only")
|
| 279 |
+
logger.info("="*50)
|
| 280 |
+
|
| 281 |
+
from ..agents.question_generation_agent import QuestionGenerationAgent, QuestionGenerationRequest
|
| 282 |
+
|
| 283 |
+
try:
|
| 284 |
+
agent = QuestionGenerationAgent()
|
| 285 |
+
|
| 286 |
+
request = QuestionGenerationRequest(
|
| 287 |
+
topic="attention mechanisms in neural networks",
|
| 288 |
+
max_questions=3,
|
| 289 |
+
depth_level="comprehensive"
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
question_set = await agent.generate_research_questions(request)
|
| 293 |
+
|
| 294 |
+
logger.info(f"β
Generated {len(question_set.questions)} questions")
|
| 295 |
+
logger.info(f"β
Categories covered: {[cat.value for cat in question_set.categories_covered]}")
|
| 296 |
+
|
| 297 |
+
# Show questions by category
|
| 298 |
+
for category in question_set.categories_covered:
|
| 299 |
+
category_questions = question_set.get_questions_by_category(category)
|
| 300 |
+
logger.info(f"\nπ {category.value.upper()}:")
|
| 301 |
+
for q in category_questions:
|
| 302 |
+
priority_indicator = "π₯" if q.priority >= 8 else "π"
|
| 303 |
+
logger.info(f" {priority_indicator} [{q.priority}] {q.question}")
|
| 304 |
+
|
| 305 |
+
except Exception as e:
|
| 306 |
+
logger.error(f"β Question generation test failed: {e}")
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
if __name__ == "__main__":
|
| 310 |
+
|
| 311 |
+
# Choose which test to run
|
| 312 |
+
print("Research Exploration Engine Test Suite")
|
| 313 |
+
print("1. Conversational exploration (recommended)")
|
| 314 |
+
print("2. Test question generation only")
|
| 315 |
+
print("3. Legacy test suite")
|
| 316 |
+
|
| 317 |
+
choice = input("Choose test (1-3, default 1): ").strip()
|
| 318 |
+
|
| 319 |
+
if choice == "2":
|
| 320 |
+
asyncio.run(test_question_generation_only())
|
| 321 |
+
elif choice == "3":
|
| 322 |
+
print("Running legacy tests...")
|
| 323 |
+
asyncio.run(test_question_generation_only())
|
| 324 |
+
# Note: test_basic_exploration removed for conversational interface
|
| 325 |
+
print("Legacy basic exploration replaced with conversational mode")
|
| 326 |
+
else:
|
| 327 |
+
print("Starting conversational exploration...")
|
| 328 |
+
asyncio.run(conversational_exploration())
|
backend/agentic_system/orchestrators/utils/__init__.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utilities for research exploration orchestrator.
|
| 3 |
+
|
| 4 |
+
Contains modular utilities for logging, answer extraction, workflow processing,
|
| 5 |
+
and result organization to keep the main orchestrator clean and focused.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from .logging_utils import (
|
| 9 |
+
setup_exploration_logging,
|
| 10 |
+
log_exploration_phase,
|
| 11 |
+
log_exploration_result,
|
| 12 |
+
log_workflow_progress,
|
| 13 |
+
log_workflow_completion,
|
| 14 |
+
log_error
|
| 15 |
+
)
|
| 16 |
+
from .answer_extraction_utils import (
|
| 17 |
+
extract_answer_text,
|
| 18 |
+
extract_answer_summary_only,
|
| 19 |
+
format_detailed_answer_from_steps,
|
| 20 |
+
extract_confidence_score,
|
| 21 |
+
extract_context_sources,
|
| 22 |
+
is_valid_answer,
|
| 23 |
+
extract_answer_metadata
|
| 24 |
+
)
|
| 25 |
+
from .workflow_processing_utils import (
|
| 26 |
+
process_question_with_mix_mode,
|
| 27 |
+
process_question_with_custom_params,
|
| 28 |
+
get_enhanced_retrieval_params,
|
| 29 |
+
diagnose_workflow_failure,
|
| 30 |
+
retry_question_with_fallback_modes
|
| 31 |
+
)
|
| 32 |
+
from .result_organization_utils import (
|
| 33 |
+
organize_results_by_category,
|
| 34 |
+
generate_research_summary,
|
| 35 |
+
calculate_category_statistics,
|
| 36 |
+
identify_problematic_categories,
|
| 37 |
+
generate_failure_analysis
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
__all__ = [
|
| 41 |
+
# Logging utilities
|
| 42 |
+
'setup_exploration_logging',
|
| 43 |
+
'log_exploration_phase',
|
| 44 |
+
'log_exploration_result',
|
| 45 |
+
'log_workflow_progress',
|
| 46 |
+
'log_workflow_completion',
|
| 47 |
+
'log_error',
|
| 48 |
+
# Answer extraction utilities
|
| 49 |
+
'extract_answer_text',
|
| 50 |
+
'extract_answer_summary_only',
|
| 51 |
+
'format_detailed_answer_from_steps',
|
| 52 |
+
'extract_confidence_score',
|
| 53 |
+
'extract_context_sources',
|
| 54 |
+
'is_valid_answer',
|
| 55 |
+
'extract_answer_metadata',
|
| 56 |
+
# Workflow processing utilities
|
| 57 |
+
'process_question_with_mix_mode',
|
| 58 |
+
'process_question_with_custom_params',
|
| 59 |
+
'get_enhanced_retrieval_params',
|
| 60 |
+
'diagnose_workflow_failure',
|
| 61 |
+
'retry_question_with_fallback_modes',
|
| 62 |
+
# Result organization utilities
|
| 63 |
+
'organize_results_by_category',
|
| 64 |
+
'generate_research_summary',
|
| 65 |
+
'calculate_category_statistics',
|
| 66 |
+
'identify_problematic_categories',
|
| 67 |
+
'generate_failure_analysis'
|
| 68 |
+
]
|
backend/agentic_system/orchestrators/utils/answer_extraction_utils.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Answer extraction utilities for research exploration orchestrator.
|
| 3 |
+
|
| 4 |
+
Handles extraction of answer text and metadata from various answer object types.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Optional, Any
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def extract_answer_text(guided_answer: Any) -> str:
|
| 11 |
+
"""
|
| 12 |
+
Extract text from a GuidedAnswer object or other answer formats.
|
| 13 |
+
|
| 14 |
+
Prioritizes detailed step-by-step content over concise summaries for rich answers.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
guided_answer: GuidedAnswer object, string, or other answer format
|
| 18 |
+
|
| 19 |
+
Returns:
|
| 20 |
+
str: Extracted answer text, empty string if extraction fails
|
| 21 |
+
"""
|
| 22 |
+
if not guided_answer:
|
| 23 |
+
return ""
|
| 24 |
+
|
| 25 |
+
# Handle string answers directly
|
| 26 |
+
if isinstance(guided_answer, str):
|
| 27 |
+
return guided_answer
|
| 28 |
+
|
| 29 |
+
# Try to extract detailed step-by-step content first
|
| 30 |
+
if hasattr(guided_answer, 'steps') and guided_answer.steps:
|
| 31 |
+
return format_detailed_answer_from_steps(guided_answer)
|
| 32 |
+
|
| 33 |
+
# Try various common answer attributes (fallback to summary)
|
| 34 |
+
if hasattr(guided_answer, 'summary'):
|
| 35 |
+
return guided_answer.summary
|
| 36 |
+
elif hasattr(guided_answer, 'answer'):
|
| 37 |
+
return guided_answer.answer
|
| 38 |
+
elif hasattr(guided_answer, 'text'):
|
| 39 |
+
return guided_answer.text
|
| 40 |
+
elif hasattr(guided_answer, 'content'):
|
| 41 |
+
return guided_answer.content
|
| 42 |
+
else:
|
| 43 |
+
# Fallback to string conversion
|
| 44 |
+
return str(guided_answer)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def format_detailed_answer_from_steps(guided_answer: Any) -> str:
|
| 48 |
+
"""
|
| 49 |
+
Format a comprehensive answer from the detailed steps structure.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
guided_answer: GuidedAnswer object with steps attribute
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
str: Formatted detailed answer with all steps
|
| 56 |
+
"""
|
| 57 |
+
try:
|
| 58 |
+
# Start with summary if available
|
| 59 |
+
result = ""
|
| 60 |
+
if hasattr(guided_answer, 'summary') and guided_answer.summary:
|
| 61 |
+
result += f"## Summary\n{guided_answer.summary}\n\n"
|
| 62 |
+
|
| 63 |
+
# Add confidence and coverage info if available
|
| 64 |
+
metadata_parts = []
|
| 65 |
+
if hasattr(guided_answer, 'confidence_level'):
|
| 66 |
+
metadata_parts.append(f"**Confidence:** {guided_answer.confidence_level}")
|
| 67 |
+
if hasattr(guided_answer, 'context_coverage'):
|
| 68 |
+
metadata_parts.append(f"**Context Coverage:** {guided_answer.context_coverage}")
|
| 69 |
+
|
| 70 |
+
if metadata_parts:
|
| 71 |
+
result += f"*{' | '.join(metadata_parts)}*\n\n"
|
| 72 |
+
|
| 73 |
+
# Add detailed steps
|
| 74 |
+
result += "## Detailed Analysis\n\n"
|
| 75 |
+
|
| 76 |
+
for step in guided_answer.steps:
|
| 77 |
+
step_num = getattr(step, 'step_number', '')
|
| 78 |
+
title = getattr(step, 'title', f'Step {step_num}')
|
| 79 |
+
explanation = getattr(step, 'explanation', '')
|
| 80 |
+
|
| 81 |
+
result += f"### {step_num}. {title}\n\n"
|
| 82 |
+
result += f"{explanation}\n\n"
|
| 83 |
+
|
| 84 |
+
# Add context references if available
|
| 85 |
+
context_refs = getattr(step, 'context_references', None)
|
| 86 |
+
if context_refs and len(context_refs) > 0:
|
| 87 |
+
result += f"*Sources: {', '.join(context_refs)}*\n\n"
|
| 88 |
+
|
| 89 |
+
return result.strip()
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
# Fallback to summary if steps formatting fails
|
| 93 |
+
if hasattr(guided_answer, 'summary'):
|
| 94 |
+
return guided_answer.summary
|
| 95 |
+
return f"Error formatting detailed answer: {str(e)}"
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def extract_answer_summary_only(guided_answer: Any) -> str:
|
| 99 |
+
"""
|
| 100 |
+
Extract only the summary portion (for cases where brief answers are preferred).
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
guided_answer: GuidedAnswer object or other answer format
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
str: Summary text only
|
| 107 |
+
"""
|
| 108 |
+
if not guided_answer:
|
| 109 |
+
return ""
|
| 110 |
+
|
| 111 |
+
if isinstance(guided_answer, str):
|
| 112 |
+
return guided_answer
|
| 113 |
+
|
| 114 |
+
if hasattr(guided_answer, 'summary'):
|
| 115 |
+
return guided_answer.summary
|
| 116 |
+
elif hasattr(guided_answer, 'answer'):
|
| 117 |
+
return guided_answer.answer
|
| 118 |
+
else:
|
| 119 |
+
return str(guided_answer)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def extract_confidence_score(workflow_state: Any) -> Optional[float]:
|
| 123 |
+
"""
|
| 124 |
+
Extract confidence score from workflow state if available.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
workflow_state: Workflow state object
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
Optional[float]: Confidence score (0-1) or None if not available
|
| 131 |
+
"""
|
| 132 |
+
if not workflow_state:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
# Try various confidence score attributes
|
| 136 |
+
confidence_attrs = [
|
| 137 |
+
'confidence_score',
|
| 138 |
+
'confidence',
|
| 139 |
+
'score',
|
| 140 |
+
'certainty'
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
for attr in confidence_attrs:
|
| 144 |
+
if hasattr(workflow_state, attr):
|
| 145 |
+
value = getattr(workflow_state, attr)
|
| 146 |
+
if isinstance(value, (int, float)) and 0 <= value <= 1:
|
| 147 |
+
return float(value)
|
| 148 |
+
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def extract_context_sources(workflow_state: Any) -> list:
|
| 153 |
+
"""
|
| 154 |
+
Extract context sources from workflow state if available.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
workflow_state: Workflow state object
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
list: List of source identifiers, empty list if not available
|
| 161 |
+
"""
|
| 162 |
+
if not workflow_state:
|
| 163 |
+
return []
|
| 164 |
+
|
| 165 |
+
# Try various source attributes
|
| 166 |
+
source_attrs = [
|
| 167 |
+
'sources',
|
| 168 |
+
'context_sources',
|
| 169 |
+
'references',
|
| 170 |
+
'citations'
|
| 171 |
+
]
|
| 172 |
+
|
| 173 |
+
for attr in source_attrs:
|
| 174 |
+
if hasattr(workflow_state, attr):
|
| 175 |
+
value = getattr(workflow_state, attr)
|
| 176 |
+
if isinstance(value, list):
|
| 177 |
+
return value
|
| 178 |
+
|
| 179 |
+
return []
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def is_valid_answer(answer_text: str, min_length: int = 10) -> bool:
|
| 183 |
+
"""
|
| 184 |
+
Check if an extracted answer is valid and meaningful.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
answer_text: Extracted answer text
|
| 188 |
+
min_length: Minimum length for valid answer (default: 10)
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
bool: True if answer appears valid, False otherwise
|
| 192 |
+
"""
|
| 193 |
+
if not answer_text or not isinstance(answer_text, str):
|
| 194 |
+
return False
|
| 195 |
+
|
| 196 |
+
# Check minimum length
|
| 197 |
+
if len(answer_text.strip()) < min_length:
|
| 198 |
+
return False
|
| 199 |
+
|
| 200 |
+
# Check for common "no answer" patterns
|
| 201 |
+
no_answer_patterns = [
|
| 202 |
+
"no context available",
|
| 203 |
+
"unable to answer",
|
| 204 |
+
"cannot determine",
|
| 205 |
+
"not found",
|
| 206 |
+
"no information",
|
| 207 |
+
"context not provided"
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
answer_lower = answer_text.lower()
|
| 211 |
+
for pattern in no_answer_patterns:
|
| 212 |
+
if pattern in answer_lower:
|
| 213 |
+
return False
|
| 214 |
+
|
| 215 |
+
return True
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def extract_answer_metadata(workflow_state: Any) -> dict:
|
| 219 |
+
"""
|
| 220 |
+
Extract comprehensive metadata from workflow state.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
workflow_state: Workflow state object
|
| 224 |
+
|
| 225 |
+
Returns:
|
| 226 |
+
dict: Dictionary containing available metadata
|
| 227 |
+
"""
|
| 228 |
+
metadata = {}
|
| 229 |
+
|
| 230 |
+
if not workflow_state:
|
| 231 |
+
return metadata
|
| 232 |
+
|
| 233 |
+
# Extract various metadata fields
|
| 234 |
+
metadata_attrs = {
|
| 235 |
+
'confidence_score': extract_confidence_score(workflow_state),
|
| 236 |
+
'context_sources': extract_context_sources(workflow_state),
|
| 237 |
+
'status': getattr(workflow_state, 'status', None),
|
| 238 |
+
'error': getattr(workflow_state, 'error', None),
|
| 239 |
+
'processing_time': getattr(workflow_state, 'processing_time', None),
|
| 240 |
+
'retrieval_status': getattr(workflow_state, 'retrieval_status', None),
|
| 241 |
+
'context_length': getattr(workflow_state, 'context_length', None)
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
# Only include non-None values
|
| 245 |
+
return {k: v for k, v in metadata_attrs.items() if v is not None}
|
backend/agentic_system/orchestrators/utils/logging_utils.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Logging utilities for research exploration orchestrator.
|
| 3 |
+
|
| 4 |
+
Provides centralized logging setup and configuration for the exploration process.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
from typing import Optional
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def setup_exploration_logging(name: str, level: int = logging.DEBUG) -> logging.Logger:
|
| 12 |
+
"""
|
| 13 |
+
Set up structured logging for the research exploration orchestrator.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
name: Logger name (typically __name__ from calling module)
|
| 17 |
+
level: Logging level (default: DEBUG)
|
| 18 |
+
|
| 19 |
+
Returns:
|
| 20 |
+
logging.Logger: Configured logger instance
|
| 21 |
+
"""
|
| 22 |
+
logger = logging.getLogger(name)
|
| 23 |
+
|
| 24 |
+
# Only add handlers if none exist to avoid duplicates
|
| 25 |
+
if not logger.handlers:
|
| 26 |
+
handler = logging.StreamHandler()
|
| 27 |
+
formatter = logging.Formatter(
|
| 28 |
+
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 29 |
+
)
|
| 30 |
+
handler.setFormatter(formatter)
|
| 31 |
+
logger.addHandler(handler)
|
| 32 |
+
logger.setLevel(level)
|
| 33 |
+
|
| 34 |
+
return logger
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def log_exploration_phase(logger: logging.Logger, phase: int, description: str) -> None:
|
| 38 |
+
"""
|
| 39 |
+
Log the start of an exploration phase with consistent formatting.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
logger: Logger instance
|
| 43 |
+
phase: Phase number (1, 2, 3, etc.)
|
| 44 |
+
description: Description of the phase
|
| 45 |
+
"""
|
| 46 |
+
logger.info(f"π Phase {phase}: {description}")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def log_exploration_result(
|
| 50 |
+
logger: logging.Logger,
|
| 51 |
+
successful: int,
|
| 52 |
+
total: int,
|
| 53 |
+
context: Optional[str] = None
|
| 54 |
+
) -> None:
|
| 55 |
+
"""
|
| 56 |
+
Log exploration completion results with consistent formatting.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
logger: Logger instance
|
| 60 |
+
successful: Number of successful operations
|
| 61 |
+
total: Total number of operations
|
| 62 |
+
context: Optional context description
|
| 63 |
+
"""
|
| 64 |
+
context_str = f" {context}" if context else ""
|
| 65 |
+
logger.info(f"π― Research exploration complete{context_str}: {successful}/{total} questions answered successfully")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def log_workflow_progress(logger: logging.Logger, question: str, max_length: int = 50) -> None:
|
| 69 |
+
"""
|
| 70 |
+
Log workflow processing progress for individual questions.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
logger: Logger instance
|
| 74 |
+
question: Question being processed
|
| 75 |
+
max_length: Maximum length to display (default: 50)
|
| 76 |
+
"""
|
| 77 |
+
truncated_question = question[:max_length] + "..." if len(question) > max_length else question
|
| 78 |
+
logger.debug(f"π Processing question: {truncated_question}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def log_workflow_completion(
|
| 82 |
+
logger: logging.Logger,
|
| 83 |
+
status: str,
|
| 84 |
+
error: Optional[str] = None
|
| 85 |
+
) -> None:
|
| 86 |
+
"""
|
| 87 |
+
Log workflow completion status.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
logger: Logger instance
|
| 91 |
+
status: Workflow status
|
| 92 |
+
error: Error message if any
|
| 93 |
+
"""
|
| 94 |
+
error_str = f", Error: {error}" if error else ""
|
| 95 |
+
logger.debug(f"β
Workflow completed. Status: {status}{error_str}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def log_error(logger: logging.Logger, operation: str, error: Exception) -> None:
|
| 99 |
+
"""
|
| 100 |
+
Log errors with consistent formatting.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
logger: Logger instance
|
| 104 |
+
operation: Description of operation that failed
|
| 105 |
+
error: Exception that occurred
|
| 106 |
+
"""
|
| 107 |
+
logger.error(f"β {operation} failed: {error}")
|
backend/agentic_system/orchestrators/utils/result_organization_utils.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Result organization utilities for research exploration orchestrator.
|
| 3 |
+
|
| 4 |
+
Handles organization of question results by category and generation of research summaries.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
from typing import List, Optional, Any
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
|
| 11 |
+
from ..research_exploration_schema import CategoryResults, QuestionResult
|
| 12 |
+
from .answer_extraction_utils import extract_answer_text
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def organize_results_by_category(question_results: List[QuestionResult]) -> List[CategoryResults]:
|
| 16 |
+
"""
|
| 17 |
+
Organize question results by research category.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
question_results: List of individual question results
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
List[CategoryResults]: Results organized by category
|
| 24 |
+
"""
|
| 25 |
+
# Group results by category
|
| 26 |
+
category_groups = defaultdict(list)
|
| 27 |
+
for result in question_results:
|
| 28 |
+
category_groups[result.question.category].append(result)
|
| 29 |
+
|
| 30 |
+
# Create CategoryResults for each group
|
| 31 |
+
category_results = []
|
| 32 |
+
for category, results in category_groups.items():
|
| 33 |
+
successful = sum(1 for r in results if r.status == "completed")
|
| 34 |
+
|
| 35 |
+
category_result = CategoryResults(
|
| 36 |
+
category=category,
|
| 37 |
+
questions_processed=len(results),
|
| 38 |
+
successful_answers=successful,
|
| 39 |
+
results=results
|
| 40 |
+
)
|
| 41 |
+
category_results.append(category_result)
|
| 42 |
+
|
| 43 |
+
return category_results
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
async def generate_research_summary(
|
| 47 |
+
topic: str,
|
| 48 |
+
category_results: List[CategoryResults],
|
| 49 |
+
qa_workflow: Any,
|
| 50 |
+
logger: Optional[logging.Logger] = None
|
| 51 |
+
) -> Optional[str]:
|
| 52 |
+
"""
|
| 53 |
+
Generate an overall research summary from category results.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
topic: The research topic
|
| 57 |
+
category_results: Results organized by category
|
| 58 |
+
qa_workflow: QA workflow instance for summary generation
|
| 59 |
+
logger: Optional logger for debugging
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
Optional[str]: Research summary or None if generation fails
|
| 63 |
+
"""
|
| 64 |
+
try:
|
| 65 |
+
# Collect successful answers for summary generation
|
| 66 |
+
successful_answers = []
|
| 67 |
+
for cat_result in category_results:
|
| 68 |
+
for result in cat_result.results:
|
| 69 |
+
if result.status == "completed" and result.answer:
|
| 70 |
+
successful_answers.append({
|
| 71 |
+
'category': cat_result.category.value,
|
| 72 |
+
'question': result.question.question,
|
| 73 |
+
'answer': result.answer
|
| 74 |
+
})
|
| 75 |
+
|
| 76 |
+
if not successful_answers:
|
| 77 |
+
return "No successful answers to summarize."
|
| 78 |
+
|
| 79 |
+
# Create summary prompt and use QA workflow
|
| 80 |
+
summary_question = f"Based on the following Q&A about {topic}, provide a comprehensive research summary: {successful_answers}"
|
| 81 |
+
|
| 82 |
+
summary_state = await qa_workflow.process_question(summary_question)
|
| 83 |
+
|
| 84 |
+
# Extract text from GuidedAnswer object using helper
|
| 85 |
+
summary_text = extract_answer_text(summary_state.answer)
|
| 86 |
+
return summary_text if summary_text else "Unable to generate research summary."
|
| 87 |
+
|
| 88 |
+
except Exception as e:
|
| 89 |
+
if logger:
|
| 90 |
+
logger.warning(f"Failed to generate research summary: {e}")
|
| 91 |
+
return f"Summary generation failed: {e}"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def calculate_category_statistics(category_results: List[CategoryResults]) -> dict:
|
| 95 |
+
"""
|
| 96 |
+
Calculate comprehensive statistics across all categories.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
category_results: Results organized by category
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
dict: Statistics including success rates, timing, etc.
|
| 103 |
+
"""
|
| 104 |
+
stats = {
|
| 105 |
+
'total_categories': len(category_results),
|
| 106 |
+
'total_questions': 0,
|
| 107 |
+
'total_successful': 0,
|
| 108 |
+
'category_breakdown': [],
|
| 109 |
+
'success_rate_by_category': {},
|
| 110 |
+
'overall_success_rate': 0.0
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
for cat_result in category_results:
|
| 114 |
+
stats['total_questions'] += cat_result.questions_processed
|
| 115 |
+
stats['total_successful'] += cat_result.successful_answers
|
| 116 |
+
|
| 117 |
+
category_success_rate = (
|
| 118 |
+
cat_result.successful_answers / cat_result.questions_processed
|
| 119 |
+
if cat_result.questions_processed > 0 else 0.0
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
stats['category_breakdown'].append({
|
| 123 |
+
'category': cat_result.category.value,
|
| 124 |
+
'questions': cat_result.questions_processed,
|
| 125 |
+
'successful': cat_result.successful_answers,
|
| 126 |
+
'success_rate': category_success_rate
|
| 127 |
+
})
|
| 128 |
+
|
| 129 |
+
stats['success_rate_by_category'][cat_result.category.value] = category_success_rate
|
| 130 |
+
|
| 131 |
+
stats['overall_success_rate'] = (
|
| 132 |
+
stats['total_successful'] / stats['total_questions']
|
| 133 |
+
if stats['total_questions'] > 0 else 0.0
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
return stats
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def identify_problematic_categories(category_results: List[CategoryResults], threshold: float = 0.5) -> List[str]:
|
| 140 |
+
"""
|
| 141 |
+
Identify categories with success rates below threshold.
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
category_results: Results organized by category
|
| 145 |
+
threshold: Success rate threshold (default: 0.5)
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
List[str]: List of problematic category names
|
| 149 |
+
"""
|
| 150 |
+
problematic = []
|
| 151 |
+
|
| 152 |
+
for cat_result in category_results:
|
| 153 |
+
success_rate = (
|
| 154 |
+
cat_result.successful_answers / cat_result.questions_processed
|
| 155 |
+
if cat_result.questions_processed > 0 else 0.0
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
if success_rate < threshold:
|
| 159 |
+
problematic.append(cat_result.category.value)
|
| 160 |
+
|
| 161 |
+
return problematic
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def get_best_performing_answers(category_results: List[CategoryResults], top_n: int = 5) -> List[dict]:
|
| 165 |
+
"""
|
| 166 |
+
Get the best performing answers based on various criteria.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
category_results: Results organized by category
|
| 170 |
+
top_n: Number of top answers to return
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
List[dict]: Top performing answers with metadata
|
| 174 |
+
"""
|
| 175 |
+
all_successful = []
|
| 176 |
+
|
| 177 |
+
for cat_result in category_results:
|
| 178 |
+
for result in cat_result.results:
|
| 179 |
+
if result.status == "completed" and result.answer:
|
| 180 |
+
answer_info = {
|
| 181 |
+
'category': cat_result.category.value,
|
| 182 |
+
'question': result.question.question,
|
| 183 |
+
'answer': result.answer,
|
| 184 |
+
'priority': result.question.priority,
|
| 185 |
+
'confidence_score': result.confidence_score or 0.0,
|
| 186 |
+
'processing_time': result.processing_time or float('inf'),
|
| 187 |
+
'answer_length': len(result.answer)
|
| 188 |
+
}
|
| 189 |
+
all_successful.append(answer_info)
|
| 190 |
+
|
| 191 |
+
# Sort by priority (desc), confidence (desc), then processing time (asc)
|
| 192 |
+
all_successful.sort(
|
| 193 |
+
key=lambda x: (-x['priority'], -x['confidence_score'], x['processing_time'])
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
return all_successful[:top_n]
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def generate_failure_analysis(category_results: List[CategoryResults]) -> dict:
|
| 200 |
+
"""
|
| 201 |
+
Analyze failed questions to identify patterns.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
category_results: Results organized by category
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
dict: Analysis of failure patterns
|
| 208 |
+
"""
|
| 209 |
+
failure_analysis = {
|
| 210 |
+
'total_failures': 0,
|
| 211 |
+
'failure_reasons': defaultdict(int),
|
| 212 |
+
'failed_categories': defaultdict(int),
|
| 213 |
+
'common_patterns': []
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
for cat_result in category_results:
|
| 217 |
+
for result in cat_result.results:
|
| 218 |
+
if result.status == "failed":
|
| 219 |
+
failure_analysis['total_failures'] += 1
|
| 220 |
+
failure_analysis['failed_categories'][cat_result.category.value] += 1
|
| 221 |
+
|
| 222 |
+
if result.error_message:
|
| 223 |
+
# Categorize error messages
|
| 224 |
+
error_msg = result.error_message.lower()
|
| 225 |
+
if "no context" in error_msg:
|
| 226 |
+
failure_analysis['failure_reasons']['no_context'] += 1
|
| 227 |
+
elif "timeout" in error_msg:
|
| 228 |
+
failure_analysis['failure_reasons']['timeout'] += 1
|
| 229 |
+
elif "workflow error" in error_msg:
|
| 230 |
+
failure_analysis['failure_reasons']['workflow_error'] += 1
|
| 231 |
+
else:
|
| 232 |
+
failure_analysis['failure_reasons']['other'] += 1
|
| 233 |
+
|
| 234 |
+
# Identify common patterns
|
| 235 |
+
if failure_analysis['failure_reasons']['no_context'] > failure_analysis['total_failures'] * 0.5:
|
| 236 |
+
failure_analysis['common_patterns'].append('High retrieval failure rate - check knowledge base coverage')
|
| 237 |
+
|
| 238 |
+
if failure_analysis['failure_reasons']['timeout'] > failure_analysis['total_failures'] * 0.3:
|
| 239 |
+
failure_analysis['common_patterns'].append('Processing timeouts - consider increasing timeout limits')
|
| 240 |
+
|
| 241 |
+
return dict(failure_analysis)
|
backend/agentic_system/orchestrators/utils/workflow_processing_utils.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Workflow processing utilities for research exploration orchestrator.
|
| 3 |
+
|
| 4 |
+
Handles question processing through QA workflows with various modes and configurations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import time
|
| 8 |
+
import logging
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from typing import Any, Dict, Optional
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
async def process_question_with_mix_mode(
|
| 14 |
+
question: str,
|
| 15 |
+
qa_workflow: Any,
|
| 16 |
+
logger: Optional[logging.Logger] = None
|
| 17 |
+
) -> Any:
|
| 18 |
+
"""
|
| 19 |
+
Process a question through QA workflow with mix mode for comprehensive retrieval.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
question: The question to process
|
| 23 |
+
qa_workflow: QA workflow instance
|
| 24 |
+
logger: Optional logger for debugging
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
WorkflowState: The workflow state after processing
|
| 28 |
+
"""
|
| 29 |
+
try:
|
| 30 |
+
from ...graphs.state_schema import WorkflowState
|
| 31 |
+
|
| 32 |
+
# Create initial state with mix mode for better retrieval coverage
|
| 33 |
+
initial_state = WorkflowState(
|
| 34 |
+
question=question,
|
| 35 |
+
workflow_start_time=datetime.now(),
|
| 36 |
+
retrieval_params={
|
| 37 |
+
"mode": "mix", # Use mix mode for better context retrieval
|
| 38 |
+
"top_k": 10, # Increase top_k for more comprehensive retrieval
|
| 39 |
+
"chunk_top_k": 4 # Increase chunk_top_k for better context
|
| 40 |
+
}
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
if logger:
|
| 44 |
+
logger.debug(f"π§ Using retrieval params: {initial_state.retrieval_params}")
|
| 45 |
+
|
| 46 |
+
# Run the workflow with our custom initial state
|
| 47 |
+
config = {"configurable": {"thread_id": f"research_{int(time.time())}"}}
|
| 48 |
+
result = await qa_workflow.app.ainvoke(initial_state.dict(), config)
|
| 49 |
+
|
| 50 |
+
return WorkflowState(**result)
|
| 51 |
+
|
| 52 |
+
except Exception as e:
|
| 53 |
+
if logger:
|
| 54 |
+
logger.error(f"Error in process_question_with_mix_mode: {e}")
|
| 55 |
+
|
| 56 |
+
# Return error state similar to normal QA workflow
|
| 57 |
+
from ...graphs.state_schema import WorkflowState
|
| 58 |
+
|
| 59 |
+
return WorkflowState(
|
| 60 |
+
question=question,
|
| 61 |
+
error=f"Mix mode workflow error: {str(e)}",
|
| 62 |
+
status="error",
|
| 63 |
+
workflow_start_time=datetime.now(),
|
| 64 |
+
workflow_end_time=datetime.now()
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
async def process_question_with_custom_params(
|
| 69 |
+
question: str,
|
| 70 |
+
qa_workflow: Any,
|
| 71 |
+
retrieval_params: Dict[str, Any],
|
| 72 |
+
logger: Optional[logging.Logger] = None
|
| 73 |
+
) -> Any:
|
| 74 |
+
"""
|
| 75 |
+
Process a question with custom retrieval parameters.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
question: The question to process
|
| 79 |
+
qa_workflow: QA workflow instance
|
| 80 |
+
retrieval_params: Custom retrieval parameters
|
| 81 |
+
logger: Optional logger for debugging
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
WorkflowState: The workflow state after processing
|
| 85 |
+
"""
|
| 86 |
+
try:
|
| 87 |
+
from ...graphs.state_schema import WorkflowState
|
| 88 |
+
|
| 89 |
+
# Create initial state with custom parameters
|
| 90 |
+
initial_state = WorkflowState(
|
| 91 |
+
question=question,
|
| 92 |
+
workflow_start_time=datetime.now(),
|
| 93 |
+
retrieval_params=retrieval_params
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
if logger:
|
| 97 |
+
logger.debug(f"π§ Using custom retrieval params: {retrieval_params}")
|
| 98 |
+
|
| 99 |
+
# Run the workflow
|
| 100 |
+
config = {"configurable": {"thread_id": f"research_{int(time.time())}"}}
|
| 101 |
+
result = await qa_workflow.app.ainvoke(initial_state.dict(), config)
|
| 102 |
+
|
| 103 |
+
return WorkflowState(**result)
|
| 104 |
+
|
| 105 |
+
except Exception as e:
|
| 106 |
+
if logger:
|
| 107 |
+
logger.error(f"Error in process_question_with_custom_params: {e}")
|
| 108 |
+
|
| 109 |
+
from ...graphs.state_schema import WorkflowState
|
| 110 |
+
|
| 111 |
+
return WorkflowState(
|
| 112 |
+
question=question,
|
| 113 |
+
error=f"Custom params workflow error: {str(e)}",
|
| 114 |
+
status="error",
|
| 115 |
+
workflow_start_time=datetime.now(),
|
| 116 |
+
workflow_end_time=datetime.now()
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def get_enhanced_retrieval_params(mode: str = "mix") -> Dict[str, Any]:
|
| 121 |
+
"""
|
| 122 |
+
Get enhanced retrieval parameters for better context coverage.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
mode: Retrieval mode (default: "mix")
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
Dict[str, Any]: Enhanced retrieval parameters
|
| 129 |
+
"""
|
| 130 |
+
base_params = {
|
| 131 |
+
"top_k": 10, # More documents
|
| 132 |
+
"chunk_top_k": 4, # More chunks per document
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
if mode == "mix":
|
| 136 |
+
base_params.update({
|
| 137 |
+
"mode": "mix",
|
| 138 |
+
"top_k": 15, # Even more for mix mode
|
| 139 |
+
"chunk_top_k": 5
|
| 140 |
+
})
|
| 141 |
+
elif mode == "hybrid":
|
| 142 |
+
base_params.update({
|
| 143 |
+
"mode": "hybrid",
|
| 144 |
+
"top_k": 12,
|
| 145 |
+
"chunk_top_k": 4
|
| 146 |
+
})
|
| 147 |
+
elif mode == "global":
|
| 148 |
+
base_params.update({
|
| 149 |
+
"mode": "global",
|
| 150 |
+
"top_k": 8,
|
| 151 |
+
"chunk_top_k": 3
|
| 152 |
+
})
|
| 153 |
+
elif mode == "local":
|
| 154 |
+
base_params.update({
|
| 155 |
+
"mode": "local",
|
| 156 |
+
"top_k": 20, # Compensate with more local results
|
| 157 |
+
"chunk_top_k": 6
|
| 158 |
+
})
|
| 159 |
+
else:
|
| 160 |
+
base_params["mode"] = mode
|
| 161 |
+
|
| 162 |
+
return base_params
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def diagnose_workflow_failure(workflow_state: Any, logger: Optional[logging.Logger] = None) -> str:
|
| 166 |
+
"""
|
| 167 |
+
Diagnose why a workflow failed and provide insights.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
workflow_state: Failed workflow state
|
| 171 |
+
logger: Optional logger for additional debugging
|
| 172 |
+
|
| 173 |
+
Returns:
|
| 174 |
+
str: Diagnostic message explaining the failure
|
| 175 |
+
"""
|
| 176 |
+
if not workflow_state:
|
| 177 |
+
return "Workflow state is None - possible initialization failure"
|
| 178 |
+
|
| 179 |
+
# Check for common failure patterns
|
| 180 |
+
error = getattr(workflow_state, 'error', None)
|
| 181 |
+
status = getattr(workflow_state, 'status', None)
|
| 182 |
+
|
| 183 |
+
if error:
|
| 184 |
+
if "No context available" in str(error):
|
| 185 |
+
diagnosis = "Retrieval failure: No context found in knowledge base"
|
| 186 |
+
if logger:
|
| 187 |
+
logger.warning(f"π Diagnosis: {diagnosis}")
|
| 188 |
+
logger.warning(f"π Suggestion: Try different retrieval mode or check question relevance")
|
| 189 |
+
return diagnosis
|
| 190 |
+
elif "timeout" in str(error).lower():
|
| 191 |
+
return "Processing timeout: Question took too long to process"
|
| 192 |
+
elif "workflow error" in str(error).lower():
|
| 193 |
+
return f"Workflow execution error: {error}"
|
| 194 |
+
|
| 195 |
+
if status == "error":
|
| 196 |
+
return "Workflow completed with error status"
|
| 197 |
+
elif status == "initialized":
|
| 198 |
+
return "Workflow stuck in initialized state - possible processing failure"
|
| 199 |
+
|
| 200 |
+
return f"Unknown failure: Status={status}, Error={error}"
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
async def retry_question_with_fallback_modes(
|
| 204 |
+
question: str,
|
| 205 |
+
qa_workflow: Any,
|
| 206 |
+
logger: Optional[logging.Logger] = None
|
| 207 |
+
) -> Any:
|
| 208 |
+
"""
|
| 209 |
+
Retry a question with different retrieval modes as fallbacks.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
question: The question to process
|
| 213 |
+
qa_workflow: QA workflow instance
|
| 214 |
+
logger: Optional logger for debugging
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
WorkflowState: Best result from attempted modes
|
| 218 |
+
"""
|
| 219 |
+
fallback_modes = ["mix", "hybrid", "global", "local"]
|
| 220 |
+
|
| 221 |
+
for mode in fallback_modes:
|
| 222 |
+
if logger:
|
| 223 |
+
logger.debug(f"π Trying mode: {mode}")
|
| 224 |
+
|
| 225 |
+
params = get_enhanced_retrieval_params(mode)
|
| 226 |
+
result = await process_question_with_custom_params(
|
| 227 |
+
question, qa_workflow, params, logger
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
# Check if this attempt was successful
|
| 231 |
+
if not getattr(result, 'error', None) and getattr(result, 'status', None) == "completed":
|
| 232 |
+
if logger:
|
| 233 |
+
logger.info(f"β
Success with mode: {mode}")
|
| 234 |
+
return result
|
| 235 |
+
|
| 236 |
+
# If all modes failed, return the last result
|
| 237 |
+
if logger:
|
| 238 |
+
logger.warning(f"β All retrieval modes failed for question: {question[:50]}...")
|
| 239 |
+
|
| 240 |
+
return result
|