antas commited on
Commit
d73a3fd
·
1 Parent(s): c3f4554

refactor(lightrag): 优化文件上传接口

Browse files

- 移除 InsertFileRequest 模型,改用 FastAPI 的 File 和 UploadFile
- 修改 insert_file 函数,以适应新的文件上传方式
- 更新函数参数和逻辑,支持直接上传文件
- 优化错误处理和响应消息

examples/lightrag_api_openai_compatible_demo.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import FastAPI, HTTPException
2
  from pydantic import BaseModel
3
  import os
4
  from lightrag import LightRAG, QueryParam
@@ -78,10 +78,6 @@ class InsertRequest(BaseModel):
78
  text: str
79
 
80
 
81
- class InsertFileRequest(BaseModel):
82
- file_path: str
83
-
84
-
85
  class Response(BaseModel):
86
  status: str
87
  data: Optional[str] = None
@@ -115,30 +111,22 @@ async def insert_endpoint(request: InsertRequest):
115
 
116
 
117
  @app.post("/insert_file", response_model=Response)
118
- async def insert_file(request: InsertFileRequest):
119
  try:
120
- # Check if file exists
121
- if not os.path.exists(request.file_path):
122
- raise HTTPException(
123
- status_code=404, detail=f"File not found: {request.file_path}"
124
- )
125
-
126
  # Read file content
127
  try:
128
- with open(request.file_path, "r", encoding="utf-8") as f:
129
- content = f.read()
130
  except UnicodeDecodeError:
131
  # If UTF-8 decoding fails, try other encodings
132
- with open(request.file_path, "r", encoding="gbk") as f:
133
- content = f.read()
134
-
135
  # Insert file content
136
  loop = asyncio.get_event_loop()
137
  await loop.run_in_executor(None, lambda: rag.insert(content))
138
 
139
  return Response(
140
  status="success",
141
- message=f"File content from {request.file_path} inserted successfully",
142
  )
143
  except Exception as e:
144
  raise HTTPException(status_code=500, detail=str(e))
 
1
+ from fastapi import FastAPI, HTTPException, File, UploadFile
2
  from pydantic import BaseModel
3
  import os
4
  from lightrag import LightRAG, QueryParam
 
78
  text: str
79
 
80
 
 
 
 
 
81
  class Response(BaseModel):
82
  status: str
83
  data: Optional[str] = None
 
111
 
112
 
113
  @app.post("/insert_file", response_model=Response)
114
+ async def insert_file(file: UploadFile = File(...)):
115
  try:
116
+ file_content = await file.read()
 
 
 
 
 
117
  # Read file content
118
  try:
119
+ content = file_content.decode("utf-8")
 
120
  except UnicodeDecodeError:
121
  # If UTF-8 decoding fails, try other encodings
122
+ content = file_content.decode("gbk")
 
 
123
  # Insert file content
124
  loop = asyncio.get_event_loop()
125
  await loop.run_in_executor(None, lambda: rag.insert(content))
126
 
127
  return Response(
128
  status="success",
129
+ message=f"File content from {file.filename} inserted successfully",
130
  )
131
  except Exception as e:
132
  raise HTTPException(status_code=500, detail=str(e))