feat(handler,cmd): 实现阶段 5 HTTP 服务 — 处理器、入口程序、配置文件

This commit is contained in:
hhs
2026-06-10 15:18:06 +08:00
parent f532b21a7a
commit cdbaefecf8
7 changed files with 410 additions and 17 deletions

View File

@@ -1,7 +1,2 @@
# LLM API 配置 OPENAI_BASE_URL=https://api.openai.com
LLM_API_KEY=your-api-key-here OPENAI_API_KEY=sk-your-key-here
LLM_BASE_URL=https://api.deepseek.com
LLM_MODEL=deepseek-chat
# 服务器配置
SERVER_PORT=8091

View File

@@ -1,5 +1,111 @@
package main package main
import (
"context"
"flag"
"log"
"os"
"ai-agent-scaffold-go/internal/config"
"ai-agent-scaffold-go/internal/handler"
"ai-agent-scaffold-go/internal/model"
"ai-agent-scaffold-go/internal/service"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"go.uber.org/zap"
)
func main() { func main() {
// TODO: 实现启动逻辑 envPath := flag.String("env", ".env", "path to dotenv file (empty to skip)")
configPath := flag.String("config", "configs/application.yaml", "path to application.yaml")
flag.Parse()
// 1. 加载 .env 文件
loadDotenv(*envPath)
// 2. 加载应用配置
appCfg, err := config.LoadApplication(*configPath)
if err != nil {
log.Fatalf("load config: %v", err)
}
// 3. 初始化日志
logger, _ := zap.NewProduction()
if appCfg.App.Env == "local" || appCfg.App.Env == "dev" {
logger, _ = zap.NewDevelopment()
}
defer logger.Sync()
// 4. 组装 Agent
registry := model.NewInMemoryAgentRegistry()
sessions := model.NewInMemorySessionStore()
timeout, _ := appCfg.LLM.RequestTimeoutDuration()
agents, err := service.LoadAndAssemble(context.Background(), appCfg.Agent.ConfigPaths, timeout)
if err != nil {
logger.Fatal("assemble agents failed", zap.Error(err))
}
for _, agent := range agents {
if err := registry.Register(agent); err != nil {
logger.Fatal("register agent failed", zap.Error(err))
}
}
chatService := service.NewChatService(registry, sessions)
// 5. 配置 HTTP 路由
router := gin.Default()
router.Use(corsMiddleware())
router.GET("/healthz", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok"})
})
handler.RegisterRoutes(router, chatService)
// 6. 启动服务
addr := appCfg.Server.Addr
logger.Info("server starting", zap.String("addr", addr), zap.Int("agents", len(agents)))
if err := router.Run(addr); err != nil {
logger.Fatal("server stopped", zap.Error(err))
}
}
// corsMiddleware 跨域中间件
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.GetHeader("Origin")
if origin != "" {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Vary", "Origin")
} else {
c.Header("Access-Control-Allow-Origin", "*")
}
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
c.Header("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
// loadDotenv 加载 dotenv 文件,已有环境变量不会被覆盖
func loadDotenv(path string) {
if path == "" {
return
}
if _, err := os.Stat(path); os.IsNotExist(err) {
return
}
pairs, err := godotenv.Read(path)
if err != nil {
log.Fatalf("read dotenv: %v", err)
}
for key, value := range pairs {
if _, exists := os.LookupEnv(key); !exists {
os.Setenv(key, value)
}
}
} }

View File

@@ -0,0 +1,23 @@
ai:
agent:
config:
tables:
myAgent:
app-name: myAgent
agent:
agent-id: "10001"
agent-name: "my-assistant"
agent-desc: "通用 AI 助手"
module:
ai-api:
base-url: ${OPENAI_BASE_URL}
api-key: ${OPENAI_API_KEY}
chat-model:
model: "gpt-4"
agents:
- name: "assistant"
description: "通用助手"
instruction: |
你是一个有帮助的 AI 助手。请用中文回答用户的问题。
runner:
agent-name: "assistant"

View File

@@ -1,14 +1,13 @@
app: app:
name: goloom name: goloom
env: development env: local
port: ${SERVER_PORT:-8091}
server:
addr: ":8091"
llm: llm:
base_url: ${LLM_BASE_URL} request-timeout: 5m
api_key: ${LLM_API_KEY}
model: ${LLM_MODEL:-deepseek-chat}
timeout: 30s
max_retries: 3
agent: agent:
config_dir: configs/agent config-paths:
- configs/agent/only-one-agent.yaml

37
go.mod
View File

