File size: 8,550 Bytes
73fd1fc
aa63765
73fd1fc
c16e1c9
73fd1fc
 
 
 
 
 
 
c16e1c9
 
 
 
 
aa63765
73fd1fc
aa63765
 
 
73fd1fc
 
 
 
 
 
 
 
 
aa63765
 
 
 
 
c16e1c9
aa63765
c16e1c9
 
 
 
 
 
 
 
 
 
aa63765
c16e1c9
 
aa63765
c16e1c9
 
 
 
aa63765
 
 
 
 
 
 
 
73fd1fc
aa63765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73fd1fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa63765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345b8ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e44e5dd
 
 
 
 
 
345b8ff
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from fastapi import APIRouter, Header, HTTPException, UploadFile, File, Form
from pydantic import BaseModel
from typing import Optional, Dict, Any
from api.mcp_clients.rag_client import RAGClient
from api.services.document_ingestion import (
    prepare_ingestion_payload,
    process_ingestion,
    detect_source_type,
    normalize_text,
    extract_text_from_file_bytes
)

router = APIRouter()
rag_client = RAGClient()


class IngestRequest(BaseModel):
    """Legacy simple ingestion request"""
    content: str


class DocumentIngestRequest(BaseModel):
    """Enhanced ingestion request matching the system prompt specification"""
    action: str = "ingest_document"
    tenant_id: Optional[str] = None  # Can come from header
    source_type: Optional[str] = None  # pdf | docx | txt | url | raw_text | markdown
    content: str
    metadata: Optional[Dict[str, Any]] = None


class SearchRequest(BaseModel):
    query: str


@router.post("/search")
async def rag_search(
    req: SearchRequest,
    x_tenant_id: str = Header(None)
):
    """
    Search tenant knowledge base using the RAG MCP server.
    """

    if not x_tenant_id:
        raise HTTPException(status_code=400, detail="Missing tenant ID")

    try:
        results = await rag_client.search(req.query, x_tenant_id)
        return {
            "tenant_id": x_tenant_id,
            "query": req.query,
            "results": results
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/ingest")
async def rag_ingest(
    req: IngestRequest,
    x_tenant_id: str = Header(None)
):
    """
    Legacy ingestion endpoint - simple content ingestion.
    Ingest content into tenant knowledge base using the RAG MCP server.
    """

    if not x_tenant_id:
        raise HTTPException(status_code=400, detail="Missing tenant ID")

    try:
        result = await rag_client.ingest(req.content, x_tenant_id)
        return {
            "tenant_id": x_tenant_id,
            "status": "ok",
            **result
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/ingest-document")
async def rag_ingest_document(
    req: DocumentIngestRequest,
    x_tenant_id: Optional[str] = Header(None)
):
    """
    Enhanced document ingestion endpoint matching the system prompt specification.
    
    Supports:
    - PDF, DOCX, TXT, Markdown files
    - URLs (fetches content automatically)
    - Raw text
    - Metadata (filename, url, doc_id)
    
    Expected payload:
    {
        "action": "ingest_document",
        "tenant_id": "...",
        "source_type": "pdf | docx | txt | url | raw_text",
        "content": "...",
        "metadata": {
            "filename": "...",
            "url": "...",
            "doc_id": "..."
        }
    }
    """
    # Use tenant_id from header if not in body (for backward compatibility)
    tenant_id = req.tenant_id or x_tenant_id
    if not tenant_id:
        raise HTTPException(status_code=400, detail="Missing tenant ID")

    try:
        # Prepare ingestion payload (async for URL fetching)
        payload = await prepare_ingestion_payload(
            tenant_id=tenant_id,
            content=req.content,
            source_type=req.source_type,
            filename=req.metadata.get("filename") if req.metadata else None,
            url=req.metadata.get("url") if req.metadata else None,
            doc_id=req.metadata.get("doc_id") if req.metadata else None,
            metadata=req.metadata
        )
        
        # Process ingestion
        result = await process_ingestion(payload, rag_client)
        
        return {
            "status": "ok",
            "message": f"Document ingested successfully. {result.get('chunks_stored', 0)} chunk(s) stored.",
            **result
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/ingest-file")
async def rag_ingest_file(
    file: UploadFile = File(...),
    x_tenant_id: Optional[str] = Header(None),
    tenant_id: Optional[str] = Form(None)
):
    """
    File upload endpoint for binary files (PDF, DOCX, TXT, MD).
    Extracts text server-side and ingests into knowledge base.
    
    Usage:
        POST /rag/ingest-file
        Headers:
            x-tenant-id: <tenant_id>
        Form Data:
            file: <binary file>
            tenant_id: <optional, can use header instead>
    """
    # Use tenant_id from form or header
    tenant_id_value = tenant_id or x_tenant_id
    if not tenant_id_value:
        raise HTTPException(status_code=400, detail="Missing tenant ID")

    try:
        # Read file bytes
        file_bytes = await file.read()
        if not file_bytes:
            raise HTTPException(status_code=400, detail="File is empty")

        # Extract text from binary file
        try:
            extracted_text = extract_text_from_file_bytes(file_bytes, file.filename or "unknown")
        except ValueError as e:
            raise HTTPException(status_code=400, detail=str(e))

        if not extracted_text or not extracted_text.strip():
            raise HTTPException(status_code=400, detail="No text could be extracted from file")

        # Prepare ingestion payload
        payload = await prepare_ingestion_payload(
            tenant_id=tenant_id_value,
            content=extracted_text,
            source_type=None,  # Auto-detect from filename
            filename=file.filename,
            url=None,
            doc_id=None,
            metadata=None
        )
        
        # Process ingestion
        result = await process_ingestion(payload, rag_client)
        
        return {
            "status": "ok",
            "message": f"File '{file.filename}' ingested successfully. {result.get('chunks_stored', 0)} chunk(s) stored.",
            **result
        }
    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/list")
async def rag_list(
    limit: int = 1000,
    offset: int = 0,
    x_tenant_id: str = Header(None)
):
    """
    List all documents in tenant knowledge base.
    """

    if not x_tenant_id:
        raise HTTPException(status_code=400, detail="Missing tenant ID")

    try:
        result = await rag_client.list_documents(x_tenant_id, limit=limit, offset=offset)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/delete/{document_id}")
async def rag_delete(
    document_id: int,
    x_tenant_id: str = Header(None)
):
    """
    Delete a specific document by ID from tenant knowledge base.
    """
    if not x_tenant_id:
        raise HTTPException(status_code=400, detail="Missing tenant ID")

    try:
        result = await rag_client.delete_document(x_tenant_id, document_id)
        if "error" in result:
            # Check if it's a connection error (500) or not found (404)
            error_msg = result["error"]
            if "Cannot connect" in error_msg:
                raise HTTPException(status_code=503, detail=error_msg)
            elif "not found" in error_msg.lower() or "access denied" in error_msg.lower():
                raise HTTPException(status_code=404, detail=error_msg)
            else:
                raise HTTPException(status_code=500, detail=error_msg)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/delete-all")
async def rag_delete_all(
    x_tenant_id: str = Header(None)
):
    """
    Delete all documents for a tenant.
    """
    if not x_tenant_id:
        raise HTTPException(status_code=400, detail="Missing tenant ID")

    try:
        result = await rag_client.delete_all_documents(x_tenant_id)
        if "error" in result:
            error_msg = result["error"]
            # Check if it's a connection error (503) or other error
            if "Cannot connect" in error_msg:
                raise HTTPException(status_code=503, detail=error_msg)
            else:
                raise HTTPException(status_code=500, detail=error_msg)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))