|
| 1 | +from fastapi import FastAPI, HTTPException, File, UploadFile |
| 2 | +from pydantic import BaseModel |
| 3 | +import os |
| 4 | +from lightrag import LightRAG, QueryParam |
| 5 | +from lightrag.llm import ollama_embedding, ollama_model_complete |
| 6 | +from lightrag.utils import EmbeddingFunc |
| 7 | +from typing import Optional |
| 8 | +import asyncio |
| 9 | +import nest_asyncio |
| 10 | +import aiofiles |
| 11 | + |
| 12 | +# Apply nest_asyncio to solve event loop issues |
| 13 | +nest_asyncio.apply() |
| 14 | + |
| 15 | +DEFAULT_RAG_DIR = "index_default" |
| 16 | +app = FastAPI(title="LightRAG API", description="API for RAG operations") |
| 17 | + |
| 18 | +DEFAULT_INPUT_FILE = "book.txt" |
| 19 | +INPUT_FILE = os.environ.get("INPUT_FILE", f"{DEFAULT_INPUT_FILE}") |
| 20 | +print(f"INPUT_FILE: {INPUT_FILE}") |
| 21 | + |
| 22 | +# Configure working directory |
| 23 | +WORKING_DIR = os.environ.get("RAG_DIR", f"{DEFAULT_RAG_DIR}") |
| 24 | +print(f"WORKING_DIR: {WORKING_DIR}") |
| 25 | + |
| 26 | + |
| 27 | +if not os.path.exists(WORKING_DIR): |
| 28 | + os.mkdir(WORKING_DIR) |
| 29 | + |
| 30 | + |
| 31 | +rag = LightRAG( |
| 32 | + working_dir=WORKING_DIR, |
| 33 | + llm_model_func=ollama_model_complete, |
| 34 | + llm_model_name="gemma2:9b", |
| 35 | + llm_model_max_async=4, |
| 36 | + llm_model_max_token_size=8192, |
| 37 | + llm_model_kwargs={"host": "http://localhost:11434", "options": {"num_ctx": 8192}}, |
| 38 | + embedding_func=EmbeddingFunc( |
| 39 | + embedding_dim=768, |
| 40 | + max_token_size=8192, |
| 41 | + func=lambda texts: ollama_embedding( |
| 42 | + texts, embed_model="nomic-embed-text", host="http://localhost:11434" |
| 43 | + ), |
| 44 | + ), |
| 45 | +) |
| 46 | + |
| 47 | + |
| 48 | +# Data models |
| 49 | +class QueryRequest(BaseModel): |
| 50 | + query: str |
| 51 | + mode: str = "hybrid" |
| 52 | + only_need_context: bool = False |
| 53 | + |
| 54 | + |
| 55 | +class InsertRequest(BaseModel): |
| 56 | + text: str |
| 57 | + |
| 58 | + |
| 59 | +class Response(BaseModel): |
| 60 | + status: str |
| 61 | + data: Optional[str] = None |
| 62 | + message: Optional[str] = None |
| 63 | + |
| 64 | + |
| 65 | +# API routes |
| 66 | +@app.post("/query", response_model=Response) |
| 67 | +async def query_endpoint(request: QueryRequest): |
| 68 | + try: |
| 69 | + loop = asyncio.get_event_loop() |
| 70 | + result = await loop.run_in_executor( |
| 71 | + None, |
| 72 | + lambda: rag.query( |
| 73 | + request.query, |
| 74 | + param=QueryParam( |
| 75 | + mode=request.mode, only_need_context=request.only_need_context |
| 76 | + ), |
| 77 | + ), |
| 78 | + ) |
| 79 | + return Response(status="success", data=result) |
| 80 | + except Exception as e: |
| 81 | + raise HTTPException(status_code=500, detail=str(e)) |
| 82 | + |
| 83 | + |
| 84 | +# insert by text |
| 85 | +@app.post("/insert", response_model=Response) |
| 86 | +async def insert_endpoint(request: InsertRequest): |
| 87 | + try: |
| 88 | + loop = asyncio.get_event_loop() |
| 89 | + await loop.run_in_executor(None, lambda: rag.insert(request.text)) |
| 90 | + return Response(status="success", message="Text inserted successfully") |
| 91 | + except Exception as e: |
| 92 | + raise HTTPException(status_code=500, detail=str(e)) |
| 93 | + |
| 94 | + |
| 95 | +# insert by file in payload |
| 96 | +@app.post("/insert_file", response_model=Response) |
| 97 | +async def insert_file(file: UploadFile = File(...)): |
| 98 | + try: |
| 99 | + file_content = await file.read() |
| 100 | + # Read file content |
| 101 | + try: |
| 102 | + content = file_content.decode("utf-8") |
| 103 | + except UnicodeDecodeError: |
| 104 | + # If UTF-8 decoding fails, try other encodings |
| 105 | + content = file_content.decode("gbk") |
| 106 | + # Insert file content |
| 107 | + loop = asyncio.get_event_loop() |
| 108 | + await loop.run_in_executor(None, lambda: rag.insert(content)) |
| 109 | + |
| 110 | + return Response( |
| 111 | + status="success", |
| 112 | + message=f"File content from {file.filename} inserted successfully", |
| 113 | + ) |
| 114 | + except Exception as e: |
| 115 | + raise HTTPException(status_code=500, detail=str(e)) |
| 116 | + |
| 117 | + |
| 118 | +# insert by local default file |
| 119 | +@app.post("/insert_default_file", response_model=Response) |
| 120 | +@app.get("/insert_default_file", response_model=Response) |
| 121 | +async def insert_default_file(): |
| 122 | + try: |
| 123 | + # Read file content from book.txt |
| 124 | + async with aiofiles.open(INPUT_FILE, "r", encoding="utf-8") as file: |
| 125 | + content = await file.read() |
| 126 | + print(f"read input file {INPUT_FILE} successfully") |
| 127 | + # Insert file content |
| 128 | + loop = asyncio.get_event_loop() |
| 129 | + await loop.run_in_executor(None, lambda: rag.insert(content)) |
| 130 | + |
| 131 | + return Response( |
| 132 | + status="success", |
| 133 | + message=f"File content from {INPUT_FILE} inserted successfully", |
| 134 | + ) |
| 135 | + except Exception as e: |
| 136 | + raise HTTPException(status_code=500, detail=str(e)) |
| 137 | + |
| 138 | + |
| 139 | +@app.get("/health") |
| 140 | +async def health_check(): |
| 141 | + return {"status": "healthy"} |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + import uvicorn |
| 146 | + |
| 147 | + uvicorn.run(app, host="0.0.0.0", port=8020) |
| 148 | + |
| 149 | +# Usage example |
| 150 | +# To run the server, use the following command in your terminal: |
| 151 | +# python lightrag_api_openai_compatible_demo.py |
| 152 | + |
| 153 | +# Example requests: |
| 154 | +# 1. Query: |
| 155 | +# curl -X POST "http://127.0.0.1:8020/query" -H "Content-Type: application/json" -d '{"query": "your query here", "mode": "hybrid"}' |
| 156 | + |
| 157 | +# 2. Insert text: |
| 158 | +# curl -X POST "http://127.0.0.1:8020/insert" -H "Content-Type: application/json" -d '{"text": "your text here"}' |
| 159 | + |
| 160 | +# 3. Insert file: |
| 161 | +# curl -X POST "http://127.0.0.1:8020/insert_file" -H "Content-Type: application/json" -d '{"file_path": "path/to/your/file.txt"}' |
| 162 | + |
| 163 | +# 4. Health check: |
| 164 | +# curl -X GET "http://127.0.0.1:8020/health" |
0 commit comments