@@ -2,4 +2,39 @@ module ai-agent-scaffold-go
go 1.26.2 go 1.26.2
require gopkg.in/yaml.v3 v3.0.1 // indirect require (
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/gin-gonic/gin v1.12.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
go.uber.org/zap v1.28.0 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.48.0 // indirect
golang.org/x/net v0.51.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.34.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

82
go.sum
View File

@@ -1,3 +1,85 @@
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -1 +1,154 @@
package handler package handler
import (
"errors"
"net/http"
"strings"
"ai-agent-scaffold-go/internal/service"
"ai-agent-scaffold-go/pkg/types"
"github.com/gin-gonic/gin"
)
// Envelope 统一响应格式
type Envelope struct {
Code string `json:"code"`
Info string `json:"info"`
Data interface{} `json:"data,omitempty"`
}
// AiAgentConfigResponse Agent 配置查询响应
type AiAgentConfigResponse struct {
AgentID string `json:"agentId"`
AgentName string `json:"agentName"`
AgentDesc string `json:"agentDesc"`
}
// CreateSessionRequest 创建会话请求
type CreateSessionRequest struct {
AgentID string `json:"agentId"`
UserID string `json:"userId"`
}
// CreateSessionResponse 创建会话响应
type CreateSessionResponse struct {
SessionID string `json:"sessionId"`
}
// ChatRequest 聊天请求
type ChatRequest struct {
AgentID string `json:"agentId"`
UserID string `json:"userId"`
SessionID string `json:"sessionId"`
Message string `json:"message"`
}
// ChatResponse 聊天响应
type ChatResponse struct {
Content string `json:"content"`
}
// RegisterRoutes 注册 HTTP 路由
func RegisterRoutes(router gin.IRouter, chatService *service.ChatService) {
group := router.Group("/api/v1")
group.GET("/query_ai_agent_config_list", queryAgentConfigList(chatService))
group.POST("/create_session", createSession(chatService))
group.GET("/create_session", createSessionQuery(chatService))
group.POST("/chat", chatMessage(chatService))
group.POST("/chat_stream", chatStream(chatService))
}
func queryAgentConfigList(s *service.ChatService) gin.HandlerFunc {
return func(c *gin.Context) {
agents := s.QueryAgentConfigList()
responses := make([]AiAgentConfigResponse, 0, len(agents))
for _, agent := range agents {
responses = append(responses, AiAgentConfigResponse{
AgentID: agent.AgentID,
AgentName: agent.AgentName,
AgentDesc: agent.AgentDesc,
})
}
c.JSON(http.StatusOK, success(responses))
}
}
func createSession(s *service.ChatService) gin.HandlerFunc {
return func(c *gin.Context) {
var req CreateSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeError(c, types.NewAppError(types.CodeIllegalParameter, err.Error()))
return
}
sessionID, err := s.CreateSession(req.AgentID, req.UserID)
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, success(CreateSessionResponse{SessionID: sessionID}))
}
}
func createSessionQuery(s *service.ChatService) gin.HandlerFunc {
return func(c *gin.Context) {
sessionID, err := s.CreateSession(c.Query("agentId"), c.Query("userId"))
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, success(CreateSessionResponse{SessionID: sessionID}))
}
}
func chatMessage(s *service.ChatService) gin.HandlerFunc {
return func(c *gin.Context) {
var req ChatRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeError(c, types.NewAppError(types.CodeIllegalParameter, err.Error()))
return
}
outputs, err := s.HandleMessage(req.AgentID, req.UserID, req.SessionID, req.Message)
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, success(ChatResponse{Content: strings.Join(outputs, "\n")}))
}
}
func chatStream(s *service.ChatService) gin.HandlerFunc {
return func(c *gin.Context) {
var req ChatRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeError(c, types.NewAppError(types.CodeIllegalParameter, err.Error()))
return
}
outputs, errs := s.HandleMessageStream(req.AgentID, req.UserID, req.SessionID, req.Message)
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
for output := range outputs {
c.SSEvent("message", output)
c.Writer.Flush()
}
if err, ok := <-errs; ok && err != nil {
c.SSEvent("error", err.Error())
c.Writer.Flush()
}
}
}
func success(data interface{}) Envelope {
return Envelope{Code: types.CodeSuccess, Info: types.InfoSuccess, Data: data}
}
func writeError(c *gin.Context, err error) {
var appErr *types.AppError
if errors.As(err, &appErr) {
c.JSON(http.StatusOK, Envelope{Code: appErr.Code, Info: appErr.Info})
return
}
c.JSON(http.StatusOK, Envelope{Code: types.CodeUnknownError, Info: err.Error()})
}