Files
syops/backend/scripts/backfill_agent_registry.py
T

149 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
backend/scripts/backfill_agent_registry.py
用途:将存量 Agent 的 extra_config / type / 名称启发式回填至 agents 表结构化 Registry 列。
依赖:app.create_app、models.Agent、agent_registry.backfill_mapping.infer_registry_fields_from_legacy。
逻辑:运维 CLI;默认 dry-run;--agent-id 可单条处理;详见 docs/platform/agent_application_management_implementation.md §3.5。
Usage:
cd backend
python scripts/backfill_agent_registry.py --dry-run
python scripts/backfill_agent_registry.py
python scripts/backfill_agent_registry.py --agent-id 12
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any
BACKEND_ROOT = Path(__file__).resolve().parents[1]
if str(BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(BACKEND_ROOT))
from app import create_app # noqa: E402
from app.models import Agent # noqa: E402
from app.services.agent_registry.backfill_mapping import infer_registry_fields_from_legacy # noqa: E402
_REGISTRY_COLUMNS = (
'agent_code',
'runtime_provider',
'conversation_mode',
'dify_app_type',
'iframe_url',
'category',
'sub_category',
'sort_order',
'welcome_message',
'suggested_questions_style',
'suggested_questions',
'capabilities',
'file_upload_policy',
'bound_schedule_task_id',
'handler_config',
)
def _snapshot_agent(agent: Agent) -> dict[str, Any]:
"""提取 Agent 当前 Registry 相关字段,供 before/after 日志对比。"""
return {
column: getattr(agent, column, None)
for column in _REGISTRY_COLUMNS
}
def _apply_inferred_fields(agent: Agent, inferred: dict[str, Any]) -> dict[str, Any]:
"""
将推断结果写入 Agent 实例并返回变更摘要。
Returns:
仅含实际变更字段的 after 片段。
"""
changes: dict[str, Any] = {}
for column in _REGISTRY_COLUMNS:
if column not in inferred:
continue
new_value = inferred[column]
old_value = getattr(agent, column, None)
if old_value != new_value:
setattr(agent, column, new_value)
changes[column] = new_value
return changes
def backfill_agents(*, dry_run: bool = True, agent_id: int | None = None) -> list[dict[str, Any]]:
"""
回填 Agent Registry 结构化列。
Args:
dry_run: 为 True 时不 commit。
agent_id: 指定单条 Agent.id;None 时处理全部。
Returns:
每条 Agent 的 before/after 摘要列表。
"""
query = Agent.query.order_by(Agent.id.asc())
if agent_id is not None:
query = query.filter(Agent.id == agent_id)
rows = query.all()
summaries: list[dict[str, Any]] = []
for agent in rows:
before = _snapshot_agent(agent)
inferred = infer_registry_fields_from_legacy(agent)
after_changes = _apply_inferred_fields(agent, inferred)
summary = {
'agent_id': agent.id,
'name': agent.name,
'before': before,
'inferred': inferred,
'changed': after_changes,
}
summaries.append(summary)
if not dry_run and summaries:
from app.extensions import db
db.session.commit()
return summaries
def main() -> int:
"""CLI 入口:解析参数、执行回填并打印 JSON 摘要。"""
parser = argparse.ArgumentParser(description='Backfill Agent registry structured columns from legacy config.')
parser.add_argument('--dry-run', action='store_true', help='Preview changes without committing (default if --apply omitted).')
parser.add_argument('--apply', action='store_true', help='Persist changes to database.')
parser.add_argument('--agent-id', type=int, default=None, help='Process a single Agent.id.')
args = parser.parse_args()
dry_run = not args.apply
if args.dry_run:
dry_run = True
env = os.getenv('FLASK_ENV', 'production')
app = create_app(env)
with app.app_context():
summaries = backfill_agents(dry_run=dry_run, agent_id=args.agent_id)
print(json.dumps({
'dry_run': dry_run,
'count': len(summaries),
'agents': summaries,
}, ensure_ascii=False, indent=2, default=str))
if args.agent_id is not None and not summaries:
print(f'Agent id={args.agent_id} not found.', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())