387 lines
17 KiB
Python
387 lines
17 KiB
Python
"""
|
||
backend/app/services/admin/agent_service.py
|
||
|
||
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
|
||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization。
|
||
逻辑:由 api/admin/agents.py 调用;创建/更新写入 Registry 结构化列并清理 extra 已迁移键。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
import requests
|
||
|
||
from app import db
|
||
from app.core.config.settings import Config
|
||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||
from app.models import Agent, AgentRuntimeBinding, ShippingOrderExtractionRun, User
|
||
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
|
||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
|
||
from app.services.agent_registry.catalog_loader import get_dify_required_providers
|
||
from app.services.agent_registry.serialization import serialize_agent_for_admin
|
||
from app.services.dify import DifyService
|
||
|
||
|
||
def serialize_agent(agent: Agent) -> dict:
|
||
"""Agent ORM → 管理端列表 JSON。"""
|
||
return serialize_agent_for_admin(agent)
|
||
|
||
|
||
def list_agents(*, scope: str | None = None) -> list[dict]:
|
||
"""按管理域返回 Agent;scope=applications/executors,缺省返回全部兼容旧客户端。"""
|
||
query = db.session.query(Agent)
|
||
if scope == 'applications':
|
||
query = query.filter(Agent.exposure_mode == 'workspace')
|
||
elif scope == 'executors':
|
||
query = query.filter(Agent.exposure_mode == 'internal')
|
||
elif scope not in (None, ''):
|
||
raise ValidationError(
|
||
'Invalid agent management scope',
|
||
code='AGENT.ADMIN_SCOPE_INVALID',
|
||
details={'scope': scope},
|
||
)
|
||
agents = query.order_by(Agent.id.asc()).all()
|
||
return [serialize_agent(a) for a in agents]
|
||
|
||
|
||
def create_agent(data: dict[str, Any]) -> dict:
|
||
"""
|
||
创建 Agent 并写入 Registry 结构化列。
|
||
|
||
Returns:
|
||
{ id }。
|
||
|
||
Raises:
|
||
ValidationError: 字段校验失败。
|
||
"""
|
||
normalized = validate_agent_payload(data)
|
||
if not normalized.get('dify_api_key') and normalized.get('runtime_provider') in get_dify_required_providers():
|
||
raise ValidationError('dify_api_key 为必填项')
|
||
|
||
agent = Agent(name=normalized['name'], is_active=normalized['is_active'])
|
||
if isinstance(data.get('extra_config'), dict):
|
||
normalized['extra_config'] = data['extra_config']
|
||
else:
|
||
normalized['extra_config'] = {}
|
||
apply_agent_payload(agent, normalized)
|
||
|
||
db.session.add(agent)
|
||
db.session.flush()
|
||
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
|
||
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
|
||
runtime_binding = data.get('order_extraction_runtime_binding')
|
||
if runtime_binding is not None:
|
||
if not isinstance(runtime_binding, dict):
|
||
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
|
||
try:
|
||
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
|
||
except (TypeError, ValueError) as exc:
|
||
raise ValidationError('provider_agent_id is required') from exc
|
||
from app.services.agent_runtime_binding_service import save_runtime_binding
|
||
|
||
save_runtime_binding(
|
||
owner_agent_id=agent.id,
|
||
capability_code='shipping.order_extraction',
|
||
provider_agent_id=provider_agent_id,
|
||
enabled=runtime_binding.get('enabled') is not False,
|
||
config=runtime_binding.get('config'),
|
||
commit=False,
|
||
)
|
||
db.session.commit()
|
||
return {'id': agent.id}
|
||
|
||
|
||
def _pick_update_value(data: dict[str, Any], key: str, current: Any) -> Any:
|
||
"""区分 PATCH 未传字段与显式 null。"""
|
||
return data[key] if key in data else current
|
||
|
||
|
||
def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||
"""更新 Agent Registry 结构化列并清理 extra 已迁移键。"""
|
||
agent = db.session.get(Agent, agent_id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
|
||
merged = {
|
||
'name': data.get('name', agent.name),
|
||
'description': data.get('description', agent.description),
|
||
'icon_url': data.get('icon_url', agent.icon_url),
|
||
'is_active': data.get('is_active', agent.is_active),
|
||
'dify_app_id': data.get('dify_app_id', agent.dify_app_id),
|
||
'api_base_url': data.get('api_base_url', agent.api_base_url),
|
||
'agent_code': data.get('agent_code', agent.agent_code),
|
||
'runtime_provider': data.get('runtime_provider', agent.runtime_provider),
|
||
'conversation_mode': data.get('conversation_mode', agent.conversation_mode),
|
||
'dify_app_type': data.get('dify_app_type', agent.dify_app_type),
|
||
'exposure_mode': data.get('exposure_mode', agent.exposure_mode),
|
||
'iframe_url': data.get('iframe_url', agent.iframe_url),
|
||
'category': data.get('category', agent.category),
|
||
'sub_category': data.get('sub_category', agent.sub_category),
|
||
'sort_order': data.get('sort_order', agent.sort_order),
|
||
'welcome_message': data.get('welcome_message', agent.welcome_message),
|
||
'suggested_questions_style': data.get('suggested_questions_style', agent.suggested_questions_style),
|
||
'suggested_questions': data.get('suggested_questions', agent.suggested_questions),
|
||
'capabilities': data.get('capabilities', agent.capabilities),
|
||
'file_upload_policy': data.get('file_upload_policy', agent.file_upload_policy),
|
||
'bound_schedule_task_id': data.get('bound_schedule_task_id', agent.bound_schedule_task_id),
|
||
'handler_config': _pick_update_value(data, 'handler_config', agent.handler_config),
|
||
'extra_config': _pick_update_value(data, 'extra_config', agent.extra_config),
|
||
'is_aggregate': data.get('is_aggregate', agent.is_aggregate),
|
||
}
|
||
if data.get('dify_api_key'):
|
||
merged['dify_api_key'] = data['dify_api_key']
|
||
|
||
normalized = validate_agent_payload(merged, agent=agent, provided_fields=frozenset(data.keys()))
|
||
apply_agent_payload(agent, normalized)
|
||
if 'directory_member_ids' in data or 'is_aggregate' in data:
|
||
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
|
||
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
|
||
runtime_binding = data.get('order_extraction_runtime_binding')
|
||
if runtime_binding is not None:
|
||
if not isinstance(runtime_binding, dict):
|
||
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
|
||
try:
|
||
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
|
||
except (TypeError, ValueError) as exc:
|
||
raise ValidationError('provider_agent_id is required') from exc
|
||
from app.services.agent_runtime_binding_service import save_runtime_binding
|
||
|
||
save_runtime_binding(
|
||
owner_agent_id=agent.id,
|
||
capability_code='shipping.order_extraction',
|
||
provider_agent_id=provider_agent_id,
|
||
enabled=runtime_binding.get('enabled') is not False,
|
||
config=runtime_binding.get('config'),
|
||
commit=False,
|
||
)
|
||
db.session.commit()
|
||
|
||
|
||
def delete_agent(agent_id: int) -> None:
|
||
"""删除 Agent;被能力绑定或历史订单抽取 Run 引用时明确阻断。"""
|
||
agent = db.session.get(Agent, agent_id)
|
||
if agent:
|
||
binding_count = AgentRuntimeBinding.query.filter(
|
||
(AgentRuntimeBinding.owner_agent_id == agent.id)
|
||
| (AgentRuntimeBinding.provider_agent_id == agent.id)
|
||
).count()
|
||
run_count = ShippingOrderExtractionRun.query.filter(
|
||
(ShippingOrderExtractionRun.owner_agent_id == agent.id)
|
||
| (ShippingOrderExtractionRun.provider_agent_id == agent.id)
|
||
).count()
|
||
if binding_count or run_count:
|
||
raise ConflictError(
|
||
'Agent is referenced by runtime capability history',
|
||
code='AGENT.RUNTIME_PROVIDER_DELETE_BLOCKED',
|
||
details={'binding_count': binding_count, 'run_count': run_count},
|
||
)
|
||
db.session.delete(agent)
|
||
db.session.commit()
|
||
|
||
|
||
def test_agent_connectivity(agent_id: int) -> dict[str, Any]:
|
||
"""
|
||
测试 Agent 连通性(iframe GET 或 Dify chatflow/workflow POST)。
|
||
核心逻辑:通过则可选自动 is_active=True。
|
||
"""
|
||
agent = db.session.get(Agent, agent_id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
tested_at = datetime.utcnow().isoformat()
|
||
if agent.runtime_provider == 'iframe' or agent.type == 'iframe':
|
||
return _test_iframe_agent(agent, tested_at)
|
||
return _test_dify_agent(agent, tested_at)
|
||
|
||
|
||
def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||
iframe_url = str(agent.iframe_url or '').strip()
|
||
if not iframe_url:
|
||
return {
|
||
'passed': False,
|
||
'request_url': '',
|
||
'output_info': 'Missing iframe_url column.',
|
||
'analysis': '测试失败:未配置 iframe URL。',
|
||
'http_status': 0,
|
||
'tested_at': tested_at,
|
||
}
|
||
try:
|
||
resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True)
|
||
passed = 200 <= resp.status_code < 400
|
||
if passed and (not agent.is_active):
|
||
agent.is_active = True
|
||
db.session.commit()
|
||
return {
|
||
'passed': passed,
|
||
'request_url': iframe_url,
|
||
'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}',
|
||
'analysis': '测试通过:iframe 地址可访问。' if passed else '测试失败:iframe 地址不可访问或返回异常状态。',
|
||
'http_status': resp.status_code,
|
||
'tested_at': tested_at,
|
||
}
|
||
except requests.RequestException as exc:
|
||
return {
|
||
'passed': False,
|
||
'request_url': iframe_url,
|
||
'output_info': str(exc),
|
||
'analysis': '测试失败:请求 iframe 地址异常。',
|
||
'http_status': 0,
|
||
'tested_at': tested_at,
|
||
}
|
||
|
||
|
||
def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||
if not agent.dify_api_key:
|
||
return {
|
||
'passed': False,
|
||
'request_url': '',
|
||
'output_info': 'Missing dify_api_key.',
|
||
'analysis': '测试失败:未配置 API Key。',
|
||
'http_status': 0,
|
||
'tested_at': tested_at,
|
||
}
|
||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||
if not base_url:
|
||
return {
|
||
'passed': False,
|
||
'request_url': '',
|
||
'output_info': 'Missing api_base_url.',
|
||
'analysis': '测试失败:未配置 API Base URL。',
|
||
'http_status': 0,
|
||
'tested_at': tested_at,
|
||
}
|
||
dify_app_type = str(agent.dify_app_type or 'chatflow').strip().lower()
|
||
if dify_app_type not in ('chatflow', 'workflow'):
|
||
dify_app_type = 'chatflow'
|
||
if dify_app_type == 'workflow':
|
||
request_url = DifyService._build_workflow_url(base_url)
|
||
payload = {
|
||
'inputs': {'query': '系统连通性测试,请简短回复OK。'},
|
||
'response_mode': 'blocking',
|
||
'user': 'admin_test',
|
||
}
|
||
else:
|
||
request_url = DifyService._build_chat_messages_url(base_url)
|
||
payload = {
|
||
'inputs': {},
|
||
'query': '系统连通性测试,请简短回复OK。',
|
||
'response_mode': 'blocking',
|
||
'user': 'admin_test',
|
||
}
|
||
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
|
||
try:
|
||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||
raw_text = (resp.text or '')[:4000]
|
||
output_info = raw_text
|
||
passed = False
|
||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
|
||
passed = True
|
||
analysis = '测试通过:Workflow 接口可访问且认证通过。'
|
||
try:
|
||
data = resp.json()
|
||
if dify_app_type == 'workflow':
|
||
passed, output_info, analysis = _parse_workflow_test_response(resp, data, output_info, analysis)
|
||
else:
|
||
passed, output_info, analysis = _parse_chatflow_test_response(resp, data, output_info, analysis, passed)
|
||
except ValueError:
|
||
if resp.ok and raw_text.strip():
|
||
passed = True
|
||
analysis = (
|
||
'测试通过:Workflow 接口可访问并返回了文本内容。'
|
||
if dify_app_type == 'workflow'
|
||
else '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||
)
|
||
if passed and (not agent.is_active):
|
||
agent.is_active = True
|
||
db.session.commit()
|
||
return {
|
||
'passed': passed,
|
||
'dify_app_type': dify_app_type,
|
||
'request_url': request_url,
|
||
'output_info': output_info,
|
||
'analysis': analysis,
|
||
'http_status': resp.status_code,
|
||
'tested_at': tested_at,
|
||
}
|
||
except requests.RequestException as exc:
|
||
return {
|
||
'passed': False,
|
||
'dify_app_type': dify_app_type,
|
||
'request_url': request_url,
|
||
'output_info': str(exc),
|
||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||
'http_status': 0,
|
||
'tested_at': tested_at,
|
||
}
|
||
|
||
|
||
def _parse_workflow_test_response(resp, data, output_info: str, analysis: str) -> tuple[bool, str, str]:
|
||
passed = 200 <= resp.status_code < 300
|
||
workflow_data = data.get('data') if isinstance(data, dict) else None
|
||
outputs = workflow_data.get('outputs') if isinstance(workflow_data, dict) else None
|
||
status = workflow_data.get('status') if isinstance(workflow_data, dict) else None
|
||
message = data.get('message') if isinstance(data, dict) else None
|
||
if isinstance(outputs, dict) and outputs:
|
||
output_info = str(outputs)[:4000]
|
||
elif isinstance(message, str) and message.strip():
|
||
output_info = message[:4000]
|
||
elif isinstance(data, dict):
|
||
output_info = str(data)[:4000]
|
||
if resp.ok and status in ('succeeded', 'success'):
|
||
analysis = '测试通过:Workflow 接口可访问且业务返回成功。'
|
||
elif resp.ok:
|
||
analysis = '测试通过:Workflow 接口可访问且认证通过(本次未返回业务成功状态)。'
|
||
return passed, output_info, analysis
|
||
|
||
|
||
def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, passed: bool) -> tuple[bool, str, str]:
|
||
answer = data.get('answer') if isinstance(data, dict) else None
|
||
if answer:
|
||
output_info = str(answer)[:4000]
|
||
if resp.ok and isinstance(answer, str) and answer.strip():
|
||
passed = True
|
||
analysis = '测试通过:Chatflow 接口可访问且已返回回答。'
|
||
elif resp.ok:
|
||
analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。'
|
||
else:
|
||
message = data.get('message') if isinstance(data, dict) else None
|
||
if message:
|
||
output_info = str(message)[:4000]
|
||
return passed, output_info, analysis
|
||
|
||
|
||
def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||
"""将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。"""
|
||
agent = db.session.get(Agent, agent_id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
if agent.exposure_mode == 'internal' and user_ids:
|
||
raise ValidationError(
|
||
'内部执行器不可授予用户权限',
|
||
code='AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN',
|
||
)
|
||
current_users = db.session.query(User).filter(User.agents.contains(agent)).all()
|
||
current_user_ids = {u.id for u in current_users}
|
||
new_user_ids = set(user_ids)
|
||
to_add = new_user_ids - current_user_ids
|
||
if to_add:
|
||
users_to_add = db.session.query(User).filter(User.id.in_(to_add)).all()
|
||
for user in users_to_add:
|
||
user.agents.append(agent)
|
||
to_remove = current_user_ids - new_user_ids
|
||
if to_remove:
|
||
users_to_remove = db.session.query(User).filter(User.id.in_(to_remove)).all()
|
||
for user in users_to_remove:
|
||
user.agents.remove(agent)
|
||
db.session.commit()
|
||
|
||
|
||
def import_training_question_bank_from_pdf(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||
"""解析指定 Agent 的培训试题 PDF,并返回结构化题库。"""
|
||
agent = db.session.get(Agent, agent_id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
return parse_training_question_bank_from_guide(agent_id=agent_id, guide_id=guide_id)
|