chore: 更新配置文件和环境变量示例

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-13 21:29:22 +08:00
parent 249e7e577a
commit 903b772a06
5 changed files with 282 additions and 796 deletions

View File

@@ -4,7 +4,261 @@
"Bash(npm install)",
"Bash(npm run dev)",
"Bash(npm run build)",
"Bash(npm install echarts)"
"Bash(npm install echarts)",
"mcp__web-search-prime__webSearchPrime",
"Bash(git add web/src/style.css web/src/views/Agents.vue web/src/views/MCP.vue web/src/views/ModelAPIs.vue)",
"Bash(git commit:*)",
"Bash(ls -la *.yml *.yaml)",
"Bash(python3 -c \"import yaml; yaml.safe_load\\(open\\(''docker-compose.yml''\\)\\)\")",
"Bash(python -c \"import yaml; yaml.safe_load\\(open\\(''docker-compose.yml''\\)\\)\")",
"Bash(docker compose version)",
"Bash(docker compose convert)",
"Bash(test-compose.yml:*)",
"Bash(docker compose -f test-compose.yml config)",
"Bash(test-compose2.yml:*)",
"Bash(docker compose -f test-compose2.yml config)",
"Bash(docker compose up -d)",
"Bash(docker context ls)",
"Bash(docker compose -f compose.yml config)",
"Bash(docker compose -f compose.yml config --quiet)",
"Bash(docker-compose --version)",
"Bash(docker compose -f D:/Code/Project/X-Agents/docker-compose.yml config)",
"Bash(docker compose -f \"D:\\\\Code\\\\Project\\\\X-Agents\\\\docker-compose.yml\" config)",
"Bash(printf 'version: \"\"3.8\"\"\\\\n\\\\nnetworks:\\\\n x-agents-network:\\\\n driver: bridge\\\\n\\\\nvolumes:\\\\n db-data:\\\\n redis-data:\\\\n qdrant-data:\\\\n agent-data:\\\\n\\\\nservices:\\\\n server:\\\\n build:\\\\n context: ./server\\\\n dockerfile: Dockerfile\\\\n container_name: x-agents-server\\\\n ports:\\\\n - \"\"8080:8080\"\"\\\\n environment:\\\\n - PORT=8080\\\\n - JWT_SECRET=${JWT_SECRET:-your-secret-key-change-in-production}\\\\n - DATABASE_URL=postgres://postgres:postgres@db:5432/x_agents?sslmode=disable\\\\n - PYTHON_SERVICE_URL=http://agent:8081\\\\n depends_on:\\\\n db:\\\\n condition: service_healthy\\\\n agent:\\\\n condition: service_started\\\\n restart: unless-stopped\\\\n networks:\\\\n - x-agents-network\\\\n\\\\n agent:\\\\n build:\\\\n context: ./agent\\\\n dockerfile: Dockerfile\\\\n container_name: x-agents-agent\\\\n ports:\\\\n - \"\"8081:8081\"\"\\\\n environment:\\\\n - PYTHON_SERVICE_PORT=8081\\\\n - LLM_PROVIDER=${LLM_PROVIDER:-openai}\\\\n - OPENAI_API_KEY=${OPENAI_API_KEY:-}\\\\n - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}\\\\n volumes:\\\\n - ./agent/app:/app/app\\\\n - agent-data:/app/data\\\\n restart: unless-stopped\\\\n networks:\\\\n - x-agents-network\\\\n\\\\n db:\\\\n image: postgres:15-alpine\\\\n container_name: x-agents-db\\\\n environment:\\\\n POSTGRES_USER: postgres\\\\n POSTGRES_PASSWORD: postgres\\\\n POSTGRES_DB: x_agents\\\\n volumes:\\\\n - db-data:/var/lib/postgresql/data\\\\n ports:\\\\n - \"\"5432:5432\"\"\\\\n healthcheck:\\\\n test: [\"\"CMD-SHELL\"\", \"\"pg_isready -U postgres\"\"]\\\\n interval: 10s\\\\n timeout: 5s\\\\n retries: 5\\\\n restart: unless-stopped\\\\n networks:\\\\n - x-agents-network\\\\n\\\\n redis:\\\\n image: redis:7-alpine\\\\n container_name: x-agents-redis\\\\n ports:\\\\n - \"\"6379:6379\"\"\\\\n volumes:\\\\n - redis-data:/data\\\\n restart: unless-stopped\\\\n networks:\\\\n - x-agents-network\\\\n\\\\n qdrant:\\\\n image: qdrant/qdrant:v1.7.0\\\\n container_name: x-agents-qdrant\\\\n ports:\\\\n - \"\"6333:6333\"\"\\\\n - \"\"6334:6334\"\"\\\\n volumes:\\\\n - qdrant-data:/qdrant/storage\\\\n restart: unless-stopped\\\\n networks:\\\\n - x-agents-network\\\\n')",
"Bash(powershell.exe -Command \"Remove-Item docker-compose.yml -ErrorAction SilentlyContinue; Write-Host ''removed''\")",
"Bash(powershell.exe -NoProfile -Command '@\"\":*)",
"Bash(DEBUG=*)",
"Bash(docker compose config -p x-agents)",
"Bash(docker info)",
"Bash(docker compose ls)",
"Bash(go mod tidy)",
"Bash(docker run --rm -v D:/Code/Project/X-Agents/server:/app -w /app golang:1.21 go mod tidy)",
"Bash(where go)",
"Bash(npx vue-tsc --noEmit)",
"Bash(go env -w GOPROXY=https://goproxy.cn,direct)",
"Bash(curl -X POST http://localhost:8082/database/add -H \"Content-Type: application/json\" -d '{\"\"name\"\":\"\"test\"\",\"\"db_type\"\":\"\"mysql\"\",\"\"host\"\":\"\"localhost\"\",\"\"port\"\":6036,\"\"username\"\":\"\"root\"\",\"\"password\"\":\"\"root\"\",\"\"database\"\":\"\"x_agents\"\"}')",
"Bash(go build -o api.exe ./cmd/api)",
"Bash(curl -s -X POST http://localhost:8082/database/add -H \"Content-Type: application/json\" -d '{\"\"name\"\":\"\"测试数据库\"\",\"\"description\"\":\"\"测试\"\",\"\"db_type\"\":\"\"MySQL\"\",\"\"host\"\":\"\"localhost\"\",\"\"port\"\":3306,\"\"username\"\":\"\"root\"\",\"\"password\"\":\"\"123123\"\",\"\"database\"\":\"\"testdb\"\"}')",
"Bash(taskkill //F //IM api.exe)",
"Bash(go run temp_add_data.go)",
"Bash(ping -n 1 10.10.10.189)",
"Bash(nc -zv 10.10.10.189 3306)",
"Bash(powershell.exe -Command \"Test-NetConnection -ComputerName 10.10.10.189 -Port 3306\")",
"Bash(go run temp_grant.go)",
"Bash(go run temp_fix.go)",
"Bash(go run temp_add_data2.go)",
"Bash(go run temp_regrant.go)",
"Bash(go run temp_newuser.go)",
"Bash(go run temp_check.go)",
"Bash(go run temp_reset.go)",
"Bash(go run temp_native.go)",
"Bash(go get github.com/shirou/gopsutil/v3/mem)",
"Bash(curl -s -X POST http://localhost:8080/api/database/check -H \"Content-Type: application/json\" -d '{\"\"db_type\"\":\"\"mysql\"\",\"\"host\"\":\"\"localhost\"\",\"\"port\"\":3306,\"\"username\"\":\"\"root\"\",\"\"password\"\":\"\"root\"\",\"\"database\"\":\"\"test\"\",\"\"charset\"\":\"\"utf8mb4\"\"}')",
"Bash(docker ps --format \"table {{.Names}}\\\\t{{.Ports}}\")",
"Bash(curl -s -X POST http://localhost:8082/api/database/check -H \"Content-Type: application/json\" -d '{\"\"db_type\"\":\"\"mysql\"\",\"\"host\"\":\"\"localhost\"\",\"\"port\"\":6036,\"\"username\"\":\"\"root\"\",\"\"password\"\":\"\"root\"\",\"\"database\"\":\"\"x_agents\"\",\"\"charset\"\":\"\"utf8mb4\"\"}')",
"Bash(netstat -ano)",
"Bash(findstr \"8082\")",
"Bash(curl -s -X POST http://localhost:8082/database/check -H \"Content-Type: application/json\" -d '{\"\"db_type\"\":\"\"mysql\"\",\"\"host\"\":\"\"localhost\"\",\"\"port\"\":6036,\"\"username\"\":\"\"root\"\",\"\"password\"\":\"\"root\"\",\"\"database\"\":\"\"x_agents\"\",\"\"charset\"\":\"\"utf8mb4\"\"}')",
"Bash(taskkill //F //FI \"IMAGENAME eq api.exe\")",
"Bash(taskkill //F //FI \"IMAGENAME eq main.exe\")",
"Bash(findstr \":8082\")",
"Bash(findstr \"LISTENING\")",
"Bash(taskkill //F //PID 70176)",
"Bash(taskkill //F //PID 71260)",
"Bash(taskkill //F //PID 63192)",
"Bash(curl -s -X POST http://localhost:8082/database/check -H \"Content-Type: application/json\" -d '{\"\"db_type\"\":\"\"mysql\"\",\"\"host\"\":\"\"localhost\"\",\"\"port\"\":6036,\"\"username\"\":\"\"root\"\",\"\"password\"\":\"\"root\"\",\"\"database\"\":\"\"x_agents\"\",\"\"database_id\"\":\"\"test-id\"\"}')",
"Bash(taskkill //F //PID 43848)",
"Bash(taskkill //F //PID 35324)",
"Bash(taskkill //F //PID 74868)",
"Bash(go build ./cmd/api/main.go)",
"Bash(curl -s -X POST http://localhost:8082/database/add -H \"Content-Type: application/json\" -d '{:*)",
"Bash(taskkill //F //PID 49692)",
"Bash(curl -s -X POST http://localhost:8082/database/check -H \"Content-Type: application/json\" -d '{:*)",
"Bash(taskkill //F //PID 40216)",
"Bash(curl -s http://localhost:8082/sub-table/database/68b6fb60-eae2-495b-b248-9c46c8d8d6cb)",
"Bash(taskkill //F //PID 59688)",
"Bash(taskkill //F //PID 55352)",
"Bash(taskkill //F //PID 71716)",
"Bash(git add .gitignore)",
"Bash(git add agent/ server/ docs/ web/src/ .env.example docker-compose.yml docker-compose.dev.yml start-local.ps1 team-require/)",
"Bash(git add web/agents.html web/dashboard.html web/graph.html)",
"Bash(go get github.com/neo4j/neo4j-driver-go/v5@latest)",
"Bash(go build -o /dev/null ./cmd/api/main.go)",
"mcp__web-search-prime__web_search_prime",
"Bash(curl -X POST http://localhost:8080/neo4j/check -H \"Content-Type: application/json\" -d '{\"\"host\"\":\"\"10.10.10.189\"\",\"\"port\"\":7687,\"\"username\"\":\"\"neo4j\"\",\"\"password\"\":\"\"neo4j\"\"}')",
"Bash(curl -X POST http://localhost:8082/neo4j/check -H \"Content-Type: application/json\" -d '{\"\"host\"\":\"\"10.10.10.189\"\",\"\"port\"\":7687,\"\"username\"\":\"\"neo4j\"\",\"\"password\"\":\"\"neo4j\"\"}')",
"Bash(go build -o server.exe ./cmd/api/main.go)",
"Bash(curl -X POST http://localhost:8082/neo4j/check -H \"Content-Type: application/json\" -d '{\"\"host\"\":\"\"10.10.10.189\"\",\"\"port\"\":7687,\"\"username\"\":\"\"password\"\":\"\"neo4neo4j\"\",\"\"j\"\"}')",
"Bash(curl -X POST \"http://localhost:8082/neo4j/check\" -H \"Content-Type: application/json\" -d \"{\"\"host\"\":\"\"10.10.10.189\"\",\"\"port\"\":7687,\"\"username\"\":\"\"neo4j\"\",\"\"password\"\":\"\"neo4j\"\"}\")",
"Bash(curl -s http://localhost:8082/system/info)",
"Bash(curl -s -X POST \"http://localhost:8082/neo4j/check\" -H \"Content-Type: application/json\" -d \"{\"\"host\"\":\"\"10.10.10.189\"\",\"\"port\"\":7687,\"\"username\"\":\"\"neo4j\"\",\"\"password\"\":\"\"neo4j\"\"}\")",
"Bash(curl -v -X POST \"http://localhost:8082/neo4j/check\" -H \"Content-Type: application/json\" -d \"{\"\"host\"\":\"\"10.10.10.189\"\",\"\"port\"\":7687,\"\"username\"\":\"\"neo4j\"\",\"\"password\"\":\"\"neo4j\"\"}\")",
"Bash(findstr :8082)",
"Bash(taskkill /F /PID 68728)",
"Bash(powershell -Command \"Stop-Process -Id 68728 -Force\")",
"Bash(cmd //c \"taskkill /F /PID 68728\")",
"Bash(curl -s -X POST \"http://localhost:8082/database/check\" -H \"Content-Type: application/json\" -d \"{\"\"db_type\"\":\"\"neo4j\"\",\"\"uri\"\":\"\"bolt://10.10.10.189:7687\"\",\"\"username\"\":\"\"neo4j\"\",\"\"password\"\":\"\"neo4j\"\",\"\"database\"\":\"\"neo4j\"\"}\")",
"Bash(curl -s -X POST \"http://localhost:8082/database/check\" -H \"Content-Type: application/json\" -d \"{\"\"db_type\"\":\"\"neo4j\"\",\"\"host\"\":\"\"10.10.10.189\"\",\"\"port\"\":7687,\"\"uri\"\":\"\"bolt://10.10.10.189:7687\"\",\"\"username\"\":\"\"neo4j\"\",\"\"password\"\":\"\"neo4j\"\",\"\"database\"\":\"\"neo4j\"\"}\")",
"Bash(findstr LISTENING)",
"Bash(cmd //c \"taskkill //F //PID 80208\")",
"Bash(powershell -NoProfile -Command \"Stop-Process -Id 80208 -Force -ErrorAction SilentlyContinue\")",
"Bash(npx vite build)",
"Bash(ls d:/Code/Project/X-Agents/web/*.md)",
"Bash(go build -o server.exe ./cmd/api)",
"Bash(ls -la /d/Code/Project/X-Agents/server/*.go)",
"Bash(npm run type-check)",
"Bash(go build ./...)",
"Bash(grep -i \"ensureNeo4j\\\\|Check.*确保\\\\|Check.*database\" \"d:/Code/Project/X-Agents/server/logs/2026-03-06/\"*.log)",
"Bash(ls -la /d/Code/Project/X-Agents/web/src/*.css)",
"Bash(git add server/ web/src/ team-require/)",
"Bash(python \"C:/Users/caoxiaozhu/.claude/skills/skill-creator/scripts/init_skill.py\" write-requirement --path \"C:/Users/caoxiaozhu/.claude/skills\")",
"WebFetch(domain:github.com)",
"Bash(gh repo view Tencent/WeKnora --json name,description,readme,url)",
"mcp__web-reader__webReader",
"WebFetch(domain:minimax-algeng-chat-tts.oss-cn-wulanchabu.aliyuncs.com)",
"Bash(npx vue-tsc --noEmit src/views/Settings.vue)",
"Bash(curl -s http://localhost:5173)",
"Bash(curl -s http://localhost:8082/model/test -X POST -H \"Content-Type: application/json\" -d '{}')",
"Bash(curl -s http://localhost:8082/model/test -X POST -H \"Content-Type: application/json\" -d '{\"\"provider\"\":\"\"OpenAI\"\",\"\"model\"\":\"\"gpt-4\"\",\"\"api_key\"\":\"\"test\"\",\"\"base_url\"\":\"\"https://api.openai.com/v1\"\"}')",
"Bash(go build -o api.exe ./cmd/api/)",
"Bash(go get github.com/minio/minio-go/v7)",
"Bash(curl -s --connect-timeout 5 http://localhost:5173)",
"Bash(npx vue-tsc --noEmit src/views/MCP.vue)",
"Bash(curl -s -o /dev/null -w \"%{http_code}\" http://localhost:8082/api/knowledge/list)",
"Bash(curl -s http://localhost:8082/api/knowledge/list)",
"Bash(python -m venv venv)",
"Bash(powershell -Command \"Move-Item -Path ''algorithm'' -Destination ''ai-core'' -Force\")",
"Bash(python -c \"import sys; sys.path.insert\\(0, ''proto''\\); import docparser_pb2; print\\(''OK''\\)\")",
"Bash(python -c \"import document_parser_pb2; print\\(dir\\(document_parser_pb2\\)\\)\")",
"Bash(python -c \"import google.protobuf; print\\(google.protobuf.__version__\\)\")",
"Bash(python generate_grpc.py)",
"Bash(pip install grpcio-tools)",
"Bash(timeout 5 python main.py)",
"Bash(pip install grpcio-reflection)",
"Bash(pip install -r requirements.txt)",
"Bash(where python)",
"Bash(./venv/Scripts/pip.exe install -r requirements.txt)",
"Bash(./venv/Scripts/python.exe generate_grpc.py)",
"Bash(timeout 3 ./start.bat)",
"Bash(timeout 3 bash start.sh)",
"Bash(source venv/Scripts/activate)",
"Bash(curl -s http://localhost:50051/health)",
"Bash(timeout 10 python main.py)",
"Bash(findstr 50051)",
"Bash(findstr \"50051\\\\|50052\")",
"Bash(findstr \":50051\\\\|:50052\")",
"Bash(findstr \":50051\")",
"Bash(cd:*)",
"Read(//c/Users/caoxiaozhu/.claude/skills/ui-ux-pro-max/**)",
"Bash(python scripts/search.py \"signup registration form dark theme SaaS\" --design-system -p \"X-Agents Signup\")",
"Bash(cd D:/Code/Project/X-Agents/server && go build ./cmd/api/...)",
"Bash(git add:*)",
"Bash(cd D:/Code/Project/X-Agents/server && go get -u github.com/swaggo/swag/cmd/swag)",
"Bash(cd D:/Code/Project/X-Agents/server && go get -u github.com/swaggo/gin-swagger && go get -u github.com/swaggo/files)",
"Bash(cd D:/Code/Project/X-Agents/server && npx swag init -g cmd/api/main.go -o docs --parseDependency --parseInternal)",
"Bash(cd D:/Code/Project/X-Agents/server && go run github.com/swaggo/swag/cmd/swag@latest init -g cmd/api/main.go -o docs --parseDependency --parseInternal)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\server\\\\docs\" && cat swagger.json | python -c \"import json,sys; d=json.load\\(sys.stdin\\); print\\('\\\\n'.join\\(d['paths'].keys\\(\\)\\)\\)\")",
"Bash(sleep 3 && curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"admin\\\\\",\\\\\"password\\\\\":\\\\\"admin\\\\\",\\\\\"email\\\\\":\\\\\"admin@example.com\\\\\"}\")",
"Bash(cd D:/Code/Project/X-Agents/server && go run cmd/api/main.go 2>&1 | head -30)",
"Bash(sleep 5 && curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"admin\\\\\",\\\\\"password\\\\\":\\\\\"admin\\\\\",\\\\\"email\\\\\":\\\\\"admin@example.com\\\\\"}\")",
"Bash(mysql -h localhost -P 6036 -u root -proot -e \"USE x_agents; SHOW TABLES;\")",
"Bash(curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"admin\\\\\",\\\\\"password\\\\\":\\\\\"admin\\\\\",\\\\\"email\\\\\":\\\\\"admin@example.com\\\\\"}\")",
"Bash(sleep 8 && curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"admin\\\\\",\\\\\"password\\\\\":\\\\\"admin\\\\\",\\\\\"email\\\\\":\\\\\"admin@example.com\\\\\"}\")",
"Bash(cd D:/Code/Project/X-Agents/server && timeout 10 go run cmd/api/main.go 2>&1 || true)",
"Bash(taskkill /F /IM server.exe 2>/dev/null; sleep 2)",
"Bash(cd D:/Code/Project/X-Agents/server && go run cmd/api/main.go 2>&1 | head -20)",
"Bash(taskkill /F /IM server.exe 2>/dev/null; taskkill /F /IM go.exe 2>/dev/null; sleep 3)",
"Bash(cd D:/Code/Project/X-Agents/server && timeout 20 go run cmd/api/main.go 2>&1 || true)",
"Bash(sleep 3 && curl -X POST http://localhost:8082/auth/login -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"admin\\\\\",\\\\\"password\\\\\":\\\\\"admin\\\\\"}\")",
"Bash(sleep 5 && curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"testuser\\\\\",\\\\\"password\\\\\":\\\\\"123456\\\\\",\\\\\"email\\\\\":\\\\\"test@example.com\\\\\"}\")",
"Bash(sleep 3 && curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"user2\\\\\",\\\\\"password\\\\\":\\\\\"123456\\\\\",\\\\\"email\\\\\":\\\\\"user2@example.com\\\\\"}\")",
"Bash(cd D:/Code/Project/X-Agents/server && rm -f server.exe && go build -o server.exe ./cmd/api/... && ls -la server.exe)",
"Bash(sleep 4 && curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"user3\\\\\",\\\\\"password\\\\\":\\\\\"123456\\\\\",\\\\\"email\\\\\":\\\\\"user3@example.com\\\\\"}\")",
"Bash(sleep 4 && curl -X POST http://localhost:8082/auth/register -H \"Content-Type: application/json\" -d \"{\\\\\"username\\\\\":\\\\\"user4\\\\\",\\\\\"password\\\\\":\\\\\"123456\\\\\",\\\\\"email\\\\\":\\\\\"user4@example.com\\\\\"}\")",
"Bash(curl -s http://localhost:8082/auth/login -X POST -H \"Content-Type: application/json\" -d '{\"username\":\"admin\",\"password\":\"admin\"}')",
"Bash(TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NzM4MDQ3NzcsImV4cGlyZXNfYXQiOiIyMDI2LTAzLTE4VDExOjMyOjU3KzA4OjAwIiwiaWF0IjoxNzczMTk5OTc3LCJyb2xlIjoidXNlciIsInN1YiI6Ijg3NDgxMjlkLWM1NTYtNDM4NS04OGE5LWY5MTRjNzU4NDg3ZCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.VILfFUxl8nYbwfsYHeGvIwTaxgxWPb43mihI-pNNxWk\" && curl -s http://localhost:8082/user/list -H \"Authorization: Bearer $TOKEN\")",
"Bash(sleep 4 && curl -s http://localhost:8082/auth/login -X POST -H \"Content-Type: application/json\" -d '{\"username\":\"admin\",\"password\":\"admin\"}' | head -c 200)",
"Bash(cd D:/Code/Project/X-Agents/server && go build -o server.exe ./cmd/api/... 2>&1)",
"Bash(tasklist | grep -i server)",
"Bash(curl -s http://localhost:8082/swagger/index.html | head -20)",
"Bash(curl -s http://localhost:8082/swagger.json | grep -o '\"/user[^\"]*\"' | head -10)",
"Bash(curl -s \"http://localhost:8082/database/list\")",
"Bash(taskkill /F /IM server.exe 2>/dev/null; sleep 1)",
"Bash(taskkill /PID 48088 /F)",
"Bash(taskkill.exe //PID 48088 //F)",
"Bash(cd \"D:/Code/Project/X-Agents/web\" && npm install lucide-vue-next)",
"Bash(mkdir -p \"D:/Code/Project/X-Agents/agent/app/core/tools/impl\" && mkdir -p \"D:/Code/Project/X-Agents/agent/app/core/tools/sandbox\")",
"Bash(cd D:/Code/Project/X-Agents/server && go build -o server.exe ./cmd/api/)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\web\" && npm install monaco-editor)",
"Bash(curl -s http://localhost:8082/tools)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\web\" && npm install -D vite-plugin-monaco-editor)",
"Bash(mysql -h localhost -P 6036 -u root -proot x_agents -e \"CREATE TABLE IF NOT EXISTS tools \\(id VARCHAR\\(191\\) PRIMARY KEY, name VARCHAR\\(100\\) UNIQUE NOT NULL, description TEXT, category VARCHAR\\(50\\) NOT NULL, provider VARCHAR\\(100\\), status VARCHAR\\(20\\) DEFAULT 'active', created_at DATETIME\\(3\\), updated_at DATETIME\\(3\\), INDEX idx_tools_category \\(category\\), INDEX idx_tools_name \\(name\\)\\);\")",
"Bash(mysql -h localhost -P 6036 -u root -proot x_agents -e \"\nINSERT INTO tools \\(id, name, description, category, provider, status, created_at, updated_at\\) VALUES\n\\(UUID\\(\\), 'read_file', '读取文件', '文件操作', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'write_file', '写入文件', '文件操作', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'list_dir', '列出目录', '文件操作', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'delete_file', '删除文件', '文件操作', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'search_files', '搜索文件', '文件操作', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'execute_python', '执行Python', '代码执行', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'execute_javascript', '执行JavaScript', '代码执行', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'execute_bash', '执行Bash命令', '代码执行', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'web_fetch', '获取网页', '网页', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'web_search', '搜索网页', '网页', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'http_request', 'HTTP请求', '通信', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'send_notification', '发送通知', '通信', 'system', 'active', NOW\\(\\), NOW\\(\\)\\),\n\\(UUID\\(\\), 'get_current_time', '获取时间', '工具', 'system', 'active', NOW\\(\\), NOW\\(\\)\\)\nON DUPLICATE KEY UPDATE description=VALUES\\(description\\), category=VALUES\\(category\\);\n\")",
"Bash(curl -s http://localhost:8080/tool/list 2>/dev/null || curl -s http://localhost:3000/tool/list 2>/dev/null || echo \"Server not running on common ports\")",
"Bash(curl -s http://localhost:8082/tool/list)",
"Bash(git push:*)",
"Bash(git remote:*)",
"Bash(git reset:*)",
"Bash(cd \"D:/Code/Project/X-Agents/account/admin/\" && mv projects sandbox)",
"Read(//d/Code/Project/**)",
"Bash(mv projects:*)",
"Bash(mkdir-Agents/account/le -p skills scripts)",
"Bash(cd \"D:/Code/Project/X-Agents/server\" && swag init -g cmd/api/main.go -o docs --parseDependency --parseInternal)",
"Bash(cd \"D:/Code/Project/X-Agents/server\" && go install github.com/swaggo/swag/cmd/swag@latest)",
"Bash(find \"D:/Code/Project/X-Agents\" -name \"python_*.log\" 2>/dev/null | head -10)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\server\" && go run ./cmd/api)",
"Bash(taskkill /PID 49852 /F)",
"Bash(taskkill //PID 49852 //F)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\server\" && go build ./cmd/api 2>&1 | head -20)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\server\" && go build ./cmd/api 2>&1)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\server\" && go run ./cmd/api 2>&1 | head -30)",
"Bash(curl -N -X POST http://localhost:8081/agent/chat/stream -H \"Content-Type: application/json\" -d \"{\\\\\"agent_id\\\\\":1,\\\\\"message\\\\\":\\\\\"你好\\\\\"}\" 2>&1 | head -20)",
"Bash(curl -N -X POST http://localhost:8081/agent/chat/stream -H \"Content-Type: application/json\" -d \"{\\\\\"agent_id\\\\\":1,\\\\\"message\\\\\":\\\\\"你好\\\\\",\\\\\"user_id\\\\\":1}\" 2>&1 | head -30)",
"Bash(curl -N -X POST http://localhost:8082/api/agent/chat/stream -H \"Content-Type: application/json\" -d \"{\\\\\"agent_id\\\\\":1,\\\\\"message\\\\\":\\\\\"hello\\\\\"}\" 2>&1 | head -50)",
"Bash(curl -N -X POST http://localhost:5173/api/agent/chat/stream -H \"Content-Type: application/json\" -d \"{\\\\\"agent_id\\\\\":1,\\\\\"message\\\\\":\\\\\"hello\\\\\"}\" 2>&1 | head -30)",
"Bash(curl -s http://localhost:8082/api/model/list 2>&1)",
"Bash(curl -s http://localhost:8082/model/list 2>&1)",
"Bash(pkill -f \"go run cmd/api/main.go\" 2>/dev/null || taskkill //F //IM api.exe 2>/dev/null || true)",
"Bash(curl -N -X POST http://localhost:5173/api/agent/chat/stream -H \"Content-Type: application/json\" -d \"{\\\\\"agent_id\\\\\":1,\\\\\"message\\\\\":\\\\\"hello\\\\\",\\\\\"model_id\\\\\":\\\\\"44c82db8-5321-44a4-8caa-0829afa2c0d9\\\\\"}\" 2>&1 | head -20)",
"Bash(taskkill //F //IM node.exe 2>/dev/null || true)",
"Bash(taskkill //F //PID 52048)",
"Bash(cd \"C:\\\\Users\\\\caoxiaozhu\\\\.claude\\\\skills\\\\ui-ux-pro-max\" && python scripts/search.py \"chat message bubble design\" --design-system -p \"Chat UI\")",
"Bash(git -C \"D:/Code/Project/X-Agents\" diff web/src/views/Agents.vue | head -100)",
"Bash(git -C \"D:/Code/Project/X-Agents\" checkout -- web/src/views/Agents.vue)",
"Bash(cd D:/Code/Project/X-Agents && curl -s -X POST http://localhost:8082/skill/add -F \"skill_name=test\" -F \"skill_desc=test desc\" -F \"skill_type=user\" 2>&1)",
"Bash(cd D:/Code/Project/X-Agents/server && go run cmd/api/main.go 2>&1 | head -100)",
"Bash(sleep 3 && curl -s -X POST http://localhost:8082/skill/add -F \"skill_name=test\" -F \"skill_desc=test desc\" -F \"skill_type=user\" 2>&1)",
"Bash(sleep 3 && curl -s -X POST http://localhost:8082/skill/add -F \"skill_name=test123\" -F \"skill_desc=test desc\" -F \"skill_type=user\" 2>&1)",
"Bash(cd D:/Code/Project/X-Agents/server && timeout 5 go run cmd/api/main.go 2>&1 || true)",
"Bash(taskkill /F /IM \"main.exe\" 2>/dev/null || true)",
"Bash(cd D:/Code/Project/X-Agents/web && npx vue-tsc --noEmit src/views/skill/useSkills.ts src/views/Skill.vue 2>&1 | head -30)",
"Bash(curl -s http://localhost:8082/skill/6974b449-c1c6-4ab2-921a-f244d035cba7/content 2>&1)",
"Bash(cd D:/Code/Project/X-Agents/server && swag init -g cmd/api/main.go -o docs 2>&1)",
"Bash(cd D:/Code/Project/X-Agents/server && go build -o /dev/null ./internal/handler/...)",
"Bash(cd D:/Code/Project/X-Agents/server && go vet ./internal/handler/skill_handler.go 2>&1 || true)",
"Bash(curl -s http://localhost:8081/agent/list 2>&1)",
"Bash(netstat -ano | findstr \"8081\" 2>&1 | head -5)",
"Bash(curl -s http://localhost:8081/agent/list 2>&1 || echo \"Python service not running\")",
"Bash(cd D:/Code/Project/X-Agents/server && timeout 5 ./server.exe 2>&1 || true)",
"Bash(curl -s http://localhost:8082/api/agent/list 2>&1)",
"Bash(curl -s \"http://localhost:8082/database/a89dfc3e-5089-4a9e-8f6b-991d5bebd85d\" 2>&1)",
"Bash(curl -s -X POST http://localhost:8082/api/agent/create -H \"Content-Type: application/json\" -d '{\"name\":\"test-agent\",\"description\":\"test\",\"avatar\":\"🤖\",\"skillsMode\":\"all\",\"skills\":[],\"knowledge\":\"none\",\"prompt\":\"test prompt\"}' 2>&1)",
"Bash(curl -s http://localhost:8082/skill/list 2>&1 | head -20)",
"Bash(taskkill /F /PID 19976)",
"Bash(powershell -Command \"Stop-Process -Id 19976 -Force\")",
"Bash(cmd //c \"taskkill /F /PID 19976\")",
"Bash(curl -s http://localhost:8082/skill/list 2>&1 | head -100)",
"Bash(cd D:/Code/Project/X-Agents/web && npm install jszip)",
"Bash(curl -s http://localhost:8082/model/list | head -200)",
"Bash(curl -s \"http://localhost:8082/model/list\" | python -m json.tool 2>/dev/null || curl -s \"http://localhost:8082/model/list\")",
"Bash(curl -s \"http://localhost:5173/model/list\" 2>&1 | head -50)",
"Bash(sleep 5 && curl -s \"http://localhost:5173/model/list\" 2>&1 | head -100)",
"Bash(curl -s \"http://localhost:5173/src/views/chat/chat.ts\" 2>&1 | head -10)",
"Bash(curl -s \"http://localhost:5173/src/views/chat/chat.ts\" 2>&1 | grep -A5 \"fetchModels\")",
"Bash(cd \"D:/Code/Project/X-Agents/agent\" && pip install -r requirements.txt -q)",
"Bash(curl -s \"http://localhost:5173/src/views/chat/chat.ts\" 2>&1 | grep -A15 \"const fetchModels\")",
"Bash(curl -s \"http://localhost:5173/api/model/list\" 2>&1 | head -50)",
"Bash(cd \"D:\\\\Code\\\\Project\\\\X-Agents\\\\web\" && npx vue-tsc --noEmit src/views/Agents.vue 2>&1 | head -30)"
]
}
}

