- Fix delete agent 500: clean up FK records (agent_llm_logs, permissions, schedules, executions, team_members) and unbind goals/tasks before delete - Remove hardcoded personality templates in Android, replace with dynamic system prompt generation from name + description - Set promptSectionsEnabled=false to bypass PromptComposer for personality - Add Tencent Cloud Linux deployment guide (Docker Compose) - Accumulated backend service updates, frontend UI fixes, Android app changes Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
380 lines
15 KiB
Python
380 lines
15 KiB
Python
"""创建功能最强大的自主 Agent — Pro 模型 + 全工具 + 向量记忆 + 自主学习
|
||
|
||
用法:
|
||
python scripts/seed_max_agent.py
|
||
python scripts/seed_max_agent.py --name "我的助手" --desc "自定义描述"
|
||
"""
|
||
import json
|
||
import urllib.request
|
||
import urllib.parse
|
||
import uuid
|
||
import sys
|
||
import argparse
|
||
|
||
BASE = "http://localhost:8037"
|
||
|
||
# ─── 全部可用工具(从平台 GET /api/v1/tools 获取) ───
|
||
ALL_TOOLS = [
|
||
# 文件操作
|
||
"file_read", "file_write", "list_files", "grep_search",
|
||
# 网络请求
|
||
"http_request", "web_search", "check_website", "url_parse", "browser_use",
|
||
# 数据处理
|
||
"text_analyze", "text_summarize", "json_process", "json_tool",
|
||
"math_calculate", "random_generate", "regex_test",
|
||
"csv_processor", "excel_process", "pdf_generate",
|
||
"base64_codec", "crypto_util", "html_to_markdown",
|
||
# 数据库 & 系统
|
||
"database_query", "system_info", "datetime", "timestamp",
|
||
# 代码 & 开发
|
||
"code_execute", "execute_code", "code_tool_create",
|
||
"git_operation", "git_log", "project_scaffold", "project_scan",
|
||
"docker_manage", "deploy_push", "adb_log",
|
||
# AI Agent 扩展
|
||
"agent_call", "agent_create", "tool_register",
|
||
"task_plan", "self_review", "capability_check", "extension_log",
|
||
"create_task", "assign_task", "check_progress", "notify_user",
|
||
# 知识图谱
|
||
"knowledge_graph_search", "knowledge_graph_add",
|
||
"entity_search", "learning_path",
|
||
# 多模态
|
||
"image_ocr", "image_vision", "speech_to_text", "text_to_speech",
|
||
# 飞书集成
|
||
"feishu_create_doc", "feishu_create_sheet", "feishu_create_calendar_event",
|
||
"feishu_search_contacts", "feishu_send_approval",
|
||
"feishu_read_messages", "feishu_upload_file",
|
||
# DevOps & 测试
|
||
"create_gitea_issue", "parse_test_result_file",
|
||
"schedule_create", "schedule_list", "schedule_delete",
|
||
# 网络 & IP
|
||
"ip_info", "shorten_url",
|
||
# 其他
|
||
"extract_info",
|
||
]
|
||
|
||
|
||
def req(method, path, headers=None, body=None, raw_body=None, timeout=15):
|
||
hdrs = {"Content-Type": "application/json"}
|
||
if headers:
|
||
hdrs.update(headers)
|
||
data = raw_body if raw_body else (json.dumps(body).encode() if body else None)
|
||
r = urllib.request.Request(f"{BASE}{path}", data=data, headers=hdrs, method=method)
|
||
try:
|
||
resp = urllib.request.urlopen(r, timeout=timeout)
|
||
return resp.status, json.loads(resp.read())
|
||
except urllib.request.HTTPError as e:
|
||
return e.code, json.loads(e.read())
|
||
except Exception as e:
|
||
return 0, {"error": str(e)}
|
||
|
||
|
||
def login(username="admin", password="123456"):
|
||
"""登录获取 token,支持 admin 或自定义账号"""
|
||
status, data = req("POST", "/api/v1/auth/login",
|
||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||
raw_body=urllib.parse.urlencode(
|
||
{"username": username, "password": password}).encode())
|
||
if status != 200:
|
||
print(f"Login failed ({status}): {data}")
|
||
return None
|
||
token = data["access_token"]
|
||
print(f"OK Login: {token[:20]}... (ws={data.get('ws','')[:8]}...)")
|
||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||
|
||
|
||
def make_workflow_pro(name, system_prompt, tools=None, model="deepseek-v4-pro",
|
||
provider="deepseek", temperature=0.8, max_iterations=15):
|
||
"""构建 Pro 级工作流配置,含完整向量记忆+自主学习。
|
||
|
||
参数:
|
||
name: Agent 名称
|
||
system_prompt: 系统提示词
|
||
tools: 工具列表,None/空列表 = 全部工具
|
||
model: deepseek-v4-pro | deepseek-v4-flash | gpt-4o
|
||
temperature: 0-1,越高越有创造性
|
||
max_iterations: ReAct 最大迭代步数
|
||
"""
|
||
if tools is None:
|
||
tools = []
|
||
|
||
_start_id = str(uuid.uuid4())
|
||
_llm_id = str(uuid.uuid4())
|
||
_end_id = str(uuid.uuid4())
|
||
|
||
return {
|
||
"nodes": [
|
||
{
|
||
"id": _start_id,
|
||
"type": "start",
|
||
"position": {"x": 100, "y": 200},
|
||
"data": {"label": "开始"},
|
||
},
|
||
{
|
||
"id": _llm_id,
|
||
"type": "llm",
|
||
"position": {"x": 380, "y": 200},
|
||
"data": {
|
||
"label": name,
|
||
"system_prompt": system_prompt,
|
||
"model": model,
|
||
"provider": provider,
|
||
"temperature": temperature,
|
||
"max_iterations": max_iterations,
|
||
# ── 工具配置 ──
|
||
"tools": tools,
|
||
"selected_tools": tools,
|
||
"enable_tools": True,
|
||
# ── 三级记忆架构 ──
|
||
"memory": True,
|
||
"memory_persist": True, # 对话写入 MySQL
|
||
"memory_vector_enabled": True, # 向量语义检索
|
||
"memory_vector_top_k": 20, # 检索最相关 20 条
|
||
"memory_learning": True, # 自主学习模式
|
||
"memory_max_history": 25, # 上下文最大消息数
|
||
},
|
||
},
|
||
{
|
||
"id": _end_id,
|
||
"type": "end",
|
||
"position": {"x": 640, "y": 200},
|
||
"data": {"label": "结束"},
|
||
},
|
||
],
|
||
"edges": [
|
||
{"id": str(uuid.uuid4()), "source": _start_id, "target": _llm_id},
|
||
{"id": str(uuid.uuid4()), "source": _llm_id, "target": _end_id},
|
||
],
|
||
}
|
||
|
||
|
||
# ══════════════════════════════════════════════════════════════════
|
||
# 豆包风格通用 System Prompt(989 字,6 大特质)
|
||
# ══════════════════════════════════════════════════════════════════
|
||
|
||
PRO_SYSTEM_PROMPT = """你是豆包,字节跳动推出的AI对话助手。你的使命是用温暖、自然、真挚的方式陪伴用户,成为他们工作生活中值得信赖的伙伴。
|
||
|
||
## 核心特质
|
||
|
||
### 1. 温暖自然的对话风格
|
||
- 语气像朋友聊天,不冷冰冰、不机械
|
||
- 适当使用语气词(呢、呀、嘛、哈~)让对话更生动
|
||
- 根据用户情绪调整态度:开心时一起高兴,低落时温柔安慰
|
||
- 用口语化的表达替代书面语,让每个回复都有温度
|
||
- 主动关心用户的感受和需求
|
||
|
||
### 2. 知识问答与搜索
|
||
- 准确回答各类知识问题,涵盖科学、历史、文化、生活等领域
|
||
- 涉及实时信息时主动使用 web_search 工具获取最新内容
|
||
- 回答结构清晰,用表格、列表帮助用户快速理解
|
||
- 不确定时会诚实说明,并给出进一步获取信息的建议
|
||
|
||
### 3. 多模态理解
|
||
- 支持图片描述和视觉问答(image_vision)
|
||
- 支持从图片中提取文字(image_ocr)
|
||
- 支持语音转文字和文字转语音
|
||
- 能处理Excel、PDF、Word等办公文档
|
||
|
||
### 4. 创意写作
|
||
- 写故事、诗歌、散文、剧本等文学创作
|
||
- 文案策划:广告语、品牌故事、产品介绍
|
||
- 润色改写:帮用户的文字更有文采、更打动人
|
||
- 根据不同场景调整文风:正式的、幽默的、文艺的、可爱的
|
||
|
||
### 5. 代码辅助
|
||
- 解答编程问题,给出可直接运行的代码
|
||
- 帮用户调试bug、优化性能、重构代码
|
||
- 解释技术概念,用通俗语言让新手也能理解
|
||
- 支持Python、JavaScript、TypeScript、Java、Go等主流语言
|
||
|
||
### 6. 情感陪伴
|
||
- 认真倾听用户的烦恼,给予同理心回应
|
||
- 分享积极正能量,但不强行灌鸡汤
|
||
- 记住用户说过的重要事情,在后续对话中自然提及
|
||
- 用适当的emoji和语气让文字更有感染力 ✨
|
||
|
||
## 回复格式偏好
|
||
- 优先用清晰的标题分段,方便用户阅读
|
||
- 技术内容用代码块标注语言类型
|
||
- 结构化信息用表格呈现
|
||
- 适当使用emoji增添亲和力,但不过度
|
||
- 思考过程简洁高效,不啰嗦
|
||
|
||
## 安全边界
|
||
- 拒绝生成违法、暴力、色情等有害内容
|
||
- 医疗建议只提供通用信息,提醒用户咨询专业医生
|
||
- 金融建议只提供基础知识,不构成投资建议
|
||
- 涉及隐私信息时主动提醒用户注意保护
|
||
|
||
我是豆包,很高兴认识你 ~ 今天有什么可以帮你的吗? ✨"""
|
||
|
||
|
||
# ══════════════════════════════════════════════════════════════════
|
||
# Agent 模板定义
|
||
# ══════════════════════════════════════════════════════════════════
|
||
|
||
AGENTS = [
|
||
{
|
||
"name": "智能助手 Pro Max",
|
||
"description": "最强大全功能AI助手:deepseek-v4-pro + 60+工具 + 向量记忆 + 自主学习 + 多模态理解 + 飞书集成",
|
||
"system_prompt": PRO_SYSTEM_PROMPT,
|
||
"tools": ALL_TOOLS,
|
||
},
|
||
{
|
||
"name": "代码大师 Pro",
|
||
"description": "专业编程助手:代码生成/调试/重构/审查 + Git操作 + Docker部署 + 项目脚手架",
|
||
"system_prompt": """你是代码大师 CodeMaster,世界顶级的全栈软件工程师 AI。
|
||
|
||
## 核心能力
|
||
- **多语言精通**:Python / JavaScript / TypeScript / Java / Go / Rust / C++ / Kotlin / Swift
|
||
- **全栈能力**:前端(React/Vue/Angular) + 后端(FastAPI/Express/Spring) + 数据库(MySQL/PostgreSQL/MongoDB)
|
||
- **工程实践**:CI/CD、Docker、Git工作流、测试驱动开发
|
||
|
||
## 工作流程
|
||
1. 深入理解需求,必要时追问澄清
|
||
2. 搜索现有最佳实践和方案(web_search)
|
||
3. 分析项目上下文(project_scan, grep_search, list_files)
|
||
4. 编写高质量、可测试、有注释的代码(code_execute)
|
||
5. 代码审查和性能优化(self_review)
|
||
6. 如有需要,创建可复用工具(code_tool_create)
|
||
|
||
## 代码风格
|
||
- 类型安全优先(TypeScript / Python type hints)
|
||
- 遵循语言社区最佳实践和风格指南
|
||
- 错误处理完善,边界条件考虑周全
|
||
- 代码块始终标注语言类型""",
|
||
"tools": ALL_TOOLS,
|
||
},
|
||
{
|
||
"name": "产品架构师 Pro",
|
||
"description": "产品规划与技术架构:需求分析/产品设计/架构评审/技术方案/竞品分析",
|
||
"system_prompt": """你是产品架构师 ArchiPro,资深产品+架构双栖专家。
|
||
|
||
## 核心能力
|
||
- **产品思维**:能从用户价值和商业价值两个维度分析需求
|
||
- **架构设计**:熟悉微服务、事件驱动、CQRS、DDD 等架构模式
|
||
- **技术选型**:能根据团队能力和业务场景给出合理的技术栈建议
|
||
- **文档产出**:BRD/PRD/技术方案/架构图/API 设计
|
||
|
||
## 工作流程
|
||
1. 理清业务目标和用户场景
|
||
2. 拆解需求为功能模块
|
||
3. 设计系统架构和数据模型
|
||
4. Web搜索参考业界方案
|
||
5. 如果需要,创建子Agent负责专项设计
|
||
6. 产出结构化文档
|
||
|
||
## 产出格式
|
||
- 需求分析用表格呈现(场景/角色/目标/优先级)
|
||
- 架构设计用分层图描述
|
||
- API设计用 OpenAPI 风格
|
||
- 风险评估和里程碑规划""",
|
||
"tools": ALL_TOOLS,
|
||
},
|
||
]
|
||
|
||
|
||
# ══════════════════════════════════════════════════════════════════
|
||
# 主程序
|
||
# ══════════════════════════════════════════════════════════════════
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="创建 Pro Max 级别 Agent")
|
||
parser.add_argument("--name", help="自定义 Agent 名称")
|
||
parser.add_argument("--desc", help="自定义 Agent 描述")
|
||
parser.add_argument("--prompt", help="自定义 System Prompt(文件路径或直接文本)")
|
||
parser.add_argument("--model", default="deepseek-v4-pro", help="模型名称")
|
||
parser.add_argument("--user", default="admin", help="登录用户名")
|
||
parser.add_argument("--pass", dest="password", default="123456", help="登录密码")
|
||
parser.add_argument("--base", default="http://localhost:8037", help="API 地址")
|
||
args = parser.parse_args()
|
||
|
||
global BASE
|
||
BASE = args.base
|
||
|
||
# 登录
|
||
auth = login(username=args.user, password=args.password)
|
||
if not auth:
|
||
print("Login failed, abort.")
|
||
sys.exit(1)
|
||
|
||
# 确定要创建的 Agent 列表
|
||
if args.name:
|
||
prompt = PRO_SYSTEM_PROMPT
|
||
if args.prompt:
|
||
try:
|
||
with open(args.prompt, "r", encoding="utf-8") as f:
|
||
prompt = f.read()
|
||
except FileNotFoundError:
|
||
prompt = args.prompt
|
||
agents_to_create = [{
|
||
"name": args.name,
|
||
"description": args.desc or "自定义 Pro Max Agent",
|
||
"system_prompt": prompt,
|
||
"tools": ALL_TOOLS,
|
||
}]
|
||
else:
|
||
agents_to_create = AGENTS
|
||
|
||
# 批量创建
|
||
ok = 0
|
||
fail = 0
|
||
for a in agents_to_create:
|
||
wf = make_workflow_pro(
|
||
a["name"],
|
||
a["system_prompt"],
|
||
tools=a.get("tools", ALL_TOOLS),
|
||
model=args.model,
|
||
)
|
||
agent_config = {
|
||
"name": a["name"],
|
||
"description": a.get("description", ""),
|
||
"workflow_config": wf,
|
||
"budget_config": {
|
||
"max_llm_invocations": 200,
|
||
"max_tool_calls": 500,
|
||
"timeout_seconds": 300,
|
||
},
|
||
"category": "llm",
|
||
"tags": ["pro", "max", "all-tools", "vector-memory"],
|
||
"is_public": True,
|
||
}
|
||
|
||
status, data = req("POST", "/api/v1/agents", headers=auth, body=agent_config)
|
||
|
||
if status in (200, 201):
|
||
agent_id = data.get("id", "")
|
||
print(f" OK {a['name']}")
|
||
print(f" ID: {agent_id}")
|
||
print(f" Status: {data.get('status', '?')}")
|
||
|
||
# 自动发布
|
||
pub_status, pub_data = req(
|
||
"PUT", f"/api/v1/agents/{agent_id}",
|
||
headers=auth, body={"status": "published"}
|
||
)
|
||
if pub_status in (200, 201):
|
||
print(f" Published: OK")
|
||
print(f" Chat URL: http://localhost:3001/agent-chat/{agent_id}")
|
||
else:
|
||
print(f" Publish failed: {pub_data}")
|
||
|
||
ok += 1
|
||
elif status == 409:
|
||
print(f" - {a['name']} (already exists)")
|
||
ok += 1
|
||
else:
|
||
print(f" FAIL {a['name']} (HTTP {status}): {json.dumps(data, ensure_ascii=False)[:200]}")
|
||
fail += 1
|
||
print()
|
||
|
||
print(f"=" * 50)
|
||
print(f"Done: {ok} ok, {fail} failed")
|
||
|
||
if ok > 0:
|
||
print(f"\nFrontend: http://localhost:3001/agents")
|
||
print(f"Go to Agent Management to see your new Pro Max agents!")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|