UnisKB/apps/system_manage/ai_hub_worker.py

105 lines
5.9 KiB
Python

"""Database-backed single consumer; never consumes legacy Celery queues."""
from django.db import transaction
from django.utils import timezone
from system_manage.models.ai_hub import AITask
from system_manage import ai_hub as hub
def claim():
with transaction.atomic():
task = AITask.objects.select_for_update(skip_locked=True).filter(status='PENDING').order_by('created_at').first()
if not task:
return None
task.status = 'RUNNING'
task.started_at = timezone.now()
task.save(update_fields=['status', 'started_at', 'updated_at'])
return task
def execute(task):
from users.models import User
steps = []
try:
user = User.objects.get(pk=task.owner_id)
if not user.is_active:
raise ValueError('用户已停用')
if task.service_id:
service = hub.one('services', task.service_id, task.workspace_id, user)
if not service.enabled:
raise ValueError('服务已停用')
markdown = task.input_data.get('markdown', '')
original = markdown
source = {}
tree = {}
task.result = {'original': original, 'markdown': markdown, 'source': source, 'tree': tree}
task.save(update_fields=['result', 'updated_at'])
for node in task.snapshot['nodes']:
step = {'type': node['type'], 'status': 'RUNNING'}
steps.append(step)
task.steps = steps
task.save(update_fields=['steps', 'updated_at'])
if node['type'] == 'parse':
parser = hub.one('parsers', node['resource_id'], task.workspace_id, user)
if not parser.enabled or parser.updated_at.isoformat() != node['resource_version']:
raise ValueError('解析服务已停用或版本发生变化,请重新提交')
def report_progress(progress):
step['progress'] = progress
AITask.objects.filter(pk=task.pk, attempt=task.attempt, status='RUNNING').update(
steps=steps, updated_at=timezone.now())
report_progress({'stage': '上传文档到解析服务', 'percent': None})
parsed = hub.parse_file(parser, task.file_name, bytes(task.file_data), node['options'], progress_callback=report_progress)
from system_manage.ai_hub_assets import asset_lock, normalize
with asset_lock():
markdown = original = hub.text(normalize(parsed['markdown'], task.workspace_id, user, parsed.get('images')), '解析结果')
source = parsed['source']
# Source JSON can contain image data too; preserve structure without inline payloads.
import json
source = json.loads(normalize(json.dumps(source), task.workspace_id, user))
task.result = {'original': original, 'markdown': markdown, 'source': source}
task.save(update_fields=['result', 'updated_at'])
elif node['type'] == 'organize':
from models_provider.tools import get_model, get_model_default_params
from langchain_core.messages import HumanMessage, SystemMessage
model = hub.model_for(task.workspace_id, user, node['model_id'])
if model.update_time.isoformat() != node['resource_version']:
raise ValueError('模型配置已变更,请重新提交')
# Bound input; never silently truncate the original document.
from system_manage.ai_hub_assets import protect_images, restore_images
model_markdown, image_tokens = protect_images(markdown)
if len(model_markdown) > 60000:
raise ValueError('文档超过智能整理长度限制,请分批处理')
try:
instance = get_model(model, **{**get_model_default_params(model),
'temperature': node.get('temperature', 0.2), 'timeout': 180})
prompt = node['prompt'] + '\n保留 AIHUBIMAGE 数字 TOKEN 图片占位符,尽量放在相关内容旁;不要编造图片或重复占位符。'
response = instance.invoke([SystemMessage(content=prompt), HumanMessage(content=model_markdown)])
except Exception as exc:
from rest_framework.exceptions import ValidationError
raise ValidationError('模型调用失败,请检查接入状态或输入长度') from exc
markdown = restore_images(hub.text(response.content, '整理结果'), image_tokens)
else:
tree = hub.markdown_tree(markdown)
step['status'] = 'SUCCESS'
task.steps = steps
# Persist intermediate original output so a later model failure does not lose OCR work.
task.result = {'original': original, 'markdown': markdown, 'source': source, 'tree': tree}
task.save(update_fields=['steps', 'result', 'updated_at'])
task.status = 'SUCCESS'
except Exception as exc:
if steps:
steps[-1]['status'] = 'FAILED'
# Do not echo URLs, credentials, request bodies or provider exceptions to users/logs.
from rest_framework.exceptions import APIException
if isinstance(exc, APIException):
detail = exc.detail
while isinstance(detail, (list, tuple, dict)) and detail:
detail = next(iter(detail.values())) if isinstance(detail, dict) else detail[0]
task.error = str(detail)[:512]
else:
task.error = str(exc)[:512] if isinstance(exc, ValueError) else '执行失败,请检查服务状态后重试'
task.status = 'FAILED'
task.steps = steps
task.finished_at = timezone.now()
task.save(update_fields=['status', 'error', 'steps', 'finished_at', 'updated_at'])
return task