View File

@@ -1,11 +1,30 @@
# JWT 配置
JWT_SECRET=your-secret-key-change-in-production
# ========================================
# X-Agents 全局配置文件
# ========================================
# 将此文件复制为 .env 后修改配置
# LLM 提供商 (openai / anthropic)
LLM_PROVIDER=openai
# ========================================
# Go 后端配置
# ========================================
GO_PORT=8082
GO_DATABASE_TYPE=mysql # 可选值: mysql, sqlite
GO_DATABASE_HOST=localhost
GO_DATABASE_PORT=6036
GO_DATABASE_NAME=x_agents
GO_DATABASE_USER=root
GO_DATABASE_PASSWORD=
GO_SQLITE_PATH=./data/x_agents.db # SQLite 数据库文件路径
# OpenAI API Key
OPENAI_API_KEY=your-openai-api-key
# ========================================
# Python Agent 配置
# ========================================
PYTHON_PORT=8001
PYTHON_WORKSPACE=./workspace
PYTHON_LLM_PROVIDER=openai
PYTHON_LLM_API_KEY=
PYTHON_LLM_MODEL=gpt-4o
# Anthropic API Key
ANTHROPIC_API_KEY=your-anthropic-api-key
# ========================================
# Web 前端配置
# ========================================
WEB_PORT=5173

View File

@@ -1,655 +0,0 @@
# 智能体系统实现计划
## 项目概述
设计并实现一个支持单智能体独立工作 + 多智能体协作的混合型智能体系统,具备长短时记忆、多种技能调用能力。
## 技术架构
```
┌─────────────────────────────────────────────────────────────────┐
│ 用户请求入口 │
└─────────────────────────────┬───────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ API Gateway (Go) │
│ /api/v1/agents/:id/chat │
└─────────────────────────────┬───────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Agent Engine (Python) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Agent Core │ │ Supervisor │ │ Memory │ │
│ │ (单智能体) │ │ (多智能体) │ │ (长短时) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └────────┬────────┴──────────────────┘ │
│ ↓ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Skill Router (技能路由器) │ │
│ └──────────────────────────┬───────────────────────────┘ │
│ ↓ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Skill Executor (执行器) │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
## 1. 数据库设计
### 1.1 新增表结构
```sql
-- 智能体配置表 (agents)
CREATE TABLE agents (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
role_description TEXT,
model_provider VARCHAR(50),
model_name VARCHAR(100),
status VARCHAR(20) DEFAULT 'active',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- 技能绑定表
CREATE TABLE agent_skills (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
agent_id BIGINT NOT NULL,
skill_id BIGINT NOT NULL,
skill_config JSON,
FOREIGN KEY (agent_id) REFERENCES agents(id),
FOREIGN KEY (skill_id) REFERENCES skills(id)
);
-- 知识库绑定表
CREATE TABLE agent_knowledge_bases (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
agent_id BIGINT NOT NULL,
knowledge_base_id BIGINT NOT NULL,
FOREIGN KEY (agent_id) REFERENCES agents(id),
FOREIGN KEY (knowledge_base_id) REFERENCES knowledge_bases(id)
);
-- 长期记忆表
CREATE TABLE agent_memories (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
agent_id BIGINT NOT NULL,
user_id BIGINT,
content TEXT NOT NULL,
embedding VECTOR(1536),
memory_type VARCHAR(20),
importance INT DEFAULT 5,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (agent_id) REFERENCES agents(id)
);
-- 会话记忆 (Redis)
-- Key: session:{agent_id}:{user_id}:{session_id}
-- Value: JSON {"messages": [...], "summary": "..."}
-- 任务记录表
CREATE TABLE agent_tasks (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
agent_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
user_input TEXT NOT NULL,
agent_response TEXT,
status VARCHAR(20),
tokens_used INT DEFAULT 0,
duration_ms INT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
completed_at DATETIME,
FOREIGN KEY (agent_id) REFERENCES agents(id)
);
-- 多智能体协作配置表
CREATE TABLE agent_teams (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
supervisor_agent_id BIGINT NOT NULL,
member_agent_id BIGINT NOT NULL,
dispatch_strategy VARCHAR(20) DEFAULT 'parallel',
FOREIGN KEY (supervisor_agent_id) REFERENCES agents(id),
FOREIGN KEY (member_agent_id) REFERENCES agents(id)
);
```
## 2. 后端实现 (Python Agent Engine)
### 2.1 项目结构
```
agent/
├── app/
│ ├── agent/
│ │ ├── __init__.py
│ │ ├── core/
│ │ │ ├── __init__.py
│ │ │ ├── agent.py # AgentCore 单智能体核心
│ │ │ ├── supervisor.py # Supervisor 多智能体调度
│ │ │ └── config.py # Agent 配置模型
│ │ ├── skills/
│ │ │ ├── __init__.py
│ │ │ ├── router.py # 技能路由器
│ │ │ ├── executor.py # 技能执行器
│ │ │ └── registry.py # 技能注册表
│ │ ├── memory/
│ │ │ ├── __init__.py
│ │ │ ├── manager.py # 记忆管理器
│ │ │ ├── working.py # Working Memory
│ │ │ ├── session.py # Session Memory (Redis)
│ │ │ └── persistent.py # Persistent Memory (向量库)
│ │ ├── llm/
│ │ │ ├── __init__.py
│ │ │ ├── base.py # LLM 抽象基类
│ │ │ ├── openai.py # OpenAI 实现
│ │ │ └── anthropic.py # Anthropic 实现
│ │ └── tools/
│ │ ├── __init__.py
│ │ └── registry.py # 工具注册表 (复用现有)
│ ├── api/
│ │ ├── __init__.py
│ │ └── routes/
│ │ ├── __init__.py
│ │ └── agent.py # Agent API 路由
│ └── main.py
├── requirements.txt
└── config.yaml
```
### 2.2 核心代码设计
#### AgentCore (单智能体核心)
```python
# agent/app/agent/core/agent.py
from typing import Optional, List
from pydantic import BaseModel
from app.agent.memory.manager import MemoryManager
from app.agent.skills.router import SkillRouter
from app.agent.skills.executor import SkillExecutor
from app.agent.llm.base import LLMBase
class AgentConfig(BaseModel):
id: int
name: str
role_description: str
model_provider: str
model_name: str
skills: List[int] # 技能 ID 列表
knowledge_base_ids: List[int] = []
class AgentResponse(BaseModel):
content: str
tool_calls: List[dict] = []
tokens_used: int = 0
duration_ms: int = 0
class AgentCore:
def __init__(self, config: AgentConfig, llm: LLMBase):
self.config = config
self.llm = llm
self.memory = MemoryManager(config.id)
self.skill_router = SkillRouter(config.skills)
self.skill_executor = SkillExecutor()
async def run(self, user_input: str, user_id: int) -> AgentResponse:
start_time = time.time()
# 1. 加载记忆
context = await self.memory.load_context(user_input, user_id)
# 2. 构建 Prompt
prompt = self._build_prompt(user_input, context)
# 3. LLM 决策
decision = await self.llm.decide(prompt)
# 4. 执行技能(如需)
if decision.needs_skill:
skill_results = await self._execute_skills(decision.skills)
# 5. 基于结果生成回复
final_response = await self.llm.generate(prompt, skill_results)
else:
final_response = decision.response
# 6. 保存记忆
await self.memory.save(user_input, final_response)
duration_ms = int((time.time() - start_time) * 1000)
return AgentResponse(
content=final_response,
tool_calls=decision.tool_calls,
duration_ms=duration_ms
)
def _build_prompt(self, user_input: str, context: dict) -> str:
system_prompt = f"""你是 {self.config.name}
{self.config.role_description}
相关记忆:
{context.get('summary', '')}
"""
return f"{system_prompt}\n\n用户: {user_input}"
async def _execute_skills(self, skill_decisions: List[dict]) -> List[dict]:
results = []
for decision in skill_decisions:
result = await self.skill_executor.execute(
skill_id=decision['skill_id'],
params=decision['params']
)
results.append(result)
return results
```
#### Supervisor (多智能体调度)
```python
# agent/app/agent/core/supervisor.py
from typing import List
from app.agent.core.agent import AgentCore, AgentConfig
class Supervisor:
def __init__(self, supervisor_agent: AgentCore, members: List[AgentCore], strategy: str = "parallel"):
self.supervisor = supervisor_agent
self.members = members
self.strategy = strategy
async def run(self, task: str, user_id: int) -> dict:
# 1. 任务分解 (调用 Supervisor 的 LLM)
subtasks = await self._decompose_task(task)
# 2. 分配任务
if self.strategy == "parallel":
results = await self._dispatch_parallel(subtasks, user_id)
else:
results = await self._dispatch_sequential(subtasks, user_id)
# 3. 汇总结果
final_result = await self._aggregate(results)
return {
"main_response": final_result,
"subtask_results": results
}
async def _decompose_task(self, task: str) -> List[dict]:
# 调用 LLM 分解任务
prompt = f"""分解以下任务为子任务,返回 JSON 数组:
任务: {task}
格式: [{"task": "子任务描述", "agent_type": "适合的智能体类型"}]"""
# ... 实现
return subtasks
async def _dispatch_parallel(self, subtasks: List[dict], user_id: int) -> List[dict]:
tasks = []
for subtask, member in zip(subtasks, self.members):
tasks.append(member.run(subtask['task'], user_id))
return await asyncio.gather(*tasks)
async def _dispatch_sequential(self, subtasks: List[dict], user_id: int) -> List[dict]:
results = []
context = ""
for subtask in subtasks:
# 传递前一个结果作为上下文
enhanced_task = f"{context}\n\n当前任务: {subtask['task']}"
result = await self.members[self.members.index(subtask['agent'])].run(enhanced_task, user_id)
results.append(result)
context += f"\n{result.content}"
return results
async def _aggregate(self, results: List[dict]) -> str:
# 汇总所有子任务结果
prompt = "汇总以下结果:\n" + "\n---\n".join([r['content'] for r in results])
return await self.supervisor.llm.generate(prompt, [])
```
#### Memory Manager (记忆管理)
```python
# agent/app/agent/memory/manager.py
from app.agent.memory.working import WorkingMemory
from app.agent.memory.session import SessionMemory
from app.agent.memory.persistent import PersistentMemory
class MemoryManager:
def __init__(self, agent_id: int):
self.agent_id = agent_id
self.working = WorkingMemory()
self.session = SessionMemory(agent_id)
self.persistent = PersistentMemory(agent_id)
async def load_context(self, query: str, user_id: int, session_id: str) -> dict:
# 1. Working Memory (内存,最快)
working_context = self.working.get()
# 2. Session Memory (Redis)
session_context = await self.session.get_summary(user_id, session_id)
# 3. Persistent Memory (向量库) - 按需检索
persistent_context = await self.persistent.search(query, user_id, top_k=3)
return {
'working': working_context,
'session': session_context,
'persistent': persistent_context,
'summary': self._build_summary(session_context, persistent_context)
}
async def save(self, user_input: str, response: str, user_id: int, session_id: str):
# 1. 写入 Working
self.working.add(user_input, response)
# 2. 写入 Session (定期摘要)
await self.session.add(user_input, response, user_id, session_id)
# 3. 提取关键信息写入 Persistent (定期)
if self._should_persist():
await self._extract_and_persist(user_input, response, user_id)
def _should_persist(self) -> bool:
# 每 N 条对话或达到阈值时持久化
return self.working.size() >= 5
async def _extract_and_persist(self, user_input: str, response: str, user_id: int):
# 提取关键信息(可以用 LLM 或规则)
key_points = self._extract_key_points(user_input, response)
for point in key_points:
await self.persistent.add(point, user_id, memory_type="experience")
```
```python
# agent/app/agent/memory/working.py
class WorkingMemory:
"""当前任务上下文,内存级存储"""
def __init__(self):
self.current_task = None
self.recent_messages = []
self.max_size = 10
def get(self) -> dict:
return {
'current_task': self.current_task,
'recent_messages': self.recent_messages[-self.max_size:]
}
def add(self, user_input: str, response: str):
self.recent_messages.append({
'role': 'user',
'content': user_input
})
self.recent_messages.append({
'role': 'assistant',
'content': response
})
# 保持固定大小
if len(self.recent_messages) > self.max_size * 2:
self.recent_messages = self.recent_messages[-self.max_size:]
def size(self) -> int:
return len(self.recent_messages) // 2
```
```python
# agent/app/agent/memory/session.py
import redis.asyncio as redis
import json
class SessionMemory:
"""会话级记忆Redis 存储"""
def __init__(self, agent_id: int, redis_client: redis.Redis):
self.agent_id = agent_id
self.redis = redis_client
self.ttl = 3600 * 24 # 24 小时
def _key(self, user_id: int, session_id: str) -> str:
return f"agent:memory:session:{self.agent_id}:{user_id}:{session_id}"
async def add(self, user_input: str, response: str, user_id: int, session_id: str):
key = self._key(user_id, session_id)
# 获取现有数据
data = await self.redis.get(key)
messages = json.loads(data) if data else {"messages": [], "summary": ""}
# 添加新消息
messages["messages"].append({"role": "user", "content": user_input})
messages["messages"].append({"role": "assistant", "content": response})
# 定期生成摘要
if len(messages["messages"]) >= 10:
messages["summary"] = await self._generate_summary(messages["messages"])
await self.redis.setex(key, self.ttl, json.dumps(messages))
async def get_summary(self, user_id: int, session_id: str) -> str:
key = self._key(user_id, session_id)
data = await self.redis.get(key)
if data:
messages = json.loads(data)
return messages.get("summary", "")
return ""
async def _generate_summary(self, messages: List[dict]) -> str:
# 使用 LLM 生成摘要
# ...
return summary
```
```python
# agent/app/agent/memory/persistent.py
from typing import List
class PersistentMemory:
"""长期记忆,向量存储"""
def __init__(self, agent_id: int):
self.agent_id = agent_id
self.vector_store = None # 初始化向量库客户端
async def add(self, content: str, user_id: int, memory_type: str = "experience"):
# 生成向量
embedding = await self._get_embedding(content)
# 存储到数据库
await db.agent_memories.create(
agent_id=self.agent_id,
user_id=user_id,
content=content,
embedding=embedding,
memory_type=memory_type
)
async def search(self, query: str, user_id: int, top_k: int = 3) -> List[str]:
# 生成查询向量
query_embedding = await self._get_embedding(query)
# 向量相似度搜索
results = await db.agent_memories.search(
agent_id=self.agent_id,
user_id=user_id,
embedding=query_embedding,
top_k=top_k
)
return [r.content for r in results]
async def _get_embedding(self, text: str) -> List[float]:
# 调用 embedding 模型
# ...
pass
```
#### Skill Router (技能路由器)
```python
# agent/app/agent/skills/router.py
from typing import List, Dict
class SkillRouter:
"""根据 LLM 决策选择要调用的技能"""
def __init__(self, available_skills: List[int]):
self.available_skills = available_skills
async def route(self, llm_decision: dict) -> List[dict]:
"""解析 LLM 的技能调用决策"""
if not llm_decision.get('tool_calls'):
return []
routes = []
for tool_call in llm_decision['tool_calls']:
skill_id = tool_call['skill_id']
# 检查技能是否可用
if skill_id not in self.available_skills:
continue
routes.append({
'skill_id': skill_id,
'params': tool_call.get('parameters', {}),
'reason': tool_call.get('reason', '')
})
return routes
```
#### Skill Executor (技能执行器)
```python
# agent/app/agent/skills/executor.py
import asyncio
class SkillExecutor:
"""技能执行器,支持并发/串行执行"""
def __init__(self):
self.skill_registry = None # 技能注册表
async def execute(self, skill_id: int, params: dict) -> dict:
"""执行单个技能"""
skill = self.skill_registry.get(skill_id)
if not skill:
return {"error": f"Skill {skill_id} not found"}
try:
result = await skill.execute(**params)
return {"success": True, "result": result}
except Exception as e:
return {"success": False, "error": str(e)}
async def execute_multiple(self, skills: List[dict], strategy: str = "parallel") -> List[dict]:
"""批量执行技能"""
if strategy == "parallel":
tasks = [self.execute(s['skill_id'], s['params']) for s in skills]
return await asyncio.gather(*tasks, return_exceptions=True)
else:
results = []
for s in skills:
result = await self.execute(s['skill_id'], s['params'])
results.append(result)
return results
```
## 3. API 接口设计
### 3.1 新增接口
| 方法 | 路径 | 描述 |
|------|------|------|
| POST | /api/v1/agents/:id/chat | 单智能体对话 |
| POST | /api/v1/agents/:id/chat/stream | 单智能体流式对话 |
| POST | /api/v1/teams/:id/chat | 多智能体群聊 |
| GET | /api/v1/agents/:id/memories | 获取记忆 |
| DELETE | /api/v1/agents/:id/memories/:memory_id | 删除记忆 |
| GET | /api/v1/agents/:id/history | 获取对话历史 |
### 3.2 接口请求/响应示例
```json
// POST /api/v1/agents/1/chat
// Request
{
"user_id": 123,
"message": "帮我分析销售数据",
"session_id": "optional-session-id"
}
// Response
{
"agent_id": 1,
"response": "根据分析,今天销售额为...",
"tool_calls": [
{"skill": "query_database", "params": {"sql": "SELECT ..."}}
],
"tokens_used": 1500,
"duration_ms": 2000
}
```
## 4. 实现步骤
### Phase 1: 数据库设计与迁移
- [ ] 创建数据库迁移脚本
- [ ] 新增 agents, agent_skills, agent_memories, agent_teams 等表
### Phase 2: 后端 Agent Engine 核心
- [ ] 实现 AgentCore 单智能体核心类
- [ ] 实现 LLM 适配器 (OpenAI/Anthropic)
- [ ] 实现 Prompt 构建逻辑
### Phase 3: 记忆系统实现
- [ ] 实现 WorkingMemory (内存)
- [ ] 实现 SessionMemory (Redis)
- [ ] 实现 PersistentMemory (向量库)
- [ ] 实现 MemoryManager 统一接口
### Phase 4: 技能路由与执行器
- [ ] 实现 SkillRouter
- [ ] 实现 SkillExecutor
- [ ] 对接现有技能注册表
### Phase 5: 多智能体 Supervisor
- [ ] 实现 Supervisor 调度器
- [ ] 实现任务分解逻辑
- [ ] 实现结果聚合
### Phase 6: API 接口对接
- [ ] 新增 Agent API 路由
- [ ] 实现 /chat, /chat/stream 等接口
- [ ] 对接 Go API Gateway
### Phase 7: 前端页面集成
- [ ] 智能体详情页增加对话功能
- [ ] 记忆管理页面
- [ ] 多智能体协作配置页面
### Phase 8: 测试与优化
- [ ] 单元测试
- [ ] 集成测试
- [ ] 性能优化
## 5. 里程碑
| 里程碑 | 预计时间 | 交付物 |
|--------|----------|--------|
| M1: 基础骨架 | 1 周 | 数据库 + AgentCore 基础 |
| M2: 记忆系统 | 1 周 | 三层记忆实现 |
| M3: 技能调用 | 1 周 | Router + Executor |
| M4: 多智能体 | 1 周 | Supervisor 实现 |
| M5: API 对接 | 1 周 | 完整 API |
| M6: 前端集成 | 1 周 | 页面功能 |
## 6. 风险与对策
| 风险 | 影响 | 对策 |
|------|------|------|
| LLM API 不稳定 | 功能不可用 | 重试机制 + 降级 |
| 向量库性能 | 检索慢 | 缓存 + 限流 |
| Token 成本超支 | 费用上涨 | 记忆压缩 + 按需加载 |
| 多智能体通信 | 延迟增加 | 超时控制 + 并行优化 |

View File

@@ -1,33 +0,0 @@
# Notes: 智能体系统设计研究
## 设计决策汇总
### 1. 架构选择
- **方案**: 自研 Agent Core方案 B
- **理由**: 完全可控,易于扩展,支持多智能体调度
### 2. 工作模式
- **独立模式**: 单个智能体独立处理任务
- **协作模式**: Supervisor 调度多个子智能体
### 3. 记忆系统设计
- Working Memory: 当前任务上下文(内存变量)
- Session Memory: 会话级记忆Redis + 摘要)
- Persistent Memory: 长期记忆(向量存储)
### 4. 性能优化策略
- 分层检索: Working → Session → Persistent
- 记忆压缩: 摘要 + 结构化标签
- 按需加载: LLM 决策需要什么记忆再检索
- 缓存策略: 热门记忆放内存缓存
### 5. 错误处理
- 重试机制: LLM 调用失败重试 3 次
- 降级策略: 记忆加载失败降级到无记忆模式
- 超时控制: 多智能体调度设置超时
## 技术栈确认
- 后端: Python FastAPI (agent/)
- 记忆存储: Redis + PostgreSQL/Milvus
- LLM: OpenAI / Anthropic SDK
- 技能: 内置 + 自定义 + MCP + API

View File

@@ -1,99 +0,0 @@
# Task Plan: 智能体系统设计与实现
## Goal
设计和实现一个支持单智能体独立工作 + 多智能体协作的混合型智能体系统,具备长短时记忆、多种技能调用能力。
## Phases
- [ ] Phase 1: 数据库设计与迁移
- [ ] Phase 2: 后端 Agent Engine 核心实现
- [ ] Phase 3: 记忆系统实现
- [ ] Phase 4: 技能路由与执行器实现
- [ ] Phase 5: 多智能体 Supervisor 实现
- [ ] Phase 6: API 接口对接
- [ ] Phase 7: 前端页面集成
- [ ] Phase 8: 测试与优化
## Key Questions
1. 如何设计长短时记忆的存储和检索?
2. 如何实现灵活的技能路由?
3. 如何支持多智能体协作?
## Decisions Made
- 单智能体工作流: 用户输入 → 智能体思考 → 调用技能 → 返回结果
- 多智能体模式: Supervisor 主智能体调度子智能体
- 记忆分层: Working → Session → Persistent 三层结构
- 技能全支持: 内置 + 自定义代码 + MCP + API
## Errors Encountered
- (无)
## Status
**Currently in Phase 8** - 测试与优化
## 完成项
- [x] Phase 1: 数据库设计与迁移
- 扩展 Agent 模型 (增加角色描述、模型配置、协作模式)
- 新增 AgentSkill, AgentKnowledgeBase, AgentMemory, AgentTeam, AgentTask 模型
- 扩展 AgentRepository 添加新方法
- 创建 SQL 迁移脚本 (server/migrations/agent_system.sql)
- [x] Phase 2: 后端 Agent Engine 核心实现
- AgentCore 单智能体核心类
- Supervisor 多智能体调度器
- LLM 适配器 (OpenAI/Anthropic)
- FastAPI 服务入口 (app/main.py)
- requirements.txt
- [x] Phase 3: 记忆系统实现
- Working Memory (内存)
- Session Memory (Redis/内存模拟)
- Persistent Memory (向量库/内存模拟)
- MemoryManager 统一接口
- [x] Phase 4: 技能路由与执行器
- SkillRouter 技能路由器
- SkillExecutor 技能执行器
- [x] Phase 5: Go API 对接
- AgentService (调用 Python)
- AgentHandler (HTTP 接口)
- MemoryService (记忆服务)
- MemoryHandler (记忆接口)
- 路由注册 (/api/agent/chat, /api/agent/team/chat, /api/agent/:id/memories)
- [x] Phase 7: 前端页面集成
- agentApi.ts API 服务
- Agents.vue 添加聊天按钮和弹窗
## 技术决策
- 通信协议: HTTP REST (暂定)
- 后续可根据需要改造为 gRPC
## 完成项
- [x] Phase 1: 数据库设计与迁移
- 扩展 Agent 模型 (增加角色描述、模型配置、协作模式)
- 新增 AgentSkill, AgentKnowledgeBase, AgentMemory, AgentTeam, AgentTask 模型
- 扩展 AgentRepository 添加新方法
- 创建 SQL 迁移脚本 (server/migrations/agent_system.sql)
- [x] Phase 2: 后端 Agent Engine 核心实现
- AgentCore 单智能体核心类
- Supervisor 多智能体调度器
- LLM 适配器 (OpenAI/Anthropic)
- FastAPI 服务入口 (app/main.py)
- requirements.txt
- [x] Phase 3: 记忆系统实现
- Working Memory (内存)
- Session Memory (Redis/内存模拟)
- Persistent Memory (向量库/内存模拟)
- MemoryManager 统一接口
- [x] Phase 4: 技能路由与执行器
- SkillRouter 技能路由器
- SkillExecutor 技能执行器
- [x] Phase 5: Go API 对接
- AgentService (调用 Python)
- AgentHandler (HTTP 接口)
- 路由注册 (/api/agent/chat, /api/agent/team/chat)