feat: 新增Chat会话和群聊API

- 新增chat_session相关模型、仓库和服务
- 新增chat_group相关模型、仓库和服务
- 新增session_handler和chat_group_handler
- 实现会话管理和群聊功能

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-13 14:31:42 +08:00
parent 4045dad903
commit 77f5b4872e
7 changed files with 838 additions and 0 deletions

View File

@@ -0,0 +1,149 @@
package handler
import (
"net/http"
"strconv"
"x-agents/server/internal/model"
"x-agents/server/internal/service"
"github.com/gin-gonic/gin"
)
// ChatGroupHandler 群聊处理器
type ChatGroupHandler struct {
groupService *service.ChatGroupService
}
// NewChatGroupHandler 创建群聊处理器
func NewChatGroupHandler(groupService *service.ChatGroupService) *ChatGroupHandler {
return &ChatGroupHandler{
groupService: groupService,
}
}
// CreateGroup 创建群聊
func (h *ChatGroupHandler) CreateGroup(c *gin.Context) {
var req model.CreateGroupRequest
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 {
req.UserID = userID.(string)
}
group, err := h.groupService.CreateGroup(req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, group)
}
// ListGroups 获取群聊列表
func (h *ChatGroupHandler) ListGroups(c *gin.Context) {
userID := c.Query("user_id")
if userID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "user_id is required"})
return
}
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
groups, total, err := h.groupService.ListGroups(userID, limit, offset)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"list": groups, "total": total})
}
// GetGroup 获取群聊详情
func (h *ChatGroupHandler) GetGroup(c *gin.Context) {
id := c.Param("id")
group, err := h.groupService.GetGroup(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Group not found"})
return
}
c.JSON(http.StatusOK, group)
}
// UpdateGroup 更新群聊
func (h *ChatGroupHandler) UpdateGroup(c *gin.Context) {
id := c.Param("id")
var req model.UpdateGroupRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
group, err := h.groupService.UpdateGroup(id, req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, group)
}
// DeleteGroup 删除群聊
func (h *ChatGroupHandler) DeleteGroup(c *gin.Context) {
id := c.Param("id")
err := h.groupService.DeleteGroup(id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// GroupChat 群聊对话
func (h *ChatGroupHandler) GroupChat(c *gin.Context) {
id := c.Param("id")
// 获取群聊信息
group, err := h.groupService.GetGroup(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Group not found"})
return
}
var req model.GroupChatRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 获取用户ID
userID := ""
if uid, exists := c.Get("user_id"); exists {
userID = uid.(string)
}
// 如果没有提供 Agent IDs使用群聊中配置的
agentIDs := req.AgentIDs
if agentIDs == "" {
agentIDs = group.AgentIDs
}
response, err := h.groupService.GroupChat(userID, req.Message, agentIDs, req.SessionID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, response)
}

View File

@@ -0,0 +1,252 @@
package handler
import (
"net/http"
"strconv"
"x-agents/server/internal/model"
"x-agents/server/internal/repository"
"x-agents/server/internal/service"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// ChatHandler 处理聊天请求
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)
}
// SessionHandler 处理会话管理
type SessionHandler struct {
chatRepo *repository.ChatRepository
}
func NewSessionHandler(chatRepo *repository.ChatRepository) *SessionHandler {
return &SessionHandler{chatRepo: chatRepo}
}
// CreateSession 创建会话
func (h *SessionHandler) CreateSession(c *gin.Context) {
var req model.CreateSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
session := &model.ChatSession{
ID: uuid.New().String(),
UserID: req.UserID,
AgentID: req.AgentID,
Title: req.Title,
ModelID: req.ModelID,
Status: "active",
}
if err := h.chatRepo.CreateSession(session); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, session)
}
// ListSessions 获取会话列表
func (h *SessionHandler) ListSessions(c *gin.Context) {
userID := c.Query("user_id")
if userID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "user_id is required"})
return
}
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
sessions, total, err := h.chatRepo.GetSessionsByUserID(userID, limit, offset)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"list": sessions, "total": total})
}
// GetSession 获取会话详情
func (h *SessionHandler) GetSession(c *gin.Context) {
id := c.Param("id")
session, err := h.chatRepo.GetSessionByID(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Session not found"})
return
}
c.JSON(http.StatusOK, session)
}
// UpdateSession 更新会话
func (h *SessionHandler) UpdateSession(c *gin.Context) {
id := c.Param("id")
session, err := h.chatRepo.GetSessionByID(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Session not found"})
return
}
var req model.UpdateSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if req.Title != "" {
session.Title = req.Title
}
if req.Status != "" {
session.Status = req.Status
}
if err := h.chatRepo.UpdateSession(session); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, session)
}
// DeleteSession 删除会话
func (h *SessionHandler) DeleteSession(c *gin.Context) {
id := c.Param("id")
if err := h.chatRepo.DeleteSession(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// GetMessages 获取会话消息
func (h *SessionHandler) GetMessages(c *gin.Context) {
sessionID := c.Param("id")
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "100"))
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
messages, total, err := h.chatRepo.GetMessagesBySessionID(sessionID, limit, offset)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"list": messages, "total": total})
}
// CreateMessage 创建消息
func (h *SessionHandler) CreateMessage(c *gin.Context) {
var req model.CreateMessageRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 检查会话是否存在
_, err := h.chatRepo.GetSessionByID(req.SessionID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Session not found"})
return
}
message := &model.ChatMessage{
ID: uuid.New().String(),
SessionID: req.SessionID,
Role: req.Role,
Content: req.Content,
TokensUsed: req.TokensUsed,
DurationMs: req.DurationMs,
Metadata: req.Metadata,
}
if err := h.chatRepo.CreateMessage(message); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, message)
}