- 新增 Go 语言后端服务(server/),包含用户认证、Agent管理、数据库连接等API - 新增 Python Agent 服务(agent/),实现Agent核心逻辑和工具集 - 前端从原生HTML迁移到Vue.js框架(web/src/) - 添加 Docker Compose 支持(docker-compose.yml) - 添加项目架构文档(docs/ARCHITECTURE.md) - 添加环境变量示例(.env.example)和本地启动脚本(start-local.ps1) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
90 lines
2.0 KiB
Go
90 lines
2.0 KiB
Go
package handler
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"x-agents/server/internal/model"
|
||
"x-agents/server/internal/service"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
type ChatHandler struct {
|
||
chatService *service.ChatService
|
||
}
|
||
|
||
func NewChatHandler(chatService *service.ChatService) *ChatHandler {
|
||
return &ChatHandler{chatService: chatService}
|
||
}
|
||
|
||
// Chat 处理聊天请求
|
||
func (h *ChatHandler) Chat(c *gin.Context) {
|
||
var req model.AgentRequest
|
||
if err := c.ShouldBindJSON(&req); err != nil {
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
|
||
// 从上下文获取用户ID(由中间件设置)
|
||
userID, exists := c.Get("user_id")
|
||
if !exists {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||
return
|
||
}
|
||
|
||
resp, err := h.chatService.Chat(c.Request.Context(), userID.(string), req)
|
||
if err != nil {
|
||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
|
||
c.JSON(http.StatusOK, resp)
|
||
}
|
||
|
||
// ListAgents 获取 Agent 列表
|
||
func (h *ChatHandler) ListAgents(c *gin.Context) {
|
||
userID, exists := c.Get("user_id")
|
||
if !exists {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||
return
|
||
}
|
||
|
||
agents, err := h.chatService.ListAgents(userID.(string))
|
||
if err != nil {
|
||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
|
||
if agents == nil {
|
||
agents = []model.Agent{}
|
||
}
|
||
|
||
c.JSON(http.StatusOK, gin.H{"agents": agents})
|
||
}
|
||
|
||
// CreateAgent 创建 Agent
|
||
func (h *ChatHandler) CreateAgent(c *gin.Context) {
|
||
userID, exists := c.Get("user_id")
|
||
if !exists {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||
return
|
||
}
|
||
|
||
var req struct {
|
||
Name string `json:"name" binding:"required"`
|
||
Description string `json:"description"`
|
||
}
|
||
if err := c.ShouldBindJSON(&req); err != nil {
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
|
||
agent, err := h.chatService.CreateAgent(userID.(string), req.Name, req.Description)
|
||
if err != nil {
|
||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
|
||
c.JSON(http.StatusCreated, agent)
|
||
}
|