From a140f744a3a7933e247f4dcb1d54fbb79a41b4ee Mon Sep 17 00:00:00 2001 From: 90houlaoheshang <907333918@qq.com> Date: Tue, 5 Nov 2024 17:22:04 +0800 Subject: [PATCH] =?UTF-8?q?refactor(lightrag):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8A=E4=BC=A0=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除 InsertFileRequest 模型,改用 FastAPI 的 File 和 UploadFile - 修改 insert_file 函数,以适应新的文件上传方式 - 更新函数参数和逻辑,支持直接上传文件 - 优化错误处理和响应消息 --- .../lightrag_api_openai_compatible_demo.py | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/examples/lightrag_api_openai_compatible_demo.py b/examples/lightrag_api_openai_compatible_demo.py index 8a7286b7..94475199 100644 --- a/examples/lightrag_api_openai_compatible_demo.py +++ b/examples/lightrag_api_openai_compatible_demo.py @@ -1,4 +1,4 @@ -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, File, UploadFile from pydantic import BaseModel import os from lightrag import LightRAG, QueryParam @@ -78,10 +78,6 @@ class InsertRequest(BaseModel): text: str -class InsertFileRequest(BaseModel): - file_path: str - - class Response(BaseModel): status: str data: Optional[str] = None @@ -115,30 +111,22 @@ async def insert_endpoint(request: InsertRequest): @app.post("/insert_file", response_model=Response) -async def insert_file(request: InsertFileRequest): +async def insert_file(file: UploadFile = File(...)): try: - # Check if file exists - if not os.path.exists(request.file_path): - raise HTTPException( - status_code=404, detail=f"File not found: {request.file_path}" - ) - + file_content = await file.read() # Read file content try: - with open(request.file_path, "r", encoding="utf-8") as f: - content = f.read() + content = file_content.decode("utf-8") except UnicodeDecodeError: # If UTF-8 decoding fails, try other encodings - with open(request.file_path, "r", encoding="gbk") as f: - content = f.read() - + content = file_content.decode("gbk") # Insert file content loop = asyncio.get_event_loop() await loop.run_in_executor(None, lambda: rag.insert(content)) return Response( status="success", - message=f"File content from {request.file_path} inserted successfully", + message=f"File content from {file.filename} inserted successfully", ) except Exception as e: raise HTTPException(status_code=500, detail=str(e))