Spaces:
Running
Running
Create tools/rag_server.py
Browse files- tools/rag_server.py +53 -0
tools/rag_server.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from agent.rag_engine import RAGEngine
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
_rag_engine = None
|
| 6 |
+
|
| 7 |
+
def get_rag_engine():
|
| 8 |
+
global _rag_engine
|
| 9 |
+
if _rag_engine is None:
|
| 10 |
+
_rag_engine = RAGEngine()
|
| 11 |
+
return _rag_engine
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
async def search_documents(query: str, k: int = 5) -> dict:
|
| 15 |
+
"""
|
| 16 |
+
Search documents using RAG
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
query: Search query
|
| 20 |
+
k: Number of results
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
Dict with search results
|
| 24 |
+
"""
|
| 25 |
+
try:
|
| 26 |
+
rag = get_rag_engine()
|
| 27 |
+
results = await rag.search(query, k=k)
|
| 28 |
+
|
| 29 |
+
return {
|
| 30 |
+
'success': True,
|
| 31 |
+
'query': query,
|
| 32 |
+
'results': results,
|
| 33 |
+
'count': len(results)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
except Exception as e:
|
| 37 |
+
return {'error': str(e), 'success': False}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
async def add_document_to_rag(text: str, metadata: dict) -> dict:
|
| 41 |
+
"""Add document to RAG index"""
|
| 42 |
+
try:
|
| 43 |
+
rag = get_rag_engine()
|
| 44 |
+
doc_id = await rag.add_document(text, metadata)
|
| 45 |
+
|
| 46 |
+
return {
|
| 47 |
+
'success': True,
|
| 48 |
+
'document_id': doc_id,
|
| 49 |
+
'text_length': len(text)
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
except Exception as e:
|
| 53 |
+
return {'error': str(e), 'success': False}
|