Files
syops/backend/app/services/admin/agent_service.py
T

291 lines
11 KiB
Python

"""
backend/app/services/admin/agent_service.py
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
依赖:models、DifyService、Config、requests。
逻辑:由 api/admin/agents.py 调用。
"""
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 NotFoundError, ValidationError
from app.models import Agent, User
from app.services.dify import DifyService
def serialize_agent(agent: Agent) -> dict:
"""Agent ORM → 管理端列表 JSON。"""
return {
'id': agent.id,
'name': agent.name,
'dify_app_id': agent.dify_app_id,
'dify_api_key': agent.dify_api_key,
'is_active': agent.is_active,
'description': agent.description,
'type': agent.type,
'api_base_url': agent.api_base_url,
'extra_config': agent.extra_config,
}
def list_agents() -> list[dict]:
"""返回全部 Agent(按 id 升序)。"""
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
return [serialize_agent(a) for a in agents]
def create_agent(data: dict[str, Any]) -> dict:
"""
创建 Agent。
Returns:
{ id }。
Raises:
ValidationError: name 缺失或 API 类型缺少 dify_app_id。
"""
if not data.get('name'):
raise ValidationError('Name is required')
agent_type = data.get('type', 'api')
if agent_type == 'api' and (not data.get('dify_app_id')):
raise ValidationError('App ID is required for API agents')
agent = Agent(
name=data['name'],
dify_app_id=data.get('dify_app_id') or None,
dify_api_key=data.get('dify_api_key') or None,
description=data.get('description'),
type=agent_type,
api_base_url=data.get('api_base_url'),
extra_config=data.get('extra_config'),
is_active=data.get('is_active', True),
)
db.session.add(agent)
db.session.commit()
return {'id': agent.id}
def update_agent(agent_id: int, data: dict[str, Any]) -> None:
"""更新 Agent 字段;dify_api_key 仅在非空时覆盖。"""
agent = db.session.get(Agent, agent_id)
if not agent:
raise NotFoundError('Not found')
for key in ['name', 'dify_app_id', 'description', 'type', 'api_base_url', 'extra_config', 'is_active']:
if key in data:
setattr(agent, key, data[key])
if data.get('dify_api_key'):
agent.dify_api_key = data['dify_api_key']
db.session.commit()
def delete_agent(agent_id: int) -> None:
"""删除 Agent(不存在时静默成功)。"""
agent = db.session.get(Agent, agent_id)
if agent:
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。
Returns:
passed、request_url、output_info、analysis、http_status、tested_at 等。
Raises:
NotFoundError: Agent 不存在。
"""
agent = db.session.get(Agent, agent_id)
if not agent:
raise NotFoundError('Not found')
tested_at = datetime.utcnow().isoformat()
if 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 = (agent.extra_config or {}).get('iframe_url')
if not iframe_url:
return {
'passed': False,
'request_url': '',
'output_info': 'Missing iframe_url in extra_config.',
'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,
}
extra_config = agent.extra_config or {}
dify_app_type = str(extra_config.get('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)。
Raises:
NotFoundError: Agent 不存在。
"""
agent = db.session.get(Agent, agent_id)
if not agent:
raise NotFoundError('Not found')
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()