"""Seed agents for freight shipping notice Chatflow orchestration.""" import sqlalchemy as sa from app import create_app, db from app.models import Agent from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME app = create_app() CHAT_DESCRIPTION = "货代发货通知智能体:自然语言驱动解析、库存匹配、Excel 生成与货代上传(Tool 编排)" def _normalize_url(raw: str | None) -> str | None: if raw is None: return None text = str(raw).strip() if not text: return None if (text.startswith("`") and text.endswith("`")) or (text.startswith('"') and text.endswith('"')): text = text[1:-1].strip() return text or None def _ensure_pg_sequence(table: str, pk: str) -> None: engine_name = db.engine.dialect.name if engine_name != "postgresql": return if not table.replace("_", "").isalnum() or not pk.replace("_", "").isalnum(): raise ValueError("invalid identifier") sql = sa.text( f"SELECT setval(pg_get_serial_sequence(:tbl, :pk), COALESCE((SELECT MAX({pk}) FROM {table}), 0), true)" ) db.session.execute(sql, {"tbl": table, "pk": pk}) db.session.commit() def _upsert_agent( *, name: str, description: str, dify_app_type: str, dify_app_id: str | None = None, dify_api_key: str | None = None, api_base_url: str | None = None, ): agent = Agent.query.filter_by(name=name).first() extra_config = {"dify_app_type": dify_app_type} if not agent: agent = Agent( name=name, description=description, type="api", dify_app_id=dify_app_id, dify_api_key=dify_api_key, api_base_url=api_base_url, extra_config=extra_config, is_active=True, ) db.session.add(agent) print(f"Created agent: {name}") else: agent.description = description agent.type = "api" agent.extra_config = extra_config if dify_app_id: agent.dify_app_id = dify_app_id if dify_api_key: agent.dify_api_key = dify_api_key if api_base_url: agent.api_base_url = api_base_url agent.is_active = True print(f"Updated agent: {name}") return agent if __name__ == "__main__": import os with app.app_context(): _ensure_pg_sequence("agents", "id") chat_key = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_API_KEY") or os.getenv("DIFY_API_KEY") chat_base = _normalize_url(os.getenv("SHIPPING_NOTICE_CHAT_DIFY_BASE") or os.getenv("DIFY_API_BASE")) _upsert_agent( name=CHAT_AGENT_NAME, description=CHAT_DESCRIPTION, dify_app_type="chatflow", dify_app_id=os.getenv("SHIPPING_NOTICE_CHAT_DIFY_APP_ID"), dify_api_key=chat_key, api_base_url=chat_base, ) db.session.commit() print("Shipping notice agents seeded.")