Enhance AI and Redis integration for smoke logging features
- Added AI configuration options to .env.example and config.go for OpenAI integration. - Implemented Redis caching for session management in main.go and auth middleware. - Updated smoke logging service to support real smoking time (`smoke_at`) and AI advice retrieval. - Enhanced API routes to include endpoints for AI advice and unlock functionality for non-members. - Improved database schema with new tables for AI advice and unlock records. - Expanded documentation to cover new AI features and Redis caching implementation.
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
smokeservice "wx_service/internal/smoke/service"
|
||||
)
|
||||
|
||||
type unlockAIAdviceRequest struct {
|
||||
Date string `json:"date"`
|
||||
AdWatchedAt string `json:"ad_watched_at"`
|
||||
}
|
||||
|
||||
func (h *SmokeHandler) GetAIAdvice(c *gin.Context) {
|
||||
user, ok := middleware.CurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
dateStr := c.Query("date")
|
||||
adviceDate := yesterdayDate()
|
||||
if dateStr != "" {
|
||||
parsed, err := time.ParseInLocation(dateLayout, dateStr, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "date 格式错误,应为 YYYY-MM-DD"))
|
||||
return
|
||||
}
|
||||
adviceDate = parsed
|
||||
}
|
||||
|
||||
record, err := h.smokeAIAdviceService.GetOrGenerate(c.Request.Context(), user, adviceDate, smokeservice.DefaultAdvicePromptVersion)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, smokeservice.ErrAIAdviceLocked):
|
||||
c.JSON(http.StatusForbidden, model.Error(http.StatusForbidden, "需要会员或观看广告解锁后才可生成建议"))
|
||||
return
|
||||
case errors.Is(err, smokeservice.ErrAIServiceDisabled):
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "AI 服务暂不可用,请联系管理员"))
|
||||
return
|
||||
case errors.Is(err, smokeservice.ErrNoSmokeLogs):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "该日期没有抽烟记录,无法生成建议"))
|
||||
return
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "生成建议失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"date": record.AdviceDate.Format(dateLayout),
|
||||
"advice": record.Advice,
|
||||
}))
|
||||
}
|
||||
|
||||
func (h *SmokeHandler) UnlockAIAdvice(c *gin.Context) {
|
||||
user, ok := middleware.CurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
var req unlockAIAdviceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
unlockDate := yesterdayDate()
|
||||
if req.Date != "" {
|
||||
parsed, err := time.ParseInLocation(dateLayout, req.Date, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "date 格式错误,应为 YYYY-MM-DD"))
|
||||
return
|
||||
}
|
||||
unlockDate = parsed
|
||||
}
|
||||
|
||||
if err := h.smokeAIAdviceService.Unlock(c.Request.Context(), user, unlockDate); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "解锁失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"unlocked": true,
|
||||
"date": unlockDate.Format(dateLayout),
|
||||
}))
|
||||
}
|
||||
|
||||
func yesterdayDate() time.Time {
|
||||
now := time.Now().In(time.Local)
|
||||
y := now.AddDate(0, 0, -1)
|
||||
return time.Date(y.Year(), y.Month(), y.Day(), 0, 0, 0, 0, time.Local)
|
||||
}
|
||||
@@ -14,19 +14,26 @@ import (
|
||||
)
|
||||
|
||||
type SmokeHandler struct {
|
||||
smokeLogService *smokeservice.SmokeLogService
|
||||
smokeLogService *smokeservice.SmokeLogService
|
||||
smokeAIAdviceService *smokeservice.SmokeAIAdviceService
|
||||
}
|
||||
|
||||
func NewSmokeHandler(smokeLogService *smokeservice.SmokeLogService) *SmokeHandler {
|
||||
return &SmokeHandler{smokeLogService: smokeLogService}
|
||||
func NewSmokeHandler(smokeLogService *smokeservice.SmokeLogService, smokeAIAdviceService *smokeservice.SmokeAIAdviceService) *SmokeHandler {
|
||||
return &SmokeHandler{
|
||||
smokeLogService: smokeLogService,
|
||||
smokeAIAdviceService: smokeAIAdviceService,
|
||||
}
|
||||
}
|
||||
|
||||
// dateLayout 用于解析前端传入的日期字符串(例如:2025-12-31)
|
||||
const dateLayout = "2006-01-02"
|
||||
const dateTimeLayout = "2006-01-02 15:04:05"
|
||||
|
||||
type createSmokeLogRequest struct {
|
||||
// 只记录“日期”即可;如果不传,后端会按当天处理
|
||||
SmokeTime string `json:"smoke_time"`
|
||||
// 真实抽烟时间(精确到时分秒,可补录)
|
||||
SmokeAt string `json:"smoke_at"`
|
||||
Remark string `json:"remark"`
|
||||
Level int64 `json:"level"`
|
||||
Num int `json:"num"`
|
||||
@@ -55,8 +62,19 @@ func (h *SmokeHandler) Create(c *gin.Context) {
|
||||
smokeTime = &parsed
|
||||
}
|
||||
|
||||
var smokeAt *time.Time
|
||||
if req.SmokeAt != "" {
|
||||
parsed, err := time.ParseInLocation(dateTimeLayout, req.SmokeAt, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "smoke_at 格式错误,应为 YYYY-MM-DD HH:MM:SS"))
|
||||
return
|
||||
}
|
||||
smokeAt = &parsed
|
||||
}
|
||||
|
||||
record, err := h.smokeLogService.Create(c.Request.Context(), int(user.ID), smokeservice.CreateSmokeLogRequest{
|
||||
SmokeTime: smokeTime,
|
||||
SmokeAt: smokeAt,
|
||||
Remark: req.Remark,
|
||||
Level: req.Level,
|
||||
Num: req.Num,
|
||||
@@ -145,6 +163,7 @@ func (h *SmokeHandler) List(c *gin.Context) {
|
||||
|
||||
type updateSmokeLogRequest struct {
|
||||
SmokeTime *string `json:"smoke_time"`
|
||||
SmokeAt *string `json:"smoke_at"`
|
||||
Remark *string `json:"remark"`
|
||||
Level *int64 `json:"level"`
|
||||
Num *int `json:"num"`
|
||||
@@ -184,9 +203,26 @@ func (h *SmokeHandler) Update(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
smokeAtProvided := req.SmokeAt != nil
|
||||
var smokeAt *time.Time
|
||||
if req.SmokeAt != nil {
|
||||
if *req.SmokeAt == "" {
|
||||
smokeAt = nil
|
||||
} else {
|
||||
parsed, err := time.ParseInLocation(dateTimeLayout, *req.SmokeAt, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "smoke_at 格式错误,应为 YYYY-MM-DD HH:MM:SS"))
|
||||
return
|
||||
}
|
||||
smokeAt = &parsed
|
||||
}
|
||||
}
|
||||
|
||||
record, err := h.smokeLogService.Update(c.Request.Context(), int(user.ID), id, smokeservice.UpdateSmokeLogRequest{
|
||||
SmokeTimeProvided: smokeTimeProvided,
|
||||
SmokeTime: smokeTime,
|
||||
SmokeAtProvided: smokeAtProvided,
|
||||
SmokeAt: smokeAt,
|
||||
Remark: req.Remark,
|
||||
Level: req.Level,
|
||||
Num: req.Num,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// SmokeAIAdvice 对应表 fa_smoke_ai_advice(每日 AI 戒烟建议缓存)。
|
||||
//
|
||||
// 注意:沿用旧系统字段(createtime/updatetime/deletetime 为秒级时间戳),不使用 gorm.Model。
|
||||
type SmokeAIAdvice struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UID int `gorm:"column:uid;index:idx_smoke_ai_advice_uid_date,priority:1;uniqueIndex:uniq_smoke_ai_advice,priority:1" json:"-"`
|
||||
|
||||
AdviceDate time.Time `gorm:"column:advice_date;type:date;index:idx_smoke_ai_advice_uid_date,priority:2;uniqueIndex:uniq_smoke_ai_advice,priority:2" json:"advice_date"`
|
||||
PromptVersion string `gorm:"column:prompt_version;size:30;default:v1;uniqueIndex:uniq_smoke_ai_advice,priority:3" json:"prompt_version"`
|
||||
|
||||
Provider string `gorm:"column:provider;size:30" json:"provider,omitempty"`
|
||||
Model string `gorm:"column:model;size:60" json:"model,omitempty"`
|
||||
|
||||
InputSnapshot []byte `gorm:"column:input_snapshot;type:json" json:"input_snapshot,omitempty"`
|
||||
Advice string `gorm:"column:advice;type:mediumtext" json:"advice"`
|
||||
|
||||
TokensIn *int `gorm:"column:tokens_in" json:"tokens_in,omitempty"`
|
||||
TokensOut *int `gorm:"column:tokens_out" json:"tokens_out,omitempty"`
|
||||
CostCent *int `gorm:"column:cost_cent" json:"cost_cent,omitempty"`
|
||||
|
||||
CreateTime *int64 `gorm:"column:createtime" json:"createtime,omitempty"`
|
||||
UpdateTime *int64 `gorm:"column:updatetime" json:"updatetime,omitempty"`
|
||||
DeleteTime *int64 `gorm:"column:deletetime" json:"deletetime,omitempty"`
|
||||
}
|
||||
|
||||
func (SmokeAIAdvice) TableName() string {
|
||||
return "fa_smoke_ai_advice"
|
||||
}
|
||||
|
||||
// SmokeAIAdviceUnlock 对应表 fa_smoke_ai_advice_unlocks(非会员用户的每日广告解锁记录)。
|
||||
type SmokeAIAdviceUnlock struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UID int `gorm:"column:uid;index:idx_smoke_ai_unlock_uid_date,priority:1;uniqueIndex:uniq_smoke_ai_unlock,priority:1" json:"-"`
|
||||
|
||||
UnlockDate time.Time `gorm:"column:unlock_date;type:date;index:idx_smoke_ai_unlock_uid_date,priority:2;uniqueIndex:uniq_smoke_ai_unlock,priority:2" json:"unlock_date"`
|
||||
AdWatchedAt time.Time `gorm:"column:ad_watched_at" json:"ad_watched_at"`
|
||||
|
||||
CreateTime *int64 `gorm:"column:createtime" json:"createtime,omitempty"`
|
||||
UpdateTime *int64 `gorm:"column:updatetime" json:"updatetime,omitempty"`
|
||||
DeleteTime *int64 `gorm:"column:deletetime" json:"deletetime,omitempty"`
|
||||
}
|
||||
|
||||
func (SmokeAIAdviceUnlock) TableName() string {
|
||||
return "fa_smoke_ai_advice_unlocks"
|
||||
}
|
||||
@@ -13,6 +13,8 @@ type SmokeLog struct {
|
||||
|
||||
// smoke_time 在库里是 date 类型(只包含日期,不包含时分秒)。
|
||||
SmokeTime *time.Time `gorm:"column:smoke_time;type:date" json:"smoke_time,omitempty"`
|
||||
// smoke_at:真实抽烟时间(可补录,精确到时分秒)
|
||||
SmokeAt *time.Time `gorm:"column:smoke_at;type:datetime" json:"smoke_at,omitempty"`
|
||||
|
||||
Remark string `gorm:"column:remark;type:text" json:"remark,omitempty"`
|
||||
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/config"
|
||||
usermodel "wx_service/internal/model"
|
||||
smokemodel "wx_service/internal/smoke/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAIAdviceLocked = errors.New("ai advice is locked, vip or ad unlock required")
|
||||
ErrAIServiceDisabled = errors.New("ai service is not configured")
|
||||
ErrNoSmokeLogs = errors.New("no smoke logs for date")
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultAdvicePromptVersion = "v1"
|
||||
defaultTemperature = 0.7
|
||||
)
|
||||
|
||||
type SmokeAIAdviceService struct {
|
||||
db *gorm.DB
|
||||
cfg config.AIConfig
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewSmokeAIAdviceService(db *gorm.DB, cfg config.AIConfig) *SmokeAIAdviceService {
|
||||
timeout := cfg.RequestTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 15 * time.Second
|
||||
}
|
||||
return &SmokeAIAdviceService{
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
client: &http.Client{
|
||||
Timeout: timeout,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type adviceSnapshotNode struct {
|
||||
Time string `json:"time"`
|
||||
Num int `json:"num"`
|
||||
Level int64 `json:"level"`
|
||||
Remark string `json:"remark,omitempty"`
|
||||
}
|
||||
|
||||
type adviceSnapshot struct {
|
||||
Date string `json:"date"`
|
||||
TotalNum int `json:"total_num"`
|
||||
Nodes []adviceSnapshotNode `json:"nodes"`
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) GetOrGenerate(ctx context.Context, user *usermodel.User, adviceDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) {
|
||||
if promptVersion == "" {
|
||||
promptVersion = DefaultAdvicePromptVersion
|
||||
}
|
||||
|
||||
cached, err := s.getCached(ctx, int(user.ID), adviceDate, promptVersion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cached != nil {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
allowed, err := s.isAllowed(ctx, user, adviceDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !allowed {
|
||||
return nil, ErrAIAdviceLocked
|
||||
}
|
||||
|
||||
snapshot, snapshotJSON, err := s.buildSnapshot(ctx, int(user.ID), adviceDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
adviceText, modelName, tokensIn, tokensOut, err := s.callAI(ctx, snapshot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
createTime := now
|
||||
updateTime := now
|
||||
|
||||
record := smokemodel.SmokeAIAdvice{
|
||||
UID: int(user.ID),
|
||||
AdviceDate: dateOnly(adviceDate),
|
||||
PromptVersion: promptVersion,
|
||||
Provider: "openai-compatible",
|
||||
Model: modelName,
|
||||
InputSnapshot: snapshotJSON,
|
||||
Advice: adviceText,
|
||||
TokensIn: tokensIn,
|
||||
TokensOut: tokensOut,
|
||||
CreateTime: &createTime,
|
||||
UpdateTime: &updateTime,
|
||||
}
|
||||
|
||||
if err := s.db.WithContext(ctx).Create(&record).Error; err != nil {
|
||||
return nil, fmt.Errorf("save ai advice: %w", err)
|
||||
}
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) Unlock(ctx context.Context, user *usermodel.User, unlockDate time.Time) error {
|
||||
now := time.Now()
|
||||
nowUnix := now.Unix()
|
||||
startOfDay := dateOnly(unlockDate)
|
||||
|
||||
var existing smokemodel.SmokeAIAdviceUnlock
|
||||
tx := s.db.WithContext(ctx)
|
||||
err := tx.Where("uid = ? AND unlock_date = ? AND (deletetime IS NULL OR deletetime = 0)", user.ID, startOfDay.Format("2006-01-02")).
|
||||
First(&existing).Error
|
||||
if err == nil {
|
||||
return tx.Model(&existing).Updates(map[string]interface{}{
|
||||
"ad_watched_at": now,
|
||||
"updatetime": nowUnix,
|
||||
}).Error
|
||||
}
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("load unlock record: %w", err)
|
||||
}
|
||||
|
||||
createTime := nowUnix
|
||||
updateTime := nowUnix
|
||||
record := smokemodel.SmokeAIAdviceUnlock{
|
||||
UID: int(user.ID),
|
||||
UnlockDate: startOfDay,
|
||||
AdWatchedAt: now,
|
||||
CreateTime: &createTime,
|
||||
UpdateTime: &updateTime,
|
||||
}
|
||||
if err := tx.Create(&record).Error; err != nil {
|
||||
return fmt.Errorf("create unlock record: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) getCached(ctx context.Context, uid int, adviceDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) {
|
||||
var record smokemodel.SmokeAIAdvice
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("uid = ? AND advice_date = ? AND prompt_version = ? AND (deletetime IS NULL OR deletetime = 0)",
|
||||
uid, dateOnly(adviceDate).Format("2006-01-02"), promptVersion).
|
||||
First(&record).Error
|
||||
if err == nil {
|
||||
return &record, nil
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("load cached advice: %w", err)
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) isAllowed(ctx context.Context, user *usermodel.User, adviceDate time.Time) (bool, error) {
|
||||
isVIP, err := s.isVIP(ctx, user)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if isVIP {
|
||||
return true, nil
|
||||
}
|
||||
return s.isUnlocked(ctx, int(user.ID), adviceDate)
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) isVIP(ctx context.Context, user *usermodel.User) (bool, error) {
|
||||
now := time.Now()
|
||||
var count int64
|
||||
if err := s.db.WithContext(ctx).
|
||||
Model(&usermodel.UserMembership{}).
|
||||
Where("mini_program_id = ? AND user_id = ? AND status = ? AND ends_at > ?",
|
||||
user.MiniProgramID, user.ID, "active", now).
|
||||
Count(&count).Error; err != nil {
|
||||
return false, fmt.Errorf("check vip: %w", err)
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) isUnlocked(ctx context.Context, uid int, adviceDate time.Time) (bool, error) {
|
||||
startOfDay := dateOnly(adviceDate)
|
||||
var unlock smokemodel.SmokeAIAdviceUnlock
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("uid = ? AND unlock_date = ? AND (deletetime IS NULL OR deletetime = 0)", uid, startOfDay.Format("2006-01-02")).
|
||||
First(&unlock).Error
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("check unlock: %w", err)
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) buildSnapshot(ctx context.Context, uid int, adviceDate time.Time) (adviceSnapshot, []byte, error) {
|
||||
var logs []smokemodel.SmokeLog
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("uid = ? AND smoke_time = ? AND (deletetime IS NULL OR deletetime = 0)", uid, dateOnly(adviceDate).Format("2006-01-02")).
|
||||
Find(&logs).Error; err != nil {
|
||||
return adviceSnapshot{}, nil, fmt.Errorf("load smoke logs: %w", err)
|
||||
}
|
||||
if len(logs) == 0 {
|
||||
return adviceSnapshot{}, nil, ErrNoSmokeLogs
|
||||
}
|
||||
|
||||
type timedLog struct {
|
||||
log smokemodel.SmokeLog
|
||||
eventAt time.Time
|
||||
hasEvent bool
|
||||
}
|
||||
|
||||
timed := make([]timedLog, 0, len(logs))
|
||||
total := 0
|
||||
for _, l := range logs {
|
||||
total += l.Num
|
||||
var eventAt time.Time
|
||||
has := false
|
||||
if l.SmokeAt != nil {
|
||||
eventAt = *l.SmokeAt
|
||||
has = true
|
||||
} else if l.CreateTime != nil && *l.CreateTime > 0 {
|
||||
eventAt = time.Unix(*l.CreateTime, 0).In(time.Local)
|
||||
has = true
|
||||
}
|
||||
timed = append(timed, timedLog{log: l, eventAt: eventAt, hasEvent: has})
|
||||
}
|
||||
|
||||
// 按时间节点排序(若没有 event time,则排在最后,仍保持稳定)
|
||||
sort.SliceStable(timed, func(i, j int) bool {
|
||||
a := timed[i]
|
||||
b := timed[j]
|
||||
if a.hasEvent && b.hasEvent {
|
||||
if !a.eventAt.Equal(b.eventAt) {
|
||||
return a.eventAt.Before(b.eventAt)
|
||||
}
|
||||
return a.log.ID < b.log.ID
|
||||
}
|
||||
if a.hasEvent != b.hasEvent {
|
||||
return a.hasEvent
|
||||
}
|
||||
return a.log.ID < b.log.ID
|
||||
})
|
||||
|
||||
nodes := make([]adviceSnapshotNode, 0, len(timed))
|
||||
for _, t := range timed {
|
||||
timeLabel := ""
|
||||
if t.hasEvent {
|
||||
timeLabel = t.eventAt.Format("15:04")
|
||||
}
|
||||
nodes = append(nodes, adviceSnapshotNode{
|
||||
Time: timeLabel,
|
||||
Num: t.log.Num,
|
||||
Level: t.log.Level,
|
||||
Remark: t.log.Remark,
|
||||
})
|
||||
}
|
||||
|
||||
snap := adviceSnapshot{
|
||||
Date: dateOnly(adviceDate).Format("2006-01-02"),
|
||||
TotalNum: total,
|
||||
Nodes: nodes,
|
||||
}
|
||||
|
||||
b, err := json.Marshal(snap)
|
||||
if err != nil {
|
||||
return adviceSnapshot{}, nil, fmt.Errorf("marshal snapshot: %w", err)
|
||||
}
|
||||
return snap, b, nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) callAI(ctx context.Context, snap adviceSnapshot) (string, string, *int, *int, error) {
|
||||
if s.cfg.APIKey == "" || s.cfg.Model == "" || s.cfg.BaseURL == "" {
|
||||
return "", "", nil, nil, ErrAIServiceDisabled
|
||||
}
|
||||
|
||||
systemPrompt := strings.TrimSpace(`
|
||||
你是一名专业的戒烟教练与行为改变顾问。你需要基于用户昨天的抽烟总量与时间节点,给出可执行、可量化的戒烟/控烟建议。
|
||||
要求:
|
||||
1) 用中文输出;
|
||||
2) 先给出对昨天模式的简短分析(1-3条);
|
||||
3) 给出今天的具体行动方案(至少5条,包含替代行为、触发场景应对、时间节点策略);
|
||||
4) 给出一个“如果忍不住想抽”的 60 秒应对流程;
|
||||
5) 语气友好、不指责;不提供医疗诊断。
|
||||
`)
|
||||
|
||||
userPrompt := fmt.Sprintf("用户昨日数据(JSON):\n%s", mustJSON(snap))
|
||||
|
||||
reqBody := chatCompletionRequest{
|
||||
Model: s.cfg.Model,
|
||||
Messages: []chatMessage{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: userPrompt},
|
||||
},
|
||||
Temperature: defaultTemperature,
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("marshal ai request: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(s.cfg.BaseURL, "/") + "/chat/completions"
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("build ai request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+s.cfg.APIKey)
|
||||
|
||||
resp, err := s.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("call ai: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("read ai response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", "", nil, nil, fmt.Errorf("ai http %d: %s", resp.StatusCode, truncateString(string(body), 512))
|
||||
}
|
||||
|
||||
var parsed chatCompletionResponse
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("parse ai response: %w", err)
|
||||
}
|
||||
if len(parsed.Choices) == 0 {
|
||||
return "", "", nil, nil, errors.New("ai response has no choices")
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(parsed.Choices[0].Message.Content)
|
||||
if content == "" {
|
||||
return "", "", nil, nil, errors.New("ai response content is empty")
|
||||
}
|
||||
|
||||
modelName := parsed.Model
|
||||
if modelName == "" {
|
||||
modelName = s.cfg.Model
|
||||
}
|
||||
|
||||
var tokensIn, tokensOut *int
|
||||
if parsed.Usage != nil {
|
||||
tokensIn = &parsed.Usage.PromptTokens
|
||||
tokensOut = &parsed.Usage.CompletionTokens
|
||||
}
|
||||
|
||||
return content, modelName, tokensIn, tokensOut, nil
|
||||
}
|
||||
|
||||
type chatMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type chatCompletionRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []chatMessage `json:"messages"`
|
||||
Temperature float64 `json:"temperature,omitempty"`
|
||||
}
|
||||
|
||||
type chatCompletionResponse struct {
|
||||
Model string `json:"model"`
|
||||
Choices []struct {
|
||||
Message chatMessage `json:"message"`
|
||||
} `json:"choices"`
|
||||
Usage *struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
|
||||
func dateOnly(t time.Time) time.Time {
|
||||
local := t.In(time.Local)
|
||||
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, time.Local)
|
||||
}
|
||||
|
||||
func mustJSON(v any) string {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func truncateString(s string, max int) string {
|
||||
if max <= 0 || len(s) <= max {
|
||||
return s
|
||||
}
|
||||
return s[:max]
|
||||
}
|
||||
@@ -25,6 +25,7 @@ func NewSmokeLogService(db *gorm.DB) *SmokeLogService {
|
||||
|
||||
type CreateSmokeLogRequest struct {
|
||||
SmokeTime *time.Time
|
||||
SmokeAt *time.Time
|
||||
Remark string
|
||||
Level int64
|
||||
Num int
|
||||
@@ -44,7 +45,14 @@ func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLo
|
||||
num = 1
|
||||
}
|
||||
|
||||
smokeAt := req.SmokeAt
|
||||
|
||||
// smokeTime 用于“按天筛选”;如果传了 smokeAt,建议用其日期部分回填 smokeTime,避免出现不一致。
|
||||
smokeTime := req.SmokeTime
|
||||
if smokeAt != nil {
|
||||
day := time.Date(smokeAt.Year(), smokeAt.Month(), smokeAt.Day(), 0, 0, 0, 0, smokeAt.Location())
|
||||
smokeTime = &day
|
||||
}
|
||||
if smokeTime == nil {
|
||||
today := time.Now()
|
||||
startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
|
||||
@@ -54,6 +62,7 @@ func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLo
|
||||
record := smokemodel.SmokeLog{
|
||||
UID: uid,
|
||||
SmokeTime: smokeTime,
|
||||
SmokeAt: smokeAt,
|
||||
Remark: req.Remark,
|
||||
CreateTime: &createTime,
|
||||
UpdateTime: &updateTime,
|
||||
@@ -148,6 +157,11 @@ type UpdateSmokeLogRequest struct {
|
||||
// - true:前端传了 smoke_time(可以设置为具体日期,也可以清空为 NULL)
|
||||
SmokeTimeProvided bool
|
||||
SmokeTime *time.Time
|
||||
// SmokeAtProvided 用于区分:
|
||||
// - false:前端没传 smoke_at(不修改)
|
||||
// - true:前端传了 smoke_at(可以设置为具体时间,也可以清空为 NULL)
|
||||
SmokeAtProvided bool
|
||||
SmokeAt *time.Time
|
||||
Remark *string
|
||||
Level *int64
|
||||
Num *int
|
||||
@@ -163,6 +177,13 @@ func (s *SmokeLogService) Update(ctx context.Context, uid int, id int, req Updat
|
||||
if req.SmokeTimeProvided {
|
||||
updates["smoke_time"] = req.SmokeTime
|
||||
}
|
||||
if req.SmokeAtProvided {
|
||||
updates["smoke_at"] = req.SmokeAt
|
||||
if req.SmokeAt != nil {
|
||||
day := time.Date(req.SmokeAt.Year(), req.SmokeAt.Month(), req.SmokeAt.Day(), 0, 0, 0, 0, req.SmokeAt.Location())
|
||||
updates["smoke_time"] = &day
|
||||
}
|
||||
}
|
||||
if req.Remark != nil {
|
||||
updates["remark"] = *req.Remark
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user