UnisKB/apps/system_manage/ai_hub.py

514 lines
25 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""AI hub business operations. Secrets never cross the browser boundary."""
from urllib.parse import urlsplit
from django.db import connection, transaction
from rest_framework.exceptions import ValidationError, PermissionDenied, NotFound
from system_manage.models.ai_hub import AIParserResource, AIFlow, AIService, AITask, AIArtifact
MAX_TEXT = 2_000_000
MAX_INLINE_TEXT = MAX_TEXT + 140_000_000
MAX_FILE = 20 * 1024 * 1024
KINDS = {'parsers': AIParserResource, 'flows': AIFlow, 'services': AIService,
'tasks': AITask, 'artifacts': AIArtifact}
def admin(user):
from system_manage.platform_access import is_admin
return is_admin(user)
def require_admin(user):
if not admin(user):
raise PermissionDenied('仅管理员可操作')
def visible(query, user):
# Sharing is explicit, with no implicit public access.
if admin(user):
return query
if query.model in (AIParserResource, AIService):
from system_manage.platform_access import grants_for, expand_actions
kind = 'PARSER' if query.model == AIParserResource else 'SERVICE'
granted = {g.target for g in grants_for(user).filter(resource_type=kind) if 'VIEW' in expand_actions(g.actions)}
ids = [obj.id for obj in query if str(obj.owner_id) == str(user.id)
or str(user.id) in obj.allowed_users or str(obj.id) in granted]
return query.filter(id__in=ids)
return query.filter(owner_id=user.id)
def one(kind, pk, workspace, user, edit=False, lock=False):
from rest_framework.serializers import UUIDField
pk = UUIDField().run_validation(pk)
model = KINDS.get(kind)
if not model:
raise NotFound()
query = model.objects.filter(workspace_id=workspace, id=pk)
if lock:
query = query.select_for_update()
obj = visible(query, user).first()
if not obj:
raise NotFound('记录不存在或无权访问')
if edit and not admin(user) and str(obj.owner_id) != str(user.id):
from system_manage.platform_access import resource_actions
resource_type = {'parsers': 'PARSER', 'services': 'SERVICE'}.get(kind)
if not resource_type or 'EDIT' not in resource_actions(user, resource_type, obj.id, workspace):
raise PermissionDenied('无权修改')
return obj
def require_use(user, obj):
if admin(user) or str(obj.owner_id) == str(user.id) or str(user.id) in obj.allowed_users:
return
from system_manage.platform_access import resource_actions
kind = 'PARSER' if isinstance(obj, AIParserResource) else 'SERVICE'
if 'USE' not in resource_actions(user, kind, obj.id, obj.workspace_id):
raise PermissionDenied('未授权使用该资源')
def require_resource_action(user, obj, action):
if admin(user) or str(obj.owner_id) == str(user.id):
return
from system_manage.platform_access import resource_actions
kind = 'PARSER' if isinstance(obj, AIParserResource) else 'SERVICE'
if action not in resource_actions(user, kind, obj.id, obj.workspace_id):
raise PermissionDenied('无权操作该资源')
def text(value, label, required=True, limit=MAX_TEXT):
if not isinstance(value, str) or len(value) > limit or (required and not value.strip()):
raise ValidationError(f'{label}无效')
return value
def integer(value, minimum, maximum, label):
if isinstance(value, bool) or not isinstance(value, int) or not minimum <= value <= maximum:
raise ValidationError(f'{label}无效')
return value
def users(value):
from users.models import User
if not isinstance(value, list) or len(value) > 500:
raise ValidationError('授权用户无效')
values = {str(item) for item in value}
try:
allowed = set(str(pk) for pk in User.objects.filter(id__in=values, is_active=True).values_list('id', flat=True))
except (ValueError, TypeError):
raise ValidationError('授权用户无效')
# Registration approval is enforced by the existing activation extension.
from users.models.user_manage_ext import UserActivationApplication
pending = set(str(pk) for pk in UserActivationApplication.objects.exclude(status='APPROVED').values_list('user_id', flat=True))
if values - (allowed - pending):
raise ValidationError('只能授权已激活且启用的用户')
return sorted(values)
def authorized_models(workspace, user):
from models_provider.models import Model
from system_manage.models import WorkspaceUserResourcePermission, AuthTargetType
query = Model.objects.filter(workspace_id=workspace, status='SUCCESS')
if not admin(user):
grants = WorkspaceUserResourcePermission.objects.filter(
workspace_id=workspace, user_id=user.id, auth_target_type=AuthTargetType.MODEL)
ids = [g.target for g in grants if 'VIEW' in g.permission_list]
from system_manage.platform_access import grants_for, expand_actions
ids.extend(g.target for g in grants_for(user).filter(resource_type='MODEL') if 'USE' in expand_actions(g.actions))
query = query.filter(id__in=ids)
return query
def model_for(workspace, user, model_id):
from rest_framework.serializers import UUIDField
model_id = UUIDField().run_validation(model_id)
obj = authorized_models(workspace, user).filter(id=model_id, model_type='LLM').first()
if not obj:
raise PermissionDenied('模型不可用或未授权')
return obj
def serialize(obj, detail=False, user=None):
data = {'id': str(obj.id), 'name': obj.name, 'updated_at': obj.updated_at.isoformat()}
if user is not None:
data['can_delete'] = admin(user) or str(obj.owner_id) == str(user.id)
if user is not None and isinstance(obj, (AIParserResource, AIService)):
from system_manage.platform_access import resource_actions, ACTIONS
kind = 'PARSER' if isinstance(obj, AIParserResource) else 'SERVICE'
actions = set(ACTIONS) if admin(user) or str(obj.owner_id) == str(user.id) else resource_actions(user, kind, obj.id, obj.workspace_id)
if str(user.id) in obj.allowed_users:
actions |= {'VIEW', 'USE'}
data['actions'] = sorted(actions)
data['can_delete'] = 'EDIT' in actions
if isinstance(obj, AIParserResource):
data.update(enabled=obj.enabled, allowed_users=obj.allowed_users,
options=obj.options, credential_configured=bool(obj.credential))
# Only callers of admin management endpoints receive endpoint addresses.
elif isinstance(obj, AIFlow):
data.update(revision=obj.revision, nodes=obj.nodes)
elif isinstance(obj, AIService):
data.update(flow_id=str(obj.flow_id), enabled=obj.enabled, allowed_users=obj.allowed_users,
requests_per_minute=obj.requests_per_minute,
key_configured=bool(obj.key_hash), url=f'ai_hub/published/{obj.id}/run')
elif isinstance(obj, AITask):
from system_manage.ai_hub_progress import task_progress
data.update(status=obj.status, steps=obj.steps, error=obj.error, attempt=obj.attempt,
started_at=obj.started_at, finished_at=obj.finished_at)
if detail:
data.update(snapshot=obj.snapshot, result=obj.result, progress=task_progress(obj))
elif isinstance(obj, AIArtifact):
data.update(revision=obj.revision, layout=obj.layout, task_id=str(obj.task_id) if obj.task_id else None)
if detail:
data.update(original=obj.original, markdown=obj.markdown, history=obj.history)
return data
def parser_save(workspace, user, data, obj=None):
if obj is None:
require_admin(user)
else:
if set(data) - {'allowed_users'}:
require_resource_action(user, obj, 'EDIT')
if 'allowed_users' in data:
require_resource_action(user, obj, 'AUTHORIZE')
endpoint = text(data.get('endpoint', getattr(obj, 'endpoint', '')), '地址', limit=1024).rstrip('/')
parsed = urlsplit(endpoint)
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValidationError('解析服务地址无效')
obj = obj or AIParserResource(workspace_id=workspace, owner_id=user.id)
obj.name = text(data.get('name', obj.name), '名称', limit=128)
obj.endpoint = endpoint
if 'api_key' in data:
from common.utils.rsa_util import rsa_long_encrypt
key = text(data['api_key'], '密钥', required=False, limit=4096)
obj.credential = rsa_long_encrypt(key) if key else ''
enabled = data.get('enabled', obj.enabled)
if not isinstance(enabled, bool):
raise ValidationError('启用状态无效')
obj.enabled = enabled
if 'allowed_users' in data:
obj.allowed_users = users(data['allowed_users'])
options = data.get('options', obj.options)
from system_manage.parsers.catalog import validate_options
obj.options = validate_options(options, endpoint)
obj.save()
return obj
def parser_test(parser):
"""Probe the registered service API, without submitting files or returning service content."""
import time
import requests
from urllib.parse import urlunsplit
from common.utils.rsa_util import rsa_long_decrypt
parsed = urlsplit(parser.endpoint.rstrip('/'))
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password:
raise ValidationError('解析服务地址无效')
base_path = parsed.path
if parser.options.get('protocol') == 'v1':
if base_path.endswith('/v1'):
base_path = base_path[:-3]
url = urlunsplit((parsed.scheme, parsed.netloc, base_path + '/openapi.json', '', ''))
headers = {'Authorization': 'Bearer ' + rsa_long_decrypt(parser.credential)} if parser.credential else {}
started = time.monotonic()
try:
response = requests.get(url, headers=headers, timeout=(3, 7), allow_redirects=False)
if response.status_code != 200:
raise ValidationError(f'连接测试失败(HTTP {response.status_code})')
data = response.json()
except requests.RequestException as exc:
raise ValidationError('解析服务连接失败或超时') from exc
except ValueError as exc:
raise ValidationError('解析服务未返回有效接口定义') from exc
paths = data.get('paths') if isinstance(data, dict) else None
v1 = parser.options.get('protocol') == 'v1'
required = ('/v1/uploads', '/v1/parse/jobs') if v1 else ('/file_parse',)
if not isinstance(paths, dict) or not all(any(path.endswith(suffix) and 'post' in methods
for path, methods in paths.items() if isinstance(methods, dict)) for suffix in required):
raise ValidationError('服务接口与所选 MinerU 版本不匹配')
# Existence of the API does not prove that a local GPU/model backend is ready.
return {'connected': True, 'elapsed_ms': round((time.monotonic() - started) * 1000),
'api_version': data.get('info', {}).get('version', ''), 'message': '解析接口连接正常'}
def validate_nodes(workspace, user, nodes):
if not isinstance(nodes, list) or not 1 <= len(nodes) <= 3:
raise ValidationError('请选择处理节点')
types = [n.get('type') for n in nodes if isinstance(n, dict)]
if len(types) != len(nodes) or types[-1] != 'render' or len(set(types)) != len(types):
raise ValidationError('流程须以导图生成为终点,节点不可重复')
if types != [t for t in ('parse', 'organize', 'render') if t in types]:
raise ValidationError('节点顺序应为解析、整理、导图生成')
result = []
for node in nodes:
kind = node['type']
clean = {'type': kind}
if kind == 'parse':
if node.get('processor') == 'builtin':
result.append({'type': 'parse', 'processor': 'builtin'})
continue
parser = one('parsers', node.get('resource_id'), workspace, user, lock=connection.in_atomic_block)
require_use(user, parser)
if not parser.enabled:
raise ValidationError('解析服务已停用')
clean['resource_id'] = str(parser.id)
if kind == 'organize':
clean['model_id'] = str(model_for(workspace, user, node.get('model_id')).id)
clean['prompt'] = text(node.get('prompt', '保留事实、数值和原文语言,将以下文档整理成分级Markdown标题和要点。'), '提示词', limit=16000)
temperature = node.get('temperature')
if temperature is not None:
if isinstance(temperature, bool) or not isinstance(temperature, (int, float)) or not 0 <= temperature <= 2:
raise ValidationError('温度无效')
clean['temperature'] = temperature
# Absent parameters fall back to the per-model settings in model management.
for field, low, high in (
('context_tokens', 4096, 262144), ('output_tokens', 256, 32768),
('safety_tokens', 256, 8192), ('timeout', 30, 600)):
value = node.get(field)
if value is not None:
clean[field] = integer(value, low, high, '模型参数')
if clean.get('output_tokens', 4096) + clean.get('safety_tokens', 1024) >= clean.get('context_tokens', 32768):
raise ValidationError('输出与预留长度不能超过模型上下文')
result.append(clean)
return result
@transaction.atomic
def flow_create(workspace, user, data):
nodes = validate_nodes(workspace, user, data.get('nodes'))
# Every save is immutable; published services always reference a fixed row.
previous = one('flows', data['previous_id'], workspace, user, edit=True, lock=True) if data.get('previous_id') else None
return AIFlow.objects.create(workspace_id=workspace, owner_id=user.id,
name=text(data.get('name'), '名称', limit=128), nodes=nodes,
revision=previous.revision + 1 if previous else 1)
@transaction.atomic
def service_create(workspace, user, data):
require_admin(user)
flow = one('flows', data.get('flow_id'), workspace, user, lock=True)
validate_nodes(workspace, user, flow.nodes)
return AIService.objects.create(workspace_id=workspace, owner_id=user.id,
name=text(data.get('name'), '名称', limit=128), flow=flow,
allowed_users=users(data.get('allowed_users', [])),
requests_per_minute=integer(data.get('requests_per_minute', 20), 1, 600, '调用频率'))
def make_snapshot(workspace, user, nodes):
clean = validate_nodes(workspace, user, nodes)
for node in clean:
if node['type'] == 'parse':
if node.get('processor') == 'builtin':
continue
parser = one('parsers', node['resource_id'], workspace, user)
node['options'] = dict(parser.options)
node['resource_version'] = parser.updated_at.isoformat()
if node['type'] == 'organize':
model = model_for(workspace, user, node['model_id'])
node.update(model_name=model.model_name, provider=model.provider, resource_version=model.update_time.isoformat())
return clean
@transaction.atomic
def submit(workspace, user, data, upload=None, service=None, request=None):
from users.models import User
current_user = User.objects.select_for_update().get(id=user.id)
if not current_user.is_active:
raise PermissionDenied('用户已停用')
if AITask.objects.filter(owner_id=user.id, status__in=['PENDING', 'RUNNING']).count() >= 10:
raise ValidationError('待处理任务已达上限')
if service:
service = one('services', service.pk, workspace, user, lock=True)
require_use(user, service)
if not service.enabled:
raise ValidationError('服务已停用')
nodes = service.flow.nodes
else:
nodes = one('flows', data['flow_id'], workspace, user, lock=True).nodes if data.get('flow_id') else data.get('nodes')
snapshot = make_snapshot(workspace, user, nodes)
from system_manage.access_control import enforce_task
enforce_task(request, service.id if service else None, snapshot)
markdown = text(data.get('markdown', ''), '文档内容', required=False, limit=MAX_INLINE_TEXT)
if upload and upload.size > MAX_FILE:
raise ValidationError('文件不能超过20MB')
if upload and snapshot[0]['type'] != 'parse':
raise ValidationError('文件任务需要解析节点')
if not upload and snapshot[0]['type'] == 'parse':
raise ValidationError('请选择文件')
if not upload and not markdown.strip():
raise ValidationError('文档内容不能为空')
from system_manage.ai_hub_assets import asset_lock, normalize
with asset_lock():
markdown = text(normalize(markdown, workspace, user), '文档内容', required=False)
return AITask.objects.create(workspace_id=workspace, owner_id=user.id,
name=text(data.get('name') or (upload.name if upload else '导图任务'), '名称', limit=128), service=service,
snapshot={'nodes': snapshot, 'flow_id': str(service.flow_id) if service else data.get('flow_id'),
'flow_revision': service.flow.revision if service else None},
input_data={'markdown': markdown}, file_name=upload.name[:255] if upload else '',
file_data=upload.read() if upload else None)
@transaction.atomic
def artifact_save(workspace, user, data, obj=None):
if obj:
obj = AIArtifact.objects.select_for_update().get(pk=obj.pk)
if data.get('revision') != obj.revision:
raise ValidationError('内容已更新,请重新打开')
history = list(obj.history)
if len(history) >= 30:
raise ValidationError('修订已达30次,请另存为新图谱')
history.append({'revision': obj.revision, 'markdown': obj.markdown, 'layout': obj.layout,
'operator': str(user.id), 'updated_at': obj.updated_at.isoformat()})
obj.history = history
obj.revision += 1
else:
task = one('tasks', data['task_id'], workspace, user, lock=True) if data.get('task_id') else None
if task and task.status != 'SUCCESS':
raise ValidationError('任务尚未成功')
obj = AIArtifact(workspace_id=workspace, owner_id=user.id, task=task,
original=task.result.get('original', '') if task else text(data.get('original', ''), '原始内容', False, MAX_INLINE_TEXT))
obj.name = text(data.get('name'), '名称', limit=128)
obj.markdown = text(data.get('markdown'), '修订内容', limit=MAX_INLINE_TEXT)
obj.layout = data.get('layout', 'tree')
if obj.layout not in ('tree', 'radial', 'horizontal', 'vertical'):
raise ValidationError('布局无效')
from system_manage.ai_hub_assets import asset_lock, normalize
with asset_lock():
obj.markdown = text(normalize(obj.markdown, workspace, user), '修订内容')
obj.original = text(normalize(obj.original, workspace, user), '原始内容', required=False)
for entry in obj.history:
entry['markdown'] = normalize(entry.get('markdown', ''), workspace, user)
obj.save()
return obj
@transaction.atomic
def delete_record(kind, pk, workspace, user):
obj = one(kind, pk, workspace, user, edit=True, lock=True)
if kind == 'parsers':
reference = [{'type': 'parse', 'resource_id': str(obj.id)}]
if AIFlow.objects.filter(workspace_id=workspace, nodes__contains=reference).exists():
raise ValidationError('解析服务已被流程引用,请先删除相关流程')
if AITask.objects.filter(workspace_id=workspace, status__in=['PENDING', 'RUNNING'],
snapshot__nodes__contains=reference).exists():
raise ValidationError('解析服务有未完成任务,请稍后删除')
elif kind == 'flows':
if AIService.objects.filter(flow=obj).exists():
raise ValidationError('流程已被服务引用,请先删除相关服务')
elif kind == 'services':
if AITask.objects.filter(service=obj, status__in=['PENDING', 'RUNNING']).exists():
raise ValidationError('服务有未完成任务,请稍后删除')
elif kind == 'tasks':
if obj.status in ('PENDING', 'RUNNING'):
raise ValidationError('待处理或运行中的任务不能删除')
elif kind != 'artifacts':
raise ValidationError('资源类型无效')
# Historical task snapshots and saved artifacts remain independent records.
resource_type = {'parsers': 'PARSER', 'services': 'SERVICE'}.get(kind)
if resource_type:
from system_manage.models.platform_access import PlatformGrant
PlatformGrant.objects.filter(workspace_id=workspace, resource_type=resource_type,
target=str(obj.id)).delete()
obj.delete()
def parse_file(parser, name, content, options=None, progress_callback=None):
import requests
from common.utils.rsa_util import rsa_long_decrypt
opts = options if options is not None else parser.options
headers = {'Authorization': 'Bearer ' + rsa_long_decrypt(parser.credential)} if parser.credential else {}
from system_manage.parsers import parse
return parse(parser, name, content, opts, headers, progress_callback=progress_callback)
def markdown_tree(markdown):
"""Markdown转稳定ID结构树:标题层级、嵌套列表、表格;围栏内容不参与结构。"""
import re
root = {'id': 'root', 'text': '文档', 'children': []}
heading_stack = [(0, root)]
list_stack = []
fence = None
table_buffer, table_start = [], None
def container():
return list_stack[-1][1] if list_stack else heading_stack[-1][1]
def flush_table():
nonlocal table_buffer, table_start
if not table_buffer:
return
index, lines = table_start, table_buffer
table_buffer, table_start = [], None
def cells(raw):
return [cell.strip() for cell in raw.strip().strip('|').split('|')]
if len(lines) >= 2 and re.match(r'^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$', lines[1]):
headers = cells(lines[0])
aligns = []
for cell in cells(lines[1]):
left, right = cell.startswith(':'), cell.endswith(':')
aligns.append('center' if left and right else 'right' if right else 'left')
rows = [cells(raw) for raw in lines[2:]]
node = {'id': f'n{index}', 'type': 'table', 'text': '表格:' + '、'.join(headers),
'table': {'headers': headers, 'aligns': aligns, 'rows': rows,
'row_count': len(rows), 'column_count': len(headers)},
'children': []}
container()['children'].append(node)
else:
for offset, raw in enumerate(lines):
container()['children'].append({'id': f'n{index + offset}', 'text': raw.strip(), 'children': []})
list_pattern = re.compile(r'^(\s*)(?:([-*+])|(\d{1,9})[.)])\s+(.+)$')
for index, line in enumerate(markdown.splitlines()):
fence_match = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
if fence_match:
token = fence_match.group(1)
if fence is None:
fence = token
flush_table()
list_stack.clear()
elif token[0] == fence[0] and len(token) >= len(fence):
fence = None
continue
if fence:
continue
stripped = line.strip()
if stripped.startswith('|') and stripped.count('|') >= 2:
if table_start is None:
table_start = index
list_stack.clear()
table_buffer.append(line)
continue
flush_table()
if not stripped:
continue
heading = re.match(r'^\s{0,3}(#{1,6})\s+(.+)', line)
if heading:
level = len(heading.group(1))
list_stack.clear()
while heading_stack[-1][0] >= level:
heading_stack.pop()
node = {'id': f'n{index}', 'text': heading.group(2).rstrip('# ').strip(), 'children': []}
heading_stack[-1][1]['children'].append(node)
heading_stack.append((level, node))
continue
item = list_pattern.match(line)
if item:
indent = len(item.group(1).expandtabs(4))
while list_stack and list_stack[-1][0] >= indent:
list_stack.pop()
ordered = item.group(3)
node = {'id': f'n{index}', 'type': 'list-item',
'text': item.group(4).strip(),
'list': {'type': 'ol' if ordered else 'ul', 'index': int(ordered) if ordered else None},
'children': []}
container()['children'].append(node)
list_stack.append((indent, node))
continue
if line[:1].isspace() and list_stack:
list_stack[-1][1]['children'].append({'id': f'n{index}', 'text': stripped, 'children': []})
continue
list_stack.clear()
heading_stack[-1][1]['children'].append({'id': f'n{index}', 'text': stripped, 'children': []})
flush_table()
return root