feat(smoke): 增加 AI 今日总结接口与首页缓存透出
This commit is contained in:
@@ -31,10 +31,13 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
SmokeAIAdviceTypeDaily = "daily_advice"
|
||||
SmokeAIAdviceTypeNextSmoke = "next_smoke_time"
|
||||
SmokeAIAdviceTypeDaily = "daily_advice"
|
||||
SmokeAIAdviceTypeNextSmoke = "next_smoke_time"
|
||||
SmokeAIAdviceTypeDailySummary = "daily_summary"
|
||||
)
|
||||
|
||||
const DefaultSummaryPromptVersion = "v1"
|
||||
|
||||
type SmokeAIAdviceService struct {
|
||||
db *gorm.DB
|
||||
cfg config.AIConfig
|
||||
@@ -188,6 +191,11 @@ func (s *SmokeAIAdviceService) getCached(ctx context.Context, uid int, adviceTyp
|
||||
return nil, fmt.Errorf("load cached advice: %w", err)
|
||||
}
|
||||
|
||||
// GetCachedByType 公开方法,供 handler 层读取指定类型的 AI 缓存。
|
||||
func (s *SmokeAIAdviceService) GetCachedByType(ctx context.Context, uid int, adviceType string, adviceDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) {
|
||||
return s.getCached(ctx, uid, adviceType, adviceDate, promptVersion)
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) isAllowed(ctx context.Context, user *usermodel.User, adviceDate time.Time) (bool, error) {
|
||||
isVIP, err := hasActiveMembership(ctx, s.db, user.MiniProgramID, user.ID, time.Now())
|
||||
if err != nil {
|
||||
@@ -466,3 +474,159 @@ func deriveUserSegment(baselineCigsPerDay int, smokingYears float64) string {
|
||||
}
|
||||
return "newbie"
|
||||
}
|
||||
|
||||
// DailySummaryResult 是 AI 今日总结的结构化返回。
|
||||
type DailySummaryResult struct {
|
||||
Summary string `json:"summary"`
|
||||
Highlights []string `json:"highlights"`
|
||||
Suggestion string `json:"suggestion"`
|
||||
}
|
||||
|
||||
var ErrNoSmokeLogsToday = errors.New("today has no smoke logs yet")
|
||||
|
||||
func (s *SmokeAIAdviceService) GetOrGenerateDailySummary(
|
||||
ctx context.Context,
|
||||
user *usermodel.User,
|
||||
summaryDate time.Time,
|
||||
promptVersion string,
|
||||
) (*smokemodel.SmokeAIAdvice, error) {
|
||||
if promptVersion == "" {
|
||||
promptVersion = DefaultSummaryPromptVersion
|
||||
}
|
||||
|
||||
cached, err := s.getCached(ctx, int(user.ID), SmokeAIAdviceTypeDailySummary, summaryDate, promptVersion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cached != nil {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
allowed, err := s.isAllowed(ctx, user, summaryDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !allowed {
|
||||
return nil, ErrAIAdviceLocked
|
||||
}
|
||||
|
||||
snapshot, snapshotJSON, err := s.buildSnapshot(ctx, int(user.ID), summaryDate)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoSmokeLogs) {
|
||||
return nil, ErrNoSmokeLogsToday
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
adviceText, modelName, tokensIn, tokensOut, err := s.callAIDailySummary(ctx, snapshot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
record := smokemodel.SmokeAIAdvice{
|
||||
UID: int(user.ID),
|
||||
Type: SmokeAIAdviceTypeDailySummary,
|
||||
AdviceDate: dateOnly(summaryDate),
|
||||
PromptVersion: promptVersion,
|
||||
Provider: "openai-compatible",
|
||||
Model: modelName,
|
||||
InputSnapshot: snapshotJSON,
|
||||
Advice: adviceText,
|
||||
TokensIn: tokensIn,
|
||||
TokensOut: tokensOut,
|
||||
CreateTime: &now,
|
||||
UpdateTime: &now,
|
||||
}
|
||||
|
||||
if err := s.db.WithContext(ctx).Create(&record).Error; err != nil {
|
||||
return nil, fmt.Errorf("save daily summary: %w", err)
|
||||
}
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) callAIDailySummary(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) 输出严格的 JSON 格式(不要 markdown 代码块),结构如下:
|
||||
{
|
||||
"summary": "一段 50-100 字的今日总结,概括抽烟模式和整体表现",
|
||||
"highlights": ["亮点或关键发现1", "亮点或关键发现2", "亮点或关键发现3"],
|
||||
"suggestion": "一条具体的、可执行的明日改进建议(30-60字)"
|
||||
}
|
||||
3) summary 应包含:今日总量、时间分布特点、烟瘾等级趋势;
|
||||
4) highlights 给出 2-4 条关键发现(如高峰时段、触发场景、与昨日对比等);
|
||||
5) suggestion 给出明天可以尝试的一个具体行动;
|
||||
6) 如果有 profile 信息,结合用户的戒烟动力和作息来个性化建议。
|
||||
`)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user