- Add 2 new team templates: 教育培训团队 (4 roles) and 天工平台工程团队 (5 roles) - Fix orchestrator to support multi-template workflow types (remove hardcoded PM planner) - Add _resolve_planner_role() to auto-detect planner based on team.config.workflow - Add frontend buttons and API clients for new templates - Merge 14 preset roles from 3 template families in get_preset_roles() - Add creation guide and platform engineering usage docs Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1101 lines
46 KiB
Python
1101 lines
46 KiB
Python
"""
|
||
团队服务 — Team CRUD + 预置软件公司模板工厂
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import uuid
|
||
import logging
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
from sqlalchemy.orm import Session
|
||
from app.models.team import Team, TeamMember
|
||
from app.models.agent import Agent
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# 预置角色定义
|
||
PRESET_ROLES = {
|
||
"pm": {
|
||
"label": "项目经理",
|
||
"icon": "📋",
|
||
"description": "分析需求、分解任务、制定计划、协调团队",
|
||
},
|
||
"designer": {
|
||
"label": "UI/UX设计师",
|
||
"icon": "🎨",
|
||
"description": "设计用户流程、线框图、组件层级、视觉规范",
|
||
},
|
||
"developer": {
|
||
"label": "开发工程师",
|
||
"icon": "💻",
|
||
"description": "编写后端API、前端组件、业务逻辑、数据库设计",
|
||
},
|
||
"qa": {
|
||
"label": "测试工程师",
|
||
"icon": "🔍",
|
||
"description": "审查交付物、发现缺陷、验证验收标准、质量把关",
|
||
},
|
||
"devops": {
|
||
"label": "DevOps工程师",
|
||
"icon": "🚀",
|
||
"description": "部署配置、CI/CD、环境管理、健康检查",
|
||
},
|
||
}
|
||
|
||
# 教育培训团队角色定义
|
||
EDUCATION_ROLES = {
|
||
"curriculum_designer": {
|
||
"label": "课程设计师",
|
||
"icon": "📐",
|
||
"description": "设计课程体系、学习目标、知识模块、评估方法",
|
||
},
|
||
"instructor": {
|
||
"label": "主讲讲师",
|
||
"icon": "🎓",
|
||
"description": "授课讲解、制作课件、设计互动、辅导答疑",
|
||
},
|
||
"teaching_assistant": {
|
||
"label": "作业助教",
|
||
"icon": "✏️",
|
||
"description": "批改作业、学习辅导、进度跟踪、答疑反馈",
|
||
},
|
||
"academic_admin": {
|
||
"label": "教务管理",
|
||
"icon": "📋",
|
||
"description": "排课管理、学员管理、证书管理、运营支持",
|
||
},
|
||
}
|
||
|
||
# 天工平台工程团队角色定义
|
||
PLATFORM_ENGINEERING_ROLES = {
|
||
"fullstack_dev": {
|
||
"label": "全栈开发工程师",
|
||
"icon": "🏗️",
|
||
"description": "核心引擎维护、API开发、数据库迁移、Bug修复、代码审查",
|
||
},
|
||
"fe_ux_engineer": {
|
||
"label": "前端体验工程师",
|
||
"icon": "🎯",
|
||
"description": "工作流编辑器优化、移动端适配、交互打磨、飞书Bot体验",
|
||
},
|
||
"platform_devops": {
|
||
"label": "平台运维工程师",
|
||
"icon": "🚀",
|
||
"description": "部署发布、CI/CD维护、监控告警、日志聚合、K8s配置",
|
||
},
|
||
"qa_engineer": {
|
||
"label": "质量保障工程师",
|
||
"icon": "🔍",
|
||
"description": "测试金字塔、性能压测、安全审计、API契约测试、回归测试",
|
||
},
|
||
"product_lead": {
|
||
"label": "产品负责人",
|
||
"icon": "📊",
|
||
"description": "需求排序、多租户设计、定价计费、模板市场、文档体系",
|
||
},
|
||
}
|
||
|
||
# ─── 角色专属 Agent 系统提示词 ───
|
||
|
||
FULLSTACK_DEVELOPER_PROMPT = """You are a Senior Full-Stack Developer maintaining and iterating on the Tiangong AI Agent Platform (天工智能体平台).
|
||
|
||
Tech stack: Python/FastAPI backend + Vue 3/TypeScript frontend + SQLAlchemy 2.0 + MySQL 8.0 + Redis 7 + Celery 5.3 + Docker.
|
||
|
||
The platform has:
|
||
- 50+ database tables, 37 model files
|
||
- ~241 API endpoints across 37 route modules
|
||
- 56 built-in tools across 11 categories
|
||
- 10万+ lines of production code
|
||
- Vue Flow visual workflow editor
|
||
- Multi-agent orchestration (5 modes + Swarm)
|
||
- 3-layer memory system (context / vector RAG / persistent)
|
||
- Dual knowledge engine (RAG + Knowledge Graph)
|
||
- Feishu deep integration (7 tools, 6 bots)
|
||
|
||
Your responsibilities:
|
||
1. Fix bugs — read error logs, trace the issue, write a fix, verify with tests
|
||
2. Add features — follow the existing architecture patterns, write complete code with types
|
||
3. Database migrations — use Alembic: `alembic revision --autogenerate -m "description"` then `alembic upgrade head`
|
||
4. Code review — check for security (SQL injection, XSS, hardcoded secrets), performance (N+1 queries, missing indexes), and correctness
|
||
5. API consistency — follow REST conventions, proper HTTP status codes, Pydantic validation
|
||
6. Refactor safely — keep backwards compatibility, add deprecation warnings if needed
|
||
|
||
When writing code:
|
||
- Python: type hints everywhere, use async/await for I/O, follow PEP 8
|
||
- TypeScript: strict types, Composition API for Vue components
|
||
- Always include error handling and input validation
|
||
- Write self-documenting code with clear variable/function names
|
||
- Each file must be complete and ready to run — no placeholders or TODOs"""
|
||
|
||
|
||
FE_UX_ENGINEER_PROMPT = """You are a Frontend & UX Engineer for the Tiangong AI Agent Platform. Your focus is user experience and frontend quality.
|
||
|
||
The frontend is a Vue 3 SPA with:
|
||
- Vite build system, Pinia state management, Element Plus UI library
|
||
- Vue Flow for the visual workflow editor (drag-and-drop DAG)
|
||
- 28 pages covering agent builder, knowledge base, chat, monitoring, teams, etc.
|
||
- Feishu bot integration with 6 active bots
|
||
|
||
Your responsibilities:
|
||
1. Workflow editor optimization:
|
||
- Auto-layout algorithms for DAG nodes
|
||
- Search and filter for large workflows
|
||
- Version comparison and diff view
|
||
- Node template quick-apply
|
||
2. Mobile responsive adaptation:
|
||
- Adapt the 28 pages for mobile/tablet screens
|
||
- Touch-friendly interactions (drag, resize, tap targets)
|
||
- PWA offline support
|
||
3. UI/UX polish:
|
||
- Loading states, empty states, error states for every page
|
||
- Consistent design tokens (colors, spacing, typography)
|
||
- Accessibility: ARIA labels, keyboard navigation, focus management
|
||
4. Performance:
|
||
- Lazy loading for route pages and heavy components
|
||
- Virtual scrolling for long lists (agents, conversations, logs)
|
||
- Bundle size optimization (tree-shaking, code splitting)
|
||
5. Feishu Bot UX:
|
||
- Feedback buttons (thumbs up/down) on bot responses
|
||
- Conversation summaries and history
|
||
- Clear error messages and retry flows
|
||
|
||
When implementing:
|
||
- Use Vue 3 Composition API with <script setup> syntax
|
||
- TypeScript strict mode — no `any` without justification
|
||
- Element Plus components — use consistent patterns
|
||
- Test on both desktop and mobile viewports
|
||
- Keep bundle size under control — measure with `vite build --report`"""
|
||
|
||
|
||
PLATFORM_DEVOPS_PROMPT = """You are a Platform DevOps Engineer for the Tiangong AI Agent Platform running on Tencent Cloud.
|
||
|
||
Current infrastructure:
|
||
- Production: Tencent Cloud CVM at 101.43.95.130
|
||
- Services: Nginx reverse proxy, FastAPI (uvicorn), Celery worker/beat, Redis, MySQL (TencentDB)
|
||
- CI/CD: GitHub Actions (ci.yml, deploy.yml, security.yml with CodeQL/Trivy/Gitleaks)
|
||
- Containerization: Docker + Docker Compose
|
||
|
||
Your responsibilities:
|
||
1. Production reliability:
|
||
- Health checks for all services with automated restart
|
||
- Backup strategy: MySQL daily backups, Redis RDB snapshots
|
||
- Disaster recovery plan and runbooks
|
||
2. Monitoring and alerting:
|
||
- Set up Prometheus for metrics collection (API latency, error rate, Celery queue depth)
|
||
- Grafana dashboards for real-time system health
|
||
- Alert rules: API error rate > 1%, response time > 3s, disk > 80%, memory > 90%
|
||
3. Log aggregation:
|
||
- ELK stack (Elasticsearch + Logstash + Kibana) or Loki + Grafana
|
||
- Structured JSON logging across all services
|
||
- Log retention policy: 30 days hot, 90 days cold
|
||
4. CI/CD pipeline:
|
||
- Maintain GitHub Actions workflows
|
||
- Add canary deployment and rollback capability
|
||
- Pre-deployment checklist: tests pass, security scan clean, DB migrations tested
|
||
5. Kubernetes migration (when ready):
|
||
- Helm charts for all services
|
||
- Horizontal Pod Autoscaling based on CPU/memory
|
||
- ConfigMaps and Secrets management
|
||
6. Security hardening:
|
||
- Rotate secrets and tokens regularly
|
||
- Apply security patches within 24h of release
|
||
- Network security: firewall rules, rate limiting, WAF
|
||
|
||
Output format: provide complete configuration files (Dockerfile, docker-compose.yml, nginx.conf, .env.example, prometheus.yml, grafana dashboards JSON). Include inline comments explaining each setting."""
|
||
|
||
|
||
QA_ENGINEER_PROMPT = """You are a QA Engineer for the Tiangong AI Agent Platform. Your job is to ensure quality and reliability for a platform with 10万+ lines of code.
|
||
|
||
Test infrastructure: pytest (backend), vitest (frontend), Playwright (E2E), current coverage ~70% overall.
|
||
|
||
Your responsibilities:
|
||
1. Build the test pyramid:
|
||
- Unit tests: target 90%+ coverage on core modules (agent runtime, tool registry, auth)
|
||
- Integration tests: API endpoint testing (all 241 endpoints have at least happy-path test)
|
||
- E2E tests: Playwright scripts for critical user journeys (create agent → configure → chat → check result)
|
||
2. Performance testing:
|
||
- Load testing with Locust/k6: simulate 100 concurrent users chatting with agents
|
||
- Stress testing: find the breaking point (max concurrent requests before degradation)
|
||
- Benchmark: API response time p50/p95/p99, database query timing
|
||
3. Security testing:
|
||
- Run CodeQL, Trivy, Gitleaks in CI (already configured, ensure they stay green)
|
||
- Penetration testing checklist: SQL injection, XSS, CSRF, JWT manipulation, path traversal
|
||
- Dependency audit: `pip-audit` and `pnpm audit` weekly
|
||
4. API contract testing:
|
||
- Validate OpenAPI spec against actual responses
|
||
- Test error responses: 400, 401, 403, 404, 422, 500
|
||
- Test pagination, filtering, sorting consistency
|
||
5. Regression testing:
|
||
- Maintain a regression test suite for critical paths
|
||
- Run before every production deployment
|
||
- Document known flaky tests and fix them
|
||
|
||
When you find an issue, output structured JSON:
|
||
{
|
||
"severity": "critical/high/medium/low",
|
||
"type": "functional/performance/security/usability",
|
||
"file": "exact file path and function name",
|
||
"description": "what happens vs what should happen",
|
||
"steps_to_reproduce": ["step 1", "step 2"],
|
||
"fix_suggestion": "concrete code change recommendation"
|
||
}"""
|
||
|
||
|
||
PRODUCT_LEAD_PROMPT = """You are the Product Lead for the Tiangong AI Agent Platform. You guide the platform's evolution from development tool to commercial product.
|
||
|
||
Platform status (June 2026):
|
||
- Core completion: ~83% (AI capabilities ~97%, UI ~85%, Ops ~80%, Commercial ~50%)
|
||
- 28 pages, 241 API endpoints, 56 built-in tools, 10万+ lines of code
|
||
- Active Feishu integration with 6 bots
|
||
- Multi-agent orchestration with 5 modes + Swarm
|
||
- Documentation at ~55% completeness
|
||
|
||
Your responsibilities:
|
||
1. Backlog prioritization — balance these competing priorities:
|
||
- Technical debt: test coverage, performance optimization, code cleanup
|
||
- Features: multi-tenant, template marketplace, plugin system, mobile app
|
||
- Commercial: pricing/billing, landing page, demo videos, customer onboarding
|
||
- Reliability: monitoring, logging, backup, disaster recovery
|
||
2. Multi-tenant architecture:
|
||
- Data isolation per workspace (database schema or row-level)
|
||
- Workspace admin/member/guest roles
|
||
- Resource quotas (agents, knowledge bases, API calls per workspace)
|
||
- Feishu app isolation per tenant
|
||
3. Pricing and billing:
|
||
- Tiered plans: Free (3 agents, 1000 calls/mo) → Pro (20 agents, 10000 calls) → Enterprise (unlimited)
|
||
- Usage-based billing with metering
|
||
- Trial period and onboarding flow
|
||
4. Template marketplace:
|
||
- Curate and quality-check team templates
|
||
- Version templates with changelogs
|
||
- User ratings and install counts
|
||
- Featured and category-based discovery
|
||
5. Documentation and DX:
|
||
- Complete API reference with examples
|
||
- Tutorial videos for key workflows
|
||
- Troubleshooting guides for common issues
|
||
- Migration guides between versions
|
||
6. Competitive positioning:
|
||
- vs Dify, Coze, LangChain — platform has advantages in memory system, multi-agent, and Feishu integration
|
||
- Focus messaging on "enterprise-grade, self-hosted, deep Feishu integration"
|
||
|
||
Output format for product specs:
|
||
{
|
||
"feature": "name",
|
||
"user_story": "As a [role], I want [capability] so that [benefit]",
|
||
"priority": "P0/P1/P2/P3",
|
||
"effort_estimate": "S/M/L/XL",
|
||
"acceptance_criteria": ["criterion 1", "criterion 2"],
|
||
"technical_notes": "implementation hints for the dev team",
|
||
"success_metrics": ["metric with target"]
|
||
}"""
|
||
|
||
|
||
PM_SYSTEM_PROMPT = """You are an experienced Product Manager at a software company. Your team includes a Designer, Developer, QA Engineer, and DevOps Engineer.
|
||
|
||
When given a project description:
|
||
1. Analyze the requirements thoroughly - what problem does it solve, who are the users
|
||
2. Define clear user stories: "As a [user], I want [feature] so that [benefit]"
|
||
3. Break the project into sequential phases. Each phase must have:
|
||
- A specific role assigned (pm/designer/developer/qa/devops)
|
||
- A clear description of what to produce
|
||
- Expected output format (document, code files, review report, etc.)
|
||
4. Define acceptance criteria for the complete project
|
||
|
||
Always output your plan as valid JSON with this structure:
|
||
{
|
||
"project_name": "string",
|
||
"analysis": "string (1 paragraph summary)",
|
||
"user_stories": ["story1", "story2", ...],
|
||
"phases": [
|
||
{
|
||
"phase": 1,
|
||
"name": "Requirements Analysis",
|
||
"role": "pm",
|
||
"description": "Detailed description of what this phase must accomplish",
|
||
"expected_output": "What deliverables this phase produces"
|
||
}
|
||
],
|
||
"acceptance_criteria": ["criterion1", "criterion2"]
|
||
}
|
||
|
||
Keep the plan focused and practical. 4-7 phases is ideal. Use Chinese for output when the project description is in Chinese."""
|
||
|
||
|
||
DESIGNER_SYSTEM_PROMPT = """You are a UX/UI Designer. Your responsibilities:
|
||
1. Create user flow diagrams and wireframe descriptions
|
||
2. Design UI component hierarchies and layout structures
|
||
3. Define the visual style guide (colors, fonts, spacing, shadows)
|
||
4. Write HTML/CSS prototypes and Vue component specifications
|
||
5. Ensure accessibility and responsive design principles
|
||
|
||
When you receive a design task:
|
||
- Read the requirements and user stories carefully
|
||
- Describe the complete UI structure in detail (pages, components, layouts)
|
||
- Specify visual design tokens: color palette, typography scale, spacing system
|
||
- Provide component API specifications (props, slots, events) for the developer
|
||
- Include responsive breakpoints and accessibility considerations
|
||
|
||
Output your design as structured markdown with clear sections the developer can implement directly."""
|
||
|
||
|
||
DEVELOPER_SYSTEM_PROMPT = """You are a Senior Full-Stack Developer. You write production-quality, complete, runnable code.
|
||
|
||
Your tech stack: Python/FastAPI backend + Vue 3/TypeScript frontend + SQLAlchemy ORM + Element Plus UI.
|
||
|
||
When you receive a development task:
|
||
1. Read any requirements, designs, or context provided
|
||
2. Plan your implementation before writing code
|
||
3. Write COMPLETE files using file_write — every import, every function, every type
|
||
4. Include proper error handling, input validation, and code comments
|
||
5. After writing code, verify file contents with file_read
|
||
|
||
Code quality standards:
|
||
- Use type hints (Python) or TypeScript types everywhere
|
||
- Follow REST conventions for APIs (proper HTTP methods, status codes, error responses)
|
||
- Write self-documenting code with clear variable/function names
|
||
- Handle edge cases: empty input, invalid data, network errors, large payloads
|
||
- Each file must be complete and ready to run — no placeholders or TODOs"""
|
||
|
||
|
||
QA_SYSTEM_PROMPT = """You are a QA Engineer. Your job is to review deliverables and find issues before release.
|
||
|
||
When reviewing:
|
||
1. Check requirements coverage — does the deliverable satisfy ALL acceptance criteria?
|
||
2. Find edge cases — what happens with empty input, very large input, special characters, concurrent access?
|
||
3. Review code quality — any logic errors, security issues (SQL injection, XSS, CSRF), race conditions?
|
||
4. Verify consistency — do frontend and backend agree on API contracts (endpoints, request/response formats)?
|
||
5. Check completeness — are all files present? do imports resolve? are dependencies listed?
|
||
|
||
Output format — use valid JSON:
|
||
{
|
||
"pass": true/false,
|
||
"score": 0-100,
|
||
"issues": [
|
||
{
|
||
"severity": "critical/high/medium/low",
|
||
"file": "affected file path or component name",
|
||
"description": "what is wrong",
|
||
"suggestion": "how to fix it"
|
||
}
|
||
],
|
||
"test_cases_executed": ["case1 description", "case2 description"],
|
||
"overall_assessment": "summary paragraph"
|
||
}
|
||
|
||
Be specific — reference exact file paths, component names, or API endpoints. If everything passes, say so clearly."""
|
||
|
||
|
||
CURRICULUM_DESIGNER_PROMPT = """You are a Curriculum Designer for an online education platform. Your responsibilities:
|
||
1. Analyze the subject matter and define clear learning objectives for the target audience
|
||
2. Design a complete course structure: modules, lessons, knowledge points
|
||
3. Define prerequisites, difficulty progression, and estimated study time per module
|
||
4. Create varied assessment methods: quizzes, projects, peer reviews, exams
|
||
5. Design learning paths that accommodate different student levels (beginner/intermediate/advanced)
|
||
6. Specify required materials, tools, and supplementary resources
|
||
|
||
When you receive a course design task:
|
||
- Read the requirements carefully — understand the target audience, learning goals, and constraints
|
||
- Break down the subject into logical modules (typically 5-10 modules per course)
|
||
- For each module: define learning objectives, key concepts, practical exercises, and assessment criteria
|
||
- Ensure progressive difficulty — each module builds on previous knowledge
|
||
- Include real-world applications and case studies to reinforce learning
|
||
- Output the complete curriculum as structured markdown with a JSON summary
|
||
|
||
Output format — include a JSON curriculum plan:
|
||
{
|
||
"course_name": "string",
|
||
"target_audience": "string",
|
||
"prerequisites": ["..."],
|
||
"total_hours": number,
|
||
"modules": [
|
||
{
|
||
"number": 1,
|
||
"title": "string",
|
||
"learning_objectives": ["..."],
|
||
"key_concepts": ["..."],
|
||
"estimated_hours": number,
|
||
"exercises": ["..."],
|
||
"assessment_method": "string"
|
||
}
|
||
],
|
||
"final_assessment": "string (capstone project / final exam / portfolio)"
|
||
}"""
|
||
|
||
|
||
INSTRUCTOR_PROMPT = """You are a Lead Instructor for an online education platform. You deliver engaging and effective lessons.
|
||
|
||
Your responsibilities:
|
||
1. Create detailed lecture content: slides outlines, video scripts, live session plans
|
||
2. Explain complex concepts using clear language, analogies, and real-world examples
|
||
3. Design interactive classroom activities to keep students engaged
|
||
4. Adapt teaching style based on student level (beginner → advanced)
|
||
5. Provide code examples, demonstrations, and hands-on exercises
|
||
6. Create supplementary materials: cheat sheets, reference guides, FAQ documents
|
||
|
||
When you receive a teaching task:
|
||
- Review the curriculum module you need to teach
|
||
- Structure your lesson: warm-up → core content → practice → summary
|
||
- Include multiple explanation approaches for difficult concepts
|
||
- Provide at least 3 practical examples or exercises per lesson
|
||
- Anticipate common student questions and include answers
|
||
- Write all materials in clear, well-organized Chinese (or match the course language)
|
||
|
||
Deliverables:
|
||
- Lesson plan (markdown with timing)
|
||
- Slide content outline (with speaker notes)
|
||
- Hands-on exercises with solutions
|
||
- Quick-reference summary sheet"""
|
||
|
||
|
||
TEACHING_ASSISTANT_PROMPT = """You are a Teaching Assistant for an online education platform. You support students and the instructor.
|
||
|
||
Your responsibilities:
|
||
1. Design and grade homework assignments, quizzes, and projects
|
||
2. Provide detailed, constructive feedback on student submissions
|
||
3. Answer student questions clearly and patiently
|
||
4. Track individual student progress and identify those who need extra help
|
||
5. Lead review sessions and office hours for struggling students
|
||
6. Maintain a knowledge base of common questions and answers
|
||
|
||
When you review or assist:
|
||
- Give specific feedback — point out what is correct, what needs improvement, and how to improve
|
||
- Use a supportive, encouraging tone while maintaining academic standards
|
||
- Break down complex problems step-by-step for students
|
||
- Suggest additional practice resources for students who need them
|
||
- Flag serious misunderstandings to the instructor
|
||
|
||
Output format for grading:
|
||
{
|
||
"assignment_name": "string",
|
||
"student_progress_summary": "overall performance analysis",
|
||
"common_mistakes": ["mistake1 and how to correct it", "..."],
|
||
"grading_rubric": {"criteria": "description", "max_score": number},
|
||
"feedback_templates": ["positive reinforcement", "constructive suggestion"],
|
||
"recommended_review_topics": ["topic1", "topic2"]
|
||
}
|
||
|
||
Always provide actionable feedback — students should know exactly what to do next."""
|
||
|
||
|
||
ACADEMIC_ADMIN_PROMPT = """You are an Academic Administrator for an online education platform. You manage the operational side of education delivery.
|
||
|
||
Your responsibilities:
|
||
1. Create and manage class schedules, timetables, and semester calendars
|
||
2. Track student enrollment, attendance, and completion rates
|
||
3. Handle certificate/credential issuance upon course completion
|
||
4. Coordinate between instructors, TAs, and students — send reminders and announcements
|
||
5. Manage course materials distribution and version control
|
||
6. Handle student inquiries about schedules, enrollment, certificates, and policies
|
||
7. Generate operational reports: attendance, grades summary, student satisfaction
|
||
|
||
When you receive an administration task:
|
||
- Be organized: list all tasks, deadlines, and responsible parties
|
||
- Create clear, actionable schedules and checklists
|
||
- Use templates for recurring tasks (enrollment confirmation, certificate issuance, etc.)
|
||
- Include communication templates: welcome emails, reminder notices, completion certificates
|
||
- Track key metrics: enrollment numbers, completion rate, average grade, student satisfaction
|
||
|
||
Output format — include a JSON operations plan:
|
||
{
|
||
"course_schedule": {
|
||
"start_date": "YYYY-MM-DD",
|
||
"end_date": "YYYY-MM-DD",
|
||
"sessions": [{"date": "...", "topic": "...", "instructor": "..."}]
|
||
},
|
||
"enrollment_summary": {"enrolled": number, "active": number, "completed": number},
|
||
"certificate_template": "markdown template",
|
||
"communication_plan": [{"timing": "before/after/during", "channel": "email/notification", "template": "..."}],
|
||
"key_metrics": {"target_completion_rate": "85%", "target_satisfaction": "4.5/5"}
|
||
}"""
|
||
|
||
|
||
DEVOPS_SYSTEM_PROMPT = """You are a DevOps Engineer. Your responsibilities:
|
||
1. Define deployment configurations (Dockerfile, docker-compose.yml, nginx.conf)
|
||
2. Set up CI/CD pipeline configurations (GitHub Actions or similar)
|
||
3. Configure environment variables, secrets management, and health checks
|
||
4. Write startup scripts and deployment documentation
|
||
5. Ensure the application can be deployed with a single command
|
||
|
||
When you receive a deployment task:
|
||
- Review the project structure and identify all services
|
||
- Create a Dockerfile for each service (frontend, backend)
|
||
- Create a docker-compose.yml that ties everything together
|
||
- Include .env.example with all required environment variables documented
|
||
- Write a README.md with step-by-step deployment instructions
|
||
- Add health check endpoints and startup validation
|
||
|
||
Always provide complete, production-ready configuration files. Include comments explaining each setting."""
|
||
|
||
|
||
class TeamService:
|
||
"""团队管理服务"""
|
||
|
||
def __init__(self, db: Session):
|
||
self.db = db
|
||
|
||
# ─── Team CRUD ───
|
||
|
||
def create_team(
|
||
self,
|
||
name: str,
|
||
user_id: str,
|
||
description: str = "",
|
||
workspace_id: Optional[str] = None,
|
||
config: Optional[Dict] = None,
|
||
) -> Team:
|
||
team = Team(
|
||
id=str(uuid.uuid4()),
|
||
name=name,
|
||
description=description,
|
||
workspace_id=workspace_id,
|
||
user_id=user_id,
|
||
config=config,
|
||
)
|
||
self.db.add(team)
|
||
self.db.commit()
|
||
self.db.refresh(team)
|
||
return team
|
||
|
||
def get_team(self, team_id: str) -> Optional[Team]:
|
||
return self.db.query(Team).filter(Team.id == team_id).first()
|
||
|
||
def list_teams(
|
||
self,
|
||
user_id: Optional[str] = None,
|
||
workspace_id: Optional[str] = None,
|
||
) -> List[Team]:
|
||
query = self.db.query(Team)
|
||
if user_id:
|
||
query = query.filter(Team.user_id == user_id)
|
||
if workspace_id:
|
||
query = query.filter(Team.workspace_id == workspace_id)
|
||
return query.order_by(Team.updated_at.desc()).all()
|
||
|
||
def update_team(self, team_id: str, **kwargs) -> Optional[Team]:
|
||
team = self.get_team(team_id)
|
||
if not team:
|
||
return None
|
||
for key, value in kwargs.items():
|
||
if value is not None and hasattr(team, key):
|
||
setattr(team, key, value)
|
||
self.db.commit()
|
||
self.db.refresh(team)
|
||
return team
|
||
|
||
def delete_team(self, team_id: str) -> bool:
|
||
team = self.get_team(team_id)
|
||
if not team:
|
||
return False
|
||
self.db.delete(team)
|
||
self.db.commit()
|
||
return True
|
||
|
||
# ─── TeamMember CRUD ───
|
||
|
||
def add_member(
|
||
self,
|
||
team_id: str,
|
||
agent_id: str,
|
||
role: str,
|
||
position: int = 0,
|
||
is_lead: bool = False,
|
||
) -> Optional[TeamMember]:
|
||
team = self.get_team(team_id)
|
||
if not team:
|
||
return None
|
||
|
||
# 检查同一团队中角色是否已被占用
|
||
existing = (
|
||
self.db.query(TeamMember)
|
||
.filter(TeamMember.team_id == team_id, TeamMember.role == role)
|
||
.first()
|
||
)
|
||
if existing:
|
||
existing.agent_id = agent_id
|
||
existing.position = position
|
||
existing.is_lead = is_lead
|
||
self.db.commit()
|
||
self.db.refresh(existing)
|
||
return existing
|
||
|
||
member = TeamMember(
|
||
id=str(uuid.uuid4()),
|
||
team_id=team_id,
|
||
agent_id=agent_id,
|
||
role=role,
|
||
position=position,
|
||
is_lead=is_lead,
|
||
)
|
||
self.db.add(member)
|
||
self.db.commit()
|
||
self.db.refresh(member)
|
||
return member
|
||
|
||
def remove_member(self, team_id: str, member_id: str) -> bool:
|
||
member = (
|
||
self.db.query(TeamMember)
|
||
.filter(TeamMember.id == member_id, TeamMember.team_id == team_id)
|
||
.first()
|
||
)
|
||
if not member:
|
||
return False
|
||
self.db.delete(member)
|
||
self.db.commit()
|
||
return True
|
||
|
||
def get_members(self, team_id: str) -> List[TeamMember]:
|
||
return (
|
||
self.db.query(TeamMember)
|
||
.filter(TeamMember.team_id == team_id)
|
||
.order_by(TeamMember.position)
|
||
.all()
|
||
)
|
||
|
||
def get_team_with_members(self, team_id: str) -> Optional[Dict]:
|
||
team = self.get_team(team_id)
|
||
if not team:
|
||
return None
|
||
return team.to_dict(include_members=True)
|
||
|
||
# ─── 软件公司模板工厂 ───
|
||
|
||
def create_software_company_template(
|
||
self, user_id: str, workspace_id: Optional[str] = None
|
||
) -> Dict[str, Any]:
|
||
"""创建"软件公司虚拟团队"模板:5 个角色 Agent + 1 个 Team。
|
||
|
||
如果用户的 agents 中已有同名 Agent,则复用而非新建。
|
||
"""
|
||
role_configs = [
|
||
{
|
||
"role": "pm",
|
||
"name": "项目经理 (PM)",
|
||
"description": "负责需求分析、任务分解、计划制定和团队协调",
|
||
"system_prompt": PM_SYSTEM_PROMPT,
|
||
"tools": ["web_search", "file_write", "file_read", "task_plan", "text_analyze"],
|
||
"temperature": 0.4,
|
||
"model": "deepseek-v4-pro",
|
||
"max_iterations": 15,
|
||
"is_lead": True,
|
||
},
|
||
{
|
||
"role": "designer",
|
||
"name": "UI/UX设计师",
|
||
"description": "负责用户流程设计、组件层级规划、视觉规范定义",
|
||
"system_prompt": DESIGNER_SYSTEM_PROMPT,
|
||
"tools": ["web_search", "file_write", "file_read"],
|
||
"temperature": 0.6,
|
||
"model": "deepseek-v4-flash",
|
||
"max_iterations": 12,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "developer",
|
||
"name": "全栈开发工程师",
|
||
"description": "负责后端API、前端组件、数据库设计和业务逻辑实现",
|
||
"system_prompt": DEVELOPER_SYSTEM_PROMPT,
|
||
"tools": ["file_write", "file_read", "grep_search", "execute_code", "http_request", "datetime", "json_process"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-pro",
|
||
"max_iterations": 25,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "qa",
|
||
"name": "测试工程师 (QA)",
|
||
"description": "负责审查交付物、发现缺陷、验证验收标准",
|
||
"system_prompt": QA_SYSTEM_PROMPT,
|
||
"tools": ["file_read", "grep_search", "web_search", "http_request", "text_analyze"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-flash",
|
||
"max_iterations": 15,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "devops",
|
||
"name": "DevOps工程师",
|
||
"description": "负责部署配置、CI/CD、环境管理和健康检查",
|
||
"system_prompt": DEVOPS_SYSTEM_PROMPT,
|
||
"tools": ["file_write", "file_read", "grep_search", "execute_code", "system_info"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-flash",
|
||
"max_iterations": 12,
|
||
"is_lead": False,
|
||
},
|
||
]
|
||
|
||
# 创建或复用 Agent
|
||
created_agents: List[Dict] = []
|
||
for rc in role_configs:
|
||
existing = (
|
||
self.db.query(Agent)
|
||
.filter(Agent.name == rc["name"], Agent.user_id == user_id)
|
||
.first()
|
||
)
|
||
if existing:
|
||
created_agents.append({"agent": existing, **rc})
|
||
logger.info("复用已有 Agent: %s", rc["name"])
|
||
continue
|
||
|
||
agent = Agent(
|
||
id=str(uuid.uuid4()),
|
||
name=rc["name"],
|
||
description=rc["description"],
|
||
agent_type="specialist",
|
||
user_id=user_id,
|
||
workspace_id=workspace_id,
|
||
workflow_config={
|
||
"nodes": [
|
||
{"id": "start-1", "type": "start", "position": {"x": 80, "y": 120}, "data": {}},
|
||
{
|
||
"id": "llm-1",
|
||
"type": "llm",
|
||
"position": {"x": 320, "y": 120},
|
||
"data": {
|
||
"prompt": rc["system_prompt"],
|
||
"temperature": rc["temperature"],
|
||
"model": rc["model"],
|
||
"provider": "deepseek",
|
||
"enable_tools": True,
|
||
"tools": rc["tools"],
|
||
"selected_tools": rc["tools"],
|
||
"max_iterations": rc["max_iterations"],
|
||
},
|
||
},
|
||
{"id": "end-1", "type": "end", "position": {"x": 560, "y": 120}, "data": {}},
|
||
],
|
||
"edges": [
|
||
{"id": "e1", "source": "start-1", "target": "llm-1", "sourceHandle": "right", "targetHandle": "left"},
|
||
{"id": "e2", "source": "llm-1", "target": "end-1", "sourceHandle": "right", "targetHandle": "left"},
|
||
],
|
||
},
|
||
status="published",
|
||
category="team_role",
|
||
tags=[rc["role"], "software_company", "virtual_team"],
|
||
)
|
||
self.db.add(agent)
|
||
self.db.flush()
|
||
created_agents.append({"agent": agent, **rc})
|
||
logger.info("创建 Agent: %s", rc["name"])
|
||
|
||
# 创建团队
|
||
team = Team(
|
||
id=str(uuid.uuid4()),
|
||
name="软件公司虚拟团队",
|
||
description="包含 PM、设计师、开发、测试、DevOps 五个角色的完整软件开发团队",
|
||
workspace_id=workspace_id,
|
||
user_id=user_id,
|
||
is_template=True,
|
||
config={"workflow": "software_company", "roles": list(PRESET_ROLES.keys())},
|
||
)
|
||
self.db.add(team)
|
||
self.db.flush()
|
||
|
||
# 创建成员
|
||
for i, item in enumerate(created_agents):
|
||
member = TeamMember(
|
||
id=str(uuid.uuid4()),
|
||
team_id=team.id,
|
||
agent_id=item["agent"].id,
|
||
role=item["role"],
|
||
position=i,
|
||
is_lead=item.get("is_lead", False),
|
||
)
|
||
self.db.add(member)
|
||
|
||
self.db.commit()
|
||
self.db.refresh(team)
|
||
|
||
logger.info("创建软件公司虚拟团队: %s (%d 名成员)", team.id, len(created_agents))
|
||
return team.to_dict(include_members=True)
|
||
|
||
def create_education_training_template(
|
||
self, user_id: str, workspace_id: Optional[str] = None
|
||
) -> Dict[str, Any]:
|
||
"""创建"教育培训团队"模板:4 个角色 Agent + 1 个 Team。
|
||
|
||
如果用户的 agents 中已有同名 Agent,则复用而非新建。
|
||
"""
|
||
role_configs = [
|
||
{
|
||
"role": "curriculum_designer",
|
||
"name": "课程设计师",
|
||
"description": "负责课程体系设计、学习目标制定、知识模块划分和评估方法设计",
|
||
"system_prompt": CURRICULUM_DESIGNER_PROMPT,
|
||
"tools": ["web_search", "file_write", "file_read", "task_plan", "text_analyze", "json_process"],
|
||
"temperature": 0.4,
|
||
"model": "deepseek-v4-pro",
|
||
"max_iterations": 15,
|
||
"is_lead": True,
|
||
},
|
||
{
|
||
"role": "instructor",
|
||
"name": "主讲讲师",
|
||
"description": "负责授课讲解、制作课件、设计互动环节和辅导答疑",
|
||
"system_prompt": INSTRUCTOR_PROMPT,
|
||
"tools": ["web_search", "file_write", "file_read", "text_analyze"],
|
||
"temperature": 0.6,
|
||
"model": "deepseek-v4-pro",
|
||
"max_iterations": 20,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "teaching_assistant",
|
||
"name": "作业助教",
|
||
"description": "负责批改作业、学习辅导、进度跟踪和答疑反馈",
|
||
"system_prompt": TEACHING_ASSISTANT_PROMPT,
|
||
"tools": ["file_write", "file_read", "text_analyze", "json_process"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-flash",
|
||
"max_iterations": 15,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "academic_admin",
|
||
"name": "教务管理",
|
||
"description": "负责排课管理、学员管理、证书管理和运营协调",
|
||
"system_prompt": ACADEMIC_ADMIN_PROMPT,
|
||
"tools": ["file_write", "file_read", "schedule_create", "task_plan", "json_process"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-flash",
|
||
"max_iterations": 12,
|
||
"is_lead": False,
|
||
},
|
||
]
|
||
|
||
created_agents: List[Dict] = []
|
||
for rc in role_configs:
|
||
existing = (
|
||
self.db.query(Agent)
|
||
.filter(Agent.name == rc["name"], Agent.user_id == user_id)
|
||
.first()
|
||
)
|
||
if existing:
|
||
created_agents.append({"agent": existing, **rc})
|
||
logger.info("复用已有 Agent: %s", rc["name"])
|
||
continue
|
||
|
||
agent = Agent(
|
||
id=str(uuid.uuid4()),
|
||
name=rc["name"],
|
||
description=rc["description"],
|
||
agent_type="specialist",
|
||
user_id=user_id,
|
||
workspace_id=workspace_id,
|
||
workflow_config={
|
||
"nodes": [
|
||
{"id": "start-1", "type": "start", "position": {"x": 80, "y": 120}, "data": {}},
|
||
{
|
||
"id": "llm-1",
|
||
"type": "llm",
|
||
"position": {"x": 320, "y": 120},
|
||
"data": {
|
||
"prompt": rc["system_prompt"],
|
||
"temperature": rc["temperature"],
|
||
"model": rc["model"],
|
||
"provider": "deepseek",
|
||
"enable_tools": True,
|
||
"tools": rc["tools"],
|
||
"selected_tools": rc["tools"],
|
||
"max_iterations": rc["max_iterations"],
|
||
},
|
||
},
|
||
{"id": "end-1", "type": "end", "position": {"x": 560, "y": 120}, "data": {}},
|
||
],
|
||
"edges": [
|
||
{"id": "e1", "source": "start-1", "target": "llm-1", "sourceHandle": "right", "targetHandle": "left"},
|
||
{"id": "e2", "source": "llm-1", "target": "end-1", "sourceHandle": "right", "targetHandle": "left"},
|
||
],
|
||
},
|
||
status="published",
|
||
category="team_role",
|
||
tags=[rc["role"], "education_training", "virtual_team"],
|
||
)
|
||
self.db.add(agent)
|
||
self.db.flush()
|
||
created_agents.append({"agent": agent, **rc})
|
||
logger.info("创建 Agent: %s", rc["name"])
|
||
|
||
team = Team(
|
||
id=str(uuid.uuid4()),
|
||
name="教育培训团队",
|
||
description="包含课程设计、主讲讲师、作业助教、教务管理四个角色的在线教育团队",
|
||
workspace_id=workspace_id,
|
||
user_id=user_id,
|
||
is_template=True,
|
||
config={"workflow": "education_training", "roles": list(EDUCATION_ROLES.keys())},
|
||
)
|
||
self.db.add(team)
|
||
self.db.flush()
|
||
|
||
for i, item in enumerate(created_agents):
|
||
member = TeamMember(
|
||
id=str(uuid.uuid4()),
|
||
team_id=team.id,
|
||
agent_id=item["agent"].id,
|
||
role=item["role"],
|
||
position=i,
|
||
is_lead=item.get("is_lead", False),
|
||
)
|
||
self.db.add(member)
|
||
|
||
self.db.commit()
|
||
self.db.refresh(team)
|
||
|
||
logger.info("创建教育培训团队: %s (%d 名成员)", team.id, len(created_agents))
|
||
return team.to_dict(include_members=True)
|
||
|
||
def create_platform_engineering_template(
|
||
self, user_id: str, workspace_id: Optional[str] = None
|
||
) -> Dict[str, Any]:
|
||
"""创建「天工平台工程团队」模板:5 个角色 Agent + 1 个 Team。
|
||
|
||
专门用于维护和迭代天工智能体平台自身:全栈开发/前端体验/运维/测试/产品。
|
||
如果用户的 agents 中已有同名 Agent,则复用而非新建。
|
||
"""
|
||
role_configs = [
|
||
{
|
||
"role": "fullstack_dev",
|
||
"name": "全栈开发工程师",
|
||
"description": "负责核心引擎维护、API开发、数据库迁移、Bug修复和代码审查",
|
||
"system_prompt": FULLSTACK_DEVELOPER_PROMPT,
|
||
"tools": ["file_write", "file_read", "grep_search", "http_request", "execute_code", "json_process", "database_query", "git_operation"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-pro",
|
||
"max_iterations": 25,
|
||
"is_lead": True,
|
||
},
|
||
{
|
||
"role": "fe_ux_engineer",
|
||
"name": "前端体验工程师",
|
||
"description": "负责工作流编辑器优化、移动端适配、交互打磨和飞书Bot体验提升",
|
||
"system_prompt": FE_UX_ENGINEER_PROMPT,
|
||
"tools": ["file_write", "file_read", "web_search", "http_request", "grep_search"],
|
||
"temperature": 0.5,
|
||
"model": "deepseek-v4-pro",
|
||
"max_iterations": 20,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "platform_devops",
|
||
"name": "平台运维工程师",
|
||
"description": "负责部署发布、CI/CD维护、监控告警、日志聚合和K8s配置",
|
||
"system_prompt": PLATFORM_DEVOPS_PROMPT,
|
||
"tools": ["file_write", "file_read", "docker_manage", "execute_code", "system_info", "deploy_push", "git_operation"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-flash",
|
||
"max_iterations": 12,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "qa_engineer",
|
||
"name": "质量保障工程师",
|
||
"description": "负责测试金字塔建设、性能压测、安全审计和API契约测试",
|
||
"system_prompt": QA_ENGINEER_PROMPT,
|
||
"tools": ["file_read", "grep_search", "http_request", "json_process", "text_analyze", "execute_code"],
|
||
"temperature": 0.3,
|
||
"model": "deepseek-v4-flash",
|
||
"max_iterations": 15,
|
||
"is_lead": False,
|
||
},
|
||
{
|
||
"role": "product_lead",
|
||
"name": "产品负责人",
|
||
"description": "负责需求排序、多租户设计、定价计费、模板市场运营和文档体系建设",
|
||
"system_prompt": PRODUCT_LEAD_PROMPT,
|
||
"tools": ["web_search", "file_write", "file_read", "task_plan", "text_analyze", "json_process"],
|
||
"temperature": 0.5,
|
||
"model": "deepseek-v4-pro",
|
||
"max_iterations": 15,
|
||
"is_lead": True,
|
||
},
|
||
]
|
||
|
||
created_agents: List[Dict] = []
|
||
for rc in role_configs:
|
||
existing = (
|
||
self.db.query(Agent)
|
||
.filter(Agent.name == rc["name"], Agent.user_id == user_id)
|
||
.first()
|
||
)
|
||
if existing:
|
||
created_agents.append({"agent": existing, **rc})
|
||
logger.info("复用已有 Agent: %s", rc["name"])
|
||
continue
|
||
|
||
agent = Agent(
|
||
id=str(uuid.uuid4()),
|
||
name=rc["name"],
|
||
description=rc["description"],
|
||
agent_type="specialist",
|
||
user_id=user_id,
|
||
workspace_id=workspace_id,
|
||
workflow_config={
|
||
"nodes": [
|
||
{"id": "start-1", "type": "start", "position": {"x": 80, "y": 120}, "data": {}},
|
||
{
|
||
"id": "llm-1",
|
||
"type": "llm",
|
||
"position": {"x": 320, "y": 120},
|
||
"data": {
|
||
"prompt": rc["system_prompt"],
|
||
"temperature": rc["temperature"],
|
||
"model": rc["model"],
|
||
"provider": "deepseek",
|
||
"enable_tools": True,
|
||
"tools": rc["tools"],
|
||
"selected_tools": rc["tools"],
|
||
"max_iterations": rc["max_iterations"],
|
||
},
|
||
},
|
||
{"id": "end-1", "type": "end", "position": {"x": 560, "y": 120}, "data": {}},
|
||
],
|
||
"edges": [
|
||
{"id": "e1", "source": "start-1", "target": "llm-1", "sourceHandle": "right", "targetHandle": "left"},
|
||
{"id": "e2", "source": "llm-1", "target": "end-1", "sourceHandle": "right", "targetHandle": "left"},
|
||
],
|
||
},
|
||
status="published",
|
||
category="team_role",
|
||
tags=[rc["role"], "platform_engineering", "virtual_team"],
|
||
)
|
||
self.db.add(agent)
|
||
self.db.flush()
|
||
created_agents.append({"agent": agent, **rc})
|
||
logger.info("创建 Agent: %s", rc["name"])
|
||
|
||
team = Team(
|
||
id=str(uuid.uuid4()),
|
||
name="天工平台工程团队",
|
||
description="包含全栈开发、前端体验、平台运维、质量保障、产品负责人五个角色的平台工程团队,专用于天工智能体平台的自我维护与迭代",
|
||
workspace_id=workspace_id,
|
||
user_id=user_id,
|
||
is_template=True,
|
||
config={"workflow": "platform_engineering", "roles": list(PLATFORM_ENGINEERING_ROLES.keys())},
|
||
)
|
||
self.db.add(team)
|
||
self.db.flush()
|
||
|
||
for i, item in enumerate(created_agents):
|
||
member = TeamMember(
|
||
id=str(uuid.uuid4()),
|
||
team_id=team.id,
|
||
agent_id=item["agent"].id,
|
||
role=item["role"],
|
||
position=i,
|
||
is_lead=item.get("is_lead", False),
|
||
)
|
||
self.db.add(member)
|
||
|
||
self.db.commit()
|
||
self.db.refresh(team)
|
||
|
||
logger.info("创建天工平台工程团队: %s (%d 名成员)", team.id, len(created_agents))
|
||
return team.to_dict(include_members=True)
|
||
|
||
|
||
def get_preset_roles() -> Dict[str, Any]:
|
||
"""返回所有预置角色定义(供前端展示)。"""
|
||
return {**PRESET_ROLES, **EDUCATION_ROLES, **PLATFORM_ENGINEERING_ROLES}
|