Restore 0.1.5 version from stash
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Dict, Optional
|
||||
|
||||
from app.services.supabase_rest import supabase_rest
|
||||
|
||||
|
||||
class SimpleAIService:
|
||||
"""提供在 LightRAG 不可用时的兜底回答。"""
|
||||
|
||||
def summarize_document(
|
||||
self,
|
||||
*,
|
||||
query: str,
|
||||
user_id: str,
|
||||
document_id: Optional[str],
|
||||
workspace_id: Optional[str],
|
||||
) -> Dict[str, object]:
|
||||
document = None
|
||||
if document_id:
|
||||
document = supabase_rest.select_one(
|
||||
"documents",
|
||||
{
|
||||
"id": document_id,
|
||||
"user_id": user_id,
|
||||
},
|
||||
)
|
||||
|
||||
title = (document or {}).get("title") or "当前页面"
|
||||
raw_text = (document or {}).get("raw_text") or ""
|
||||
if not raw_text and document and document.get("content"):
|
||||
raw_text = self._blocks_to_text(document["content"])
|
||||
|
||||
snippet = raw_text.strip().replace("\n", " ")
|
||||
if len(snippet) > 400:
|
||||
snippet = snippet[:400].rstrip() + "…"
|
||||
|
||||
if snippet:
|
||||
summary = f"《{title}》当前摘要:{snippet}"
|
||||
else:
|
||||
summary = f"《{title}》暂未填写正文内容,可直接编辑后再次提问。"
|
||||
|
||||
answer = "\n\n".join(
|
||||
[
|
||||
summary,
|
||||
f"你的问题:{query}",
|
||||
"(提示:LightRAG 暂未就绪,已使用本地摘要兜底回答)",
|
||||
]
|
||||
)
|
||||
|
||||
references = []
|
||||
if document_id:
|
||||
ref_path = f"doc://{document_id}"
|
||||
if title:
|
||||
ref_path = f"{ref_path}?title={title}"
|
||||
references.append(
|
||||
{
|
||||
"file_path": ref_path,
|
||||
"workspace": workspace_id or "",
|
||||
}
|
||||
)
|
||||
|
||||
return {"content": answer, "references": references}
|
||||
|
||||
def _blocks_to_text(self, content: object) -> str:
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts = []
|
||||
for item in content:
|
||||
text = self._blocks_to_text(item)
|
||||
if text:
|
||||
parts.append(text)
|
||||
return " ".join(parts)
|
||||
if isinstance(content, dict):
|
||||
if "text" in content and isinstance(content["text"], str):
|
||||
return content["text"]
|
||||
parts = []
|
||||
for value in content.values():
|
||||
text = self._blocks_to_text(value)
|
||||
if text:
|
||||
parts.append(text)
|
||||
return " ".join(parts)
|
||||
try:
|
||||
return json.dumps(content, ensure_ascii=False)
|
||||
except TypeError:
|
||||
return ""
|
||||
|
||||
|
||||
simple_ai_service = SimpleAIService()
|
||||
Reference in New Issue
Block a user