feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持
This commit is contained in:
1 parent
ac4262cd75
commit
c8ce77199e
183 files changed
+11690
-2300
No files matched your search
@@ -2,8 +2,8 @@
|
||||
backend/app/services/admin/agent_service.py
|
||||
|
||||
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
|
||||
依赖:models、DifyService、Config、requests。
|
||||
逻辑:由 api/admin/agents.py 调用。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization。
|
||||
逻辑:由 api/admin/agents.py 调用;创建/更新写入 Registry 结构化列并清理 extra 已迁移键。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -16,23 +16,16 @@ 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
|
||||
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 {
|
||||
'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,
|
||||
}
|
||||
return serialize_agent_for_admin(agent)
|
||||
|
||||
|
||||
def list_agents() -> list[dict]:
|
||||
@@ -43,42 +36,70 @@ def list_agents() -> list[dict]:
|
||||
|
||||
def create_agent(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建 Agent。
|
||||
创建 Agent 并写入 Registry 结构化列。
|
||||
|
||||
Returns:
|
||||
{ id }。
|
||||
|
||||
Raises:
|
||||
ValidationError: name 缺失或 API 类型缺少 dify_app_id。
|
||||
ValidationError: 字段校验失败。
|
||||
"""
|
||||
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),
|
||||
)
|
||||
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.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 字段;dify_api_key 仅在非空时覆盖。"""
|
||||
"""更新 Agent Registry 结构化列并清理 extra 已迁移键。"""
|
||||
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])
|
||||
|
||||
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),
|
||||
'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),
|
||||
}
|
||||
if data.get('dify_api_key'):
|
||||
agent.dify_api_key = data['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)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -94,27 +115,23 @@ 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':
|
||||
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 = (agent.extra_config or {}).get('iframe_url')
|
||||
iframe_url = str(agent.iframe_url or '').strip()
|
||||
if not iframe_url:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing iframe_url in extra_config.',
|
||||
'output_info': 'Missing iframe_url column.',
|
||||
'analysis': '测试失败:未配置 iframe URL。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
@@ -164,8 +181,7 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
'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()
|
||||
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':
|
||||
@@ -267,11 +283,7 @@ def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, p
|
||||
|
||||
|
||||
def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
"""
|
||||
将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。
|
||||
Raises:
|
||||
NotFoundError: Agent 不存在。
|
||||
"""
|
||||
"""将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
@@ -292,11 +304,7 @@ def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
|
||||
|
||||
def import_training_question_bank_from_pdf(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
解析指定 Agent 的培训试题 PDF,并返回结构化题库。
|
||||
|
||||
用途:当前端点击“从试题 PDF 导入”时使用;这里只做解析,不直接覆盖 Agent 配置,避免误导入后无法人工复核。
|
||||
"""
|
||||
"""解析指定 Agent 的培训试题 PDF,并返回结构化题库。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
Reference in new issue
Block a user