Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
c4fa3b7
1
Parent(s): 81e5ffd
fix: resolve typescript build errors in internal portal navigation
Browse files- api/v1/kb.py +33 -23
- core/llm.py +35 -7
- core/search.py +46 -19
- core/tasks.py +10 -22
- core/vision.py +12 -8
- nexus_worker.py +9 -3
api/v1/kb.py
CHANGED
|
@@ -884,10 +884,10 @@ async def parse_kb_file(
|
|
| 884 |
raise HTTPException(status_code=400, detail="Only .txt and .md files are supported for AI parsing.")
|
| 885 |
|
| 886 |
contents = await file.read()
|
| 887 |
-
#
|
| 888 |
-
max_size =
|
| 889 |
if len(contents) > max_size:
|
| 890 |
-
raise HTTPException(status_code=400, detail="File
|
| 891 |
|
| 892 |
try:
|
| 893 |
text = contents.decode('utf-8')
|
|
@@ -912,27 +912,37 @@ async def parse_kb_file(
|
|
| 912 |
HumanMessage(content=f"UNSTRUCTURED CONTENT:\n\n{text}")
|
| 913 |
]
|
| 914 |
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
ai_content = ai_content[11:-3].strip()
|
| 922 |
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
"
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 936 |
|
| 937 |
|
| 938 |
|
|
|
|
| 884 |
raise HTTPException(status_code=400, detail="Only .txt and .md files are supported for AI parsing.")
|
| 885 |
|
| 886 |
contents = await file.read()
|
| 887 |
+
# 150 KB limit for synchronous parsing to prevent 502/524 Cloudflare chunk timeouts
|
| 888 |
+
max_size = 150 * 1024
|
| 889 |
if len(contents) > max_size:
|
| 890 |
+
raise HTTPException(status_code=400, detail="File too large for synchronous direct-edit parsing. Please upload a file smaller than 150KB.")
|
| 891 |
|
| 892 |
try:
|
| 893 |
text = contents.decode('utf-8')
|
|
|
|
| 912 |
HumanMessage(content=f"UNSTRUCTURED CONTENT:\n\n{text}")
|
| 913 |
]
|
| 914 |
|
| 915 |
+
import asyncio
|
| 916 |
+
max_retries = 3
|
| 917 |
+
for attempt in range(max_retries):
|
| 918 |
+
try:
|
| 919 |
+
resp = await llm.ainvoke(prompt)
|
| 920 |
+
ai_content = resp.content.strip()
|
|
|
|
| 921 |
|
| 922 |
+
# Strip potential markdown formatting block if LLM wraps the whole response
|
| 923 |
+
if ai_content.startswith("```markdown") and ai_content.endswith("```"):
|
| 924 |
+
ai_content = ai_content[11:-3].strip()
|
| 925 |
+
|
| 926 |
+
# Try to extract a title (first h1)
|
| 927 |
+
import re
|
| 928 |
+
title_match = re.search(r'^#\s+(.+)$', ai_content, re.MULTILINE)
|
| 929 |
+
title = title_match.group(1).strip() if title_match else "AI Generated Article"
|
| 930 |
+
|
| 931 |
+
return {
|
| 932 |
+
"title": title,
|
| 933 |
+
"content": ai_content,
|
| 934 |
+
"category": "General"
|
| 935 |
+
}
|
| 936 |
+
except Exception as e:
|
| 937 |
+
error_str = str(e)
|
| 938 |
+
is_transient = "502" in error_str or "504" in error_str or "timeout" in error_str.lower()
|
| 939 |
+
if is_transient and attempt < max_retries - 1:
|
| 940 |
+
logger.warning(f"AI Parse transient error (attempt {attempt+1}/{max_retries}): {e}. Retrying in 2 seconds...")
|
| 941 |
+
await asyncio.sleep(2)
|
| 942 |
+
continue
|
| 943 |
+
|
| 944 |
+
logger.error(f"AI Parse Failed after {attempt+1} attempts: {e}")
|
| 945 |
+
raise HTTPException(status_code=500, detail=f"AI transformation failed: {str(e)}")
|
| 946 |
|
| 947 |
|
| 948 |
|
core/llm.py
CHANGED
|
@@ -69,17 +69,24 @@ def get_llm(provider: str = None, model: str = None, use_fast_model: bool = Fals
|
|
| 69 |
import httpx
|
| 70 |
|
| 71 |
def is_retryable_exception(e):
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
| 75 |
if isinstance(e, httpx.HTTPStatusError):
|
| 76 |
-
# 524: Cloudflare Timeout - DO NOT RETRY in real-time context as it already took 100s
|
| 77 |
if e.response.status_code == 524:
|
| 78 |
return False
|
| 79 |
-
|
| 80 |
-
if "html" in e.response.headers.get("content-type", "").lower():
|
| 81 |
return False
|
| 82 |
-
return e.response.status_code in [429, 503]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
if isinstance(e, (httpx.ConnectError, httpx.ConnectTimeout)):
|
| 84 |
return True
|
| 85 |
if isinstance(e, httpx.ReadTimeout):
|
|
@@ -176,11 +183,26 @@ class TruncatedEmbeddings(Embeddings):
|
|
| 176 |
"""
|
| 177 |
Wrapper for LangChain Embeddings that ensures the output vector
|
| 178 |
matches a specific dimension by truncating or padding.
|
|
|
|
| 179 |
"""
|
| 180 |
def __init__(self, inner: Embeddings, dimension: int):
|
| 181 |
self.inner = inner
|
| 182 |
self.dimension = dimension
|
| 183 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
def _truncate(self, vector: List[float]) -> List[float]:
|
| 185 |
if len(vector) > self.dimension:
|
| 186 |
return vector[:self.dimension]
|
|
@@ -188,18 +210,24 @@ class TruncatedEmbeddings(Embeddings):
|
|
| 188 |
return vector + [0.0] * (self.dimension - len(vector))
|
| 189 |
return vector
|
| 190 |
|
|
|
|
|
|
|
|
|
|
| 191 |
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
| 192 |
vectors = self.inner.embed_documents(texts)
|
| 193 |
return [self._truncate(v) for v in vectors]
|
| 194 |
|
|
|
|
| 195 |
def embed_query(self, text: str) -> List[float]:
|
| 196 |
vector = self.inner.embed_query(text)
|
| 197 |
return self._truncate(vector)
|
| 198 |
|
|
|
|
| 199 |
async def aembed_query(self, text: str) -> List[float]:
|
| 200 |
vector = await self.inner.aembed_query(text)
|
| 201 |
return self._truncate(vector)
|
| 202 |
|
|
|
|
| 203 |
async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
|
| 204 |
# Check if the inner embedding provider has an async method
|
| 205 |
if hasattr(self.inner, "aembed_documents"):
|
|
|
|
| 69 |
import httpx
|
| 70 |
|
| 71 |
def is_retryable_exception(e):
|
| 72 |
+
import httpx
|
| 73 |
+
err_str = str(e).lower()
|
| 74 |
+
|
| 75 |
+
# Check for explicitly non-retryable 524 timeouts from Cloudflare in real-time context
|
| 76 |
+
# Or hard HTML 404/500 failures
|
| 77 |
if isinstance(e, httpx.HTTPStatusError):
|
|
|
|
| 78 |
if e.response.status_code == 524:
|
| 79 |
return False
|
| 80 |
+
if "html" in e.response.headers.get("content-type", "").lower() and e.response.status_code not in [502, 503]:
|
|
|
|
| 81 |
return False
|
| 82 |
+
return e.response.status_code in [429, 502, 503, 504]
|
| 83 |
+
|
| 84 |
+
# specifically catch Ollama SDK's ResponseError which doesn't inherit from HTTPStatusError
|
| 85 |
+
if "responseerror" in err_str or "ollama" in str(type(e)).lower():
|
| 86 |
+
if "524" in err_str: return False # Don't retry real-time cloudflare drops
|
| 87 |
+
if "502" in err_str or "503" in err_str or "504" in err_str or "429" in err_str:
|
| 88 |
+
return True
|
| 89 |
+
|
| 90 |
if isinstance(e, (httpx.ConnectError, httpx.ConnectTimeout)):
|
| 91 |
return True
|
| 92 |
if isinstance(e, httpx.ReadTimeout):
|
|
|
|
| 183 |
"""
|
| 184 |
Wrapper for LangChain Embeddings that ensures the output vector
|
| 185 |
matches a specific dimension by truncating or padding.
|
| 186 |
+
Also includes resilient retry logic for transient provider errors.
|
| 187 |
"""
|
| 188 |
def __init__(self, inner: Embeddings, dimension: int):
|
| 189 |
self.inner = inner
|
| 190 |
self.dimension = dimension
|
| 191 |
|
| 192 |
+
def _is_retryable(e):
|
| 193 |
+
import httpx
|
| 194 |
+
err_str = str(e).lower()
|
| 195 |
+
if isinstance(e, httpx.HTTPStatusError):
|
| 196 |
+
if e.response.status_code == 524: return False
|
| 197 |
+
if "html" in e.response.headers.get("content-type", "").lower() and e.response.status_code not in [502, 503]: return False
|
| 198 |
+
return e.response.status_code in [429, 502, 503, 504]
|
| 199 |
+
if "responseerror" in err_str or "ollama" in str(type(e)).lower():
|
| 200 |
+
if "524" in err_str: return False
|
| 201 |
+
if "502" in err_str or "503" in err_str or "504" in err_str or "429" in err_str: return True
|
| 202 |
+
if isinstance(e, (httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout)): return True
|
| 203 |
+
return False
|
| 204 |
+
|
| 205 |
+
|
| 206 |
def _truncate(self, vector: List[float]) -> List[float]:
|
| 207 |
if len(vector) > self.dimension:
|
| 208 |
return vector[:self.dimension]
|
|
|
|
| 210 |
return vector + [0.0] * (self.dimension - len(vector))
|
| 211 |
return vector
|
| 212 |
|
| 213 |
+
from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception
|
| 214 |
+
|
| 215 |
+
@retry(retry=retry_if_exception(_is_retryable), wait=wait_exponential(multiplier=1, min=2, max=10), stop=stop_after_attempt(3), reraise=True)
|
| 216 |
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
| 217 |
vectors = self.inner.embed_documents(texts)
|
| 218 |
return [self._truncate(v) for v in vectors]
|
| 219 |
|
| 220 |
+
@retry(retry=retry_if_exception(_is_retryable), wait=wait_exponential(multiplier=1, min=2, max=10), stop=stop_after_attempt(3), reraise=True)
|
| 221 |
def embed_query(self, text: str) -> List[float]:
|
| 222 |
vector = self.inner.embed_query(text)
|
| 223 |
return self._truncate(vector)
|
| 224 |
|
| 225 |
+
@retry(retry=retry_if_exception(_is_retryable), wait=wait_exponential(multiplier=1, min=2, max=10), stop=stop_after_attempt(3), reraise=True)
|
| 226 |
async def aembed_query(self, text: str) -> List[float]:
|
| 227 |
vector = await self.inner.aembed_query(text)
|
| 228 |
return self._truncate(vector)
|
| 229 |
|
| 230 |
+
@retry(retry=retry_if_exception(_is_retryable), wait=wait_exponential(multiplier=1, min=2, max=10), stop=stop_after_attempt(3), reraise=True)
|
| 231 |
async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
|
| 232 |
# Check if the inner embedding provider has an async method
|
| 233 |
if hasattr(self.inner, "aembed_documents"):
|
core/search.py
CHANGED
|
@@ -1,26 +1,53 @@
|
|
| 1 |
from typing import List
|
| 2 |
|
| 3 |
-
def chunk_text(text: str, chunk_size: int =
|
| 4 |
"""
|
| 5 |
-
|
| 6 |
-
|
|
|
|
| 7 |
"""
|
| 8 |
if not text:
|
| 9 |
return []
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
# Prevent infinite loop if overlap >= size
|
| 23 |
-
if chunk_overlap >= chunk_size:
|
| 24 |
-
start = end
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from typing import List
|
| 2 |
|
| 3 |
+
def chunk_text(text: str, chunk_size: int = 1200, chunk_overlap: int = 200) -> List[str]:
|
| 4 |
"""
|
| 5 |
+
Smarter Recursive-style character splitter for text chunking.
|
| 6 |
+
Prioritizes splitting at paragraph (\\n\\n) and sentence (\\n) boundaries
|
| 7 |
+
to preserve semantic context for RAG.
|
| 8 |
"""
|
| 9 |
if not text:
|
| 10 |
return []
|
| 11 |
+
|
| 12 |
+
# 1. Split by paragraphs first
|
| 13 |
+
paragraphs = text.split("\n\n")
|
| 14 |
+
final_chunks = []
|
| 15 |
+
current_chunk = ""
|
| 16 |
+
|
| 17 |
+
for paragraph in paragraphs:
|
| 18 |
+
# If adding this paragraph exceeds chunk_size, close current and start new
|
| 19 |
+
if len(current_chunk) + len(paragraph) > chunk_size:
|
| 20 |
+
if current_chunk:
|
| 21 |
+
final_chunks.append(current_chunk.strip())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# If a single paragraph is larger than chunk_size, split it by newlines
|
| 24 |
+
if len(paragraph) > chunk_size:
|
| 25 |
+
sub_lines = paragraph.split("\n")
|
| 26 |
+
for line in sub_lines:
|
| 27 |
+
if len(current_chunk) + len(line) > chunk_size:
|
| 28 |
+
if current_chunk:
|
| 29 |
+
final_chunks.append(current_chunk.strip())
|
| 30 |
+
current_chunk = line[:chunk_size]
|
| 31 |
+
else:
|
| 32 |
+
current_chunk += "\n" + line if current_chunk else line
|
| 33 |
+
else:
|
| 34 |
+
current_chunk = paragraph
|
| 35 |
+
else:
|
| 36 |
+
current_chunk += "\n\n" + paragraph if current_chunk else paragraph
|
| 37 |
+
|
| 38 |
+
if current_chunk:
|
| 39 |
+
final_chunks.append(current_chunk.strip())
|
| 40 |
+
|
| 41 |
+
# 2. Implement Overlap (Retroactive)
|
| 42 |
+
# Simple overlap addition: prepend last X chars of chunk N to start of chunk N+1
|
| 43 |
+
overlapped_chunks = []
|
| 44 |
+
for i, chunk in enumerate(final_chunks):
|
| 45 |
+
if i == 0:
|
| 46 |
+
overlapped_chunks.append(chunk)
|
| 47 |
+
continue
|
| 48 |
+
|
| 49 |
+
prev_chunk = final_chunks[i-1]
|
| 50 |
+
overlap_text = prev_chunk[-chunk_overlap:] if len(prev_chunk) > chunk_overlap else prev_chunk
|
| 51 |
+
overlapped_chunks.append(overlap_text + "\n" + chunk)
|
| 52 |
+
|
| 53 |
+
return overlapped_chunks
|
core/tasks.py
CHANGED
|
@@ -639,14 +639,15 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
|
| 639 |
# --- PHASE 3: Chunking & Architecture Enrichment ---
|
| 640 |
try:
|
| 641 |
await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))
|
| 642 |
-
|
|
|
|
| 643 |
|
|
|
|
| 644 |
for i, text_content in enumerate(raw_chunks):
|
| 645 |
-
# Architecture Enrichment Step
|
| 646 |
processed_text = text_content
|
|
|
|
| 647 |
if "```mermaid" in text_content.lower() or "```json" in text_content.lower() or "graph " in text_content[:50].lower():
|
| 648 |
try:
|
| 649 |
-
logger.info(f"Technical block detected in chunk {i} of {article_id}. Generating TEK_NAV...")
|
| 650 |
enrich_prompt = (
|
| 651 |
f"Explain this technical block in ONE concise sentence for search indexing. "
|
| 652 |
f"Identify what the flow/data represents.\n\nBLOCK:\n{text_content[:2000]}"
|
|
@@ -658,20 +659,22 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
|
| 658 |
except Exception as enrich_err:
|
| 659 |
logger.warning(f"Architecture Enrichment failed for chunk {i}: {enrich_err}")
|
| 660 |
|
|
|
|
| 661 |
chunk_vector = await text_model.aembed_query(f"{article.title}: {processed_text}")
|
| 662 |
-
|
| 663 |
article_id=article.id,
|
| 664 |
content=processed_text,
|
| 665 |
chunk_index=i,
|
| 666 |
embedding=chunk_vector
|
| 667 |
)
|
| 668 |
-
db.add(
|
|
|
|
| 669 |
|
| 670 |
if await _abort_if_deleted(): return
|
| 671 |
await db.commit()
|
| 672 |
await db.refresh(article)
|
| 673 |
phases_succeeded.append("PHASE 3 [Chunking]")
|
| 674 |
-
logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks)")
|
| 675 |
except Exception as e:
|
| 676 |
logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
|
| 677 |
phases_failed.append("PHASE 3 [Chunking]")
|
|
@@ -679,10 +682,10 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
|
| 679 |
await db.refresh(article)
|
| 680 |
if is_transient(e):
|
| 681 |
raise RuntimeError(f"Transient provider error in Phase 3: {e}")
|
| 682 |
-
# Chunking is mandatory
|
| 683 |
raise RuntimeError(f"Mandatory indexing phase (Chunking) failed for {article_id}. Retrying...")
|
| 684 |
|
| 685 |
|
|
|
|
| 686 |
# --- PHASE 4: Auto-Categorization ---
|
| 687 |
try:
|
| 688 |
if not article.category or article.category in ["N/A", "General"]:
|
|
@@ -795,21 +798,6 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
|
| 795 |
])
|
| 796 |
if resp and resp.content:
|
| 797 |
article.summary = resp.content
|
| 798 |
-
|
| 799 |
-
# 2. Defensive Check: Emergency Embedding Generation if Phase 2 failed
|
| 800 |
-
if article.embedding is None:
|
| 801 |
-
# SMART PERSISTENCE: Re-fetch from DB first to see if Phase 2 commit was successful but session stale
|
| 802 |
-
await db.refresh(article, attribute_names=["embedding"])
|
| 803 |
-
|
| 804 |
-
if article.embedding is None:
|
| 805 |
-
logger.warning(f"PHASE 7 [Critical Check]: Embedding still NULL for {article_id}. Attempting emergency generation with 4k limit.")
|
| 806 |
-
try:
|
| 807 |
-
emergency_text = truncate_content(f"{article.title} {article.content}", 4000)
|
| 808 |
-
article.embedding = await text_model.aembed_query(emergency_text)
|
| 809 |
-
logger.info(f"PHASE 7 [Critical Check]: Emergency embedding generation SUCCESSFUL for {article_id}")
|
| 810 |
-
except Exception as e_inner:
|
| 811 |
-
logger.error(f"PHASE 7 [Critical Check]: Emergency embedding generation FAILED for {article_id}: {str(e_inner)}")
|
| 812 |
-
|
| 813 |
db.add(article)
|
| 814 |
if await _abort_if_deleted(): return
|
| 815 |
await db.commit()
|
|
|
|
| 639 |
# --- PHASE 3: Chunking & Architecture Enrichment ---
|
| 640 |
try:
|
| 641 |
await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))
|
| 642 |
+
# Using the NEW smarter context-aware chunker
|
| 643 |
+
raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=200)
|
| 644 |
|
| 645 |
+
# SEQUENTIAL PROCESSING: Prevents DOSing the local Ollama provider
|
| 646 |
for i, text_content in enumerate(raw_chunks):
|
|
|
|
| 647 |
processed_text = text_content
|
| 648 |
+
# Architecture Enrichment Step
|
| 649 |
if "```mermaid" in text_content.lower() or "```json" in text_content.lower() or "graph " in text_content[:50].lower():
|
| 650 |
try:
|
|
|
|
| 651 |
enrich_prompt = (
|
| 652 |
f"Explain this technical block in ONE concise sentence for search indexing. "
|
| 653 |
f"Identify what the flow/data represents.\n\nBLOCK:\n{text_content[:2000]}"
|
|
|
|
| 659 |
except Exception as enrich_err:
|
| 660 |
logger.warning(f"Architecture Enrichment failed for chunk {i}: {enrich_err}")
|
| 661 |
|
| 662 |
+
# Embedding generation
|
| 663 |
chunk_vector = await text_model.aembed_query(f"{article.title}: {processed_text}")
|
| 664 |
+
chunk_obj = KBArticleChunk(
|
| 665 |
article_id=article.id,
|
| 666 |
content=processed_text,
|
| 667 |
chunk_index=i,
|
| 668 |
embedding=chunk_vector
|
| 669 |
)
|
| 670 |
+
db.add(chunk_obj)
|
| 671 |
+
|
| 672 |
|
| 673 |
if await _abort_if_deleted(): return
|
| 674 |
await db.commit()
|
| 675 |
await db.refresh(article)
|
| 676 |
phases_succeeded.append("PHASE 3 [Chunking]")
|
| 677 |
+
logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks in parallel)")
|
| 678 |
except Exception as e:
|
| 679 |
logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
|
| 680 |
phases_failed.append("PHASE 3 [Chunking]")
|
|
|
|
| 682 |
await db.refresh(article)
|
| 683 |
if is_transient(e):
|
| 684 |
raise RuntimeError(f"Transient provider error in Phase 3: {e}")
|
|
|
|
| 685 |
raise RuntimeError(f"Mandatory indexing phase (Chunking) failed for {article_id}. Retrying...")
|
| 686 |
|
| 687 |
|
| 688 |
+
|
| 689 |
# --- PHASE 4: Auto-Categorization ---
|
| 690 |
try:
|
| 691 |
if not article.category or article.category in ["N/A", "General"]:
|
|
|
|
| 798 |
])
|
| 799 |
if resp and resp.content:
|
| 800 |
article.summary = resp.content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 801 |
db.add(article)
|
| 802 |
if await _abort_if_deleted(): return
|
| 803 |
await db.commit()
|
core/vision.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import re
|
|
|
|
| 2 |
import base64
|
| 3 |
import os
|
| 4 |
from uuid import UUID
|
|
@@ -68,15 +69,18 @@ async def resolve_image(db: AsyncSession, workspace_id: UUID, identifier: str) -
|
|
| 68 |
|
| 69 |
local_path = storage.get_local_path(attachment.storage_path)
|
| 70 |
if os.path.exists(local_path):
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
}
|
|
|
|
| 80 |
|
| 81 |
except (ValueError, IndexError):
|
| 82 |
# Not a valid UUID or recognizable attachment link
|
|
|
|
| 1 |
import re
|
| 2 |
+
import asyncio
|
| 3 |
import base64
|
| 4 |
import os
|
| 5 |
from uuid import UUID
|
|
|
|
| 69 |
|
| 70 |
local_path = storage.get_local_path(attachment.storage_path)
|
| 71 |
if os.path.exists(local_path):
|
| 72 |
+
def _read_and_encode():
|
| 73 |
+
with open(local_path, "rb") as f:
|
| 74 |
+
return base64.b64encode(f.read()).decode("utf-8")
|
| 75 |
+
|
| 76 |
+
img_data = await asyncio.to_thread(_read_and_encode)
|
| 77 |
+
return {
|
| 78 |
+
"type": "image_url",
|
| 79 |
+
"image_url": {
|
| 80 |
+
"url": f"data:{attachment.content_type};base64,{img_data}",
|
| 81 |
+
"detail": "auto"
|
| 82 |
}
|
| 83 |
+
}
|
| 84 |
|
| 85 |
except (ValueError, IndexError):
|
| 86 |
# Not a valid UUID or recognizable attachment link
|
nexus_worker.py
CHANGED
|
@@ -156,11 +156,17 @@ async def on_job_end(ctx):
|
|
| 156 |
logger.info(f"✅ Job SUCCESS: {job.task_name} | ID: {job_id}")
|
| 157 |
else:
|
| 158 |
exception = ctx.get("exception")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
if exception is None:
|
| 160 |
-
#
|
| 161 |
-
job.error = "
|
| 162 |
job.status = JobStatus.INTERRUPTED
|
| 163 |
-
logger.warning(f"⚠️ Job
|
| 164 |
else:
|
| 165 |
job.status = JobStatus.FAILED
|
| 166 |
job.error = str(exception)
|
|
|
|
| 156 |
logger.info(f"✅ Job SUCCESS: {job.task_name} | ID: {job_id}")
|
| 157 |
else:
|
| 158 |
exception = ctx.get("exception")
|
| 159 |
+
result = ctx.get("result")
|
| 160 |
+
|
| 161 |
+
# ARQ edge case: sometimes exception is returned in the result field
|
| 162 |
+
if exception is None and isinstance(result, Exception):
|
| 163 |
+
exception = result
|
| 164 |
+
|
| 165 |
if exception is None:
|
| 166 |
+
# Verify if job was cancelled or worker is genuinely shutting down
|
| 167 |
+
job.error = "SYSTEM_INTERRUPTION: Job was interrupted (Worker Shutdown or Cancelled)."
|
| 168 |
job.status = JobStatus.INTERRUPTED
|
| 169 |
+
logger.warning(f"⚠️ Job INTERRUPTED: {job.task_name} | ID: {job_id}")
|
| 170 |
else:
|
| 171 |
job.status = JobStatus.FAILED
|
| 172 |
job.error = str(exception)
|