miaopanel
1package ai
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "strings"
9 "time"
10
11 "github.com/miaopanel/miaopanel/internal/store"
12 "github.com/miaopanel/miaopanel/internal/system"
13)
14
15// buildMessages turns the stored history into provider messages, prefixed with
16// the operator prompt and a short description of this host.
17func (s *Service) buildMessages(ctx context.Context, st Settings, sessionID string) ([]ChatMessage, error) {
18 history, err := s.db.RecentAIMessages(ctx, sessionID, 30)
19 if err != nil {
20 return nil, err
21 }
22 host, _ := os.Hostname()
23 distro := system.Detect()
24 systemPrompt := fmt.Sprintf("%s\n\n当前环境:面板 v%s,主机 %s,系统 %s %s(%s),时间 %s。",
25 st.SystemPrompt, s.version, host, distro.PrettyName, distro.Version,
26 distro.Arch, time.Now().Format("2006-01-02 15:04:05"))
27
28 out := []ChatMessage{{Role: "system", Content: systemPrompt}}
29 out = append(out, convertHistory(history)...)
30 return out, nil
31}
32
33// convertHistory replays stored messages, dropping orphaned tool exchanges so
34// the provider never sees a tool result without its assistant call.
35func convertHistory(history []*store.AIMessage) []ChatMessage {
36 type parsed struct {
37 msg *store.AIMessage
38 calls []ToolCall
39 }
40 items := make([]parsed, 0, len(history))
41 for _, m := range history {
42 p := parsed{msg: m}
43 if m.Role == "assistant" && m.ToolCalls != "" {
44 var calls []ToolCall
45 if err := json.Unmarshal([]byte(m.ToolCalls), &calls); err == nil {
46 p.calls = calls
47 }
48 }
49 items = append(items, p)
50 }
51
52 // Only assistant messages whose every tool call has a following result are
53 // safe to replay.
54 valid := map[string]bool{}
55 for i, p := range items {
56 if len(p.calls) == 0 {
57 continue
58 }
59 answers := map[string]bool{}
60 for j := i + 1; j < len(items); j++ {
61 if items[j].msg.Role == "assistant" {
62 break
63 }
64 if items[j].msg.Role == "tool" && items[j].msg.ToolCallID != "" {
65 answers[items[j].msg.ToolCallID] = true
66 }
67 }
68 complete := true
69 for _, c := range p.calls {
70 if !answers[c.ID] {
71 complete = false
72 break
73 }
74 }
75 if complete {
76 for _, c := range p.calls {
77 valid[c.ID] = true
78 }
79 }
80 }
81
82 out := make([]ChatMessage, 0, len(items))
83 for _, p := range items {
84 m := p.msg
85 switch m.Role {
86 case "user":
87 if strings.TrimSpace(m.Content) != "" {
88 out = append(out, ChatMessage{Role: "user", Content: m.Content})
89 }
90 case "assistant":
91 if len(p.calls) > 0 {
92 if !valid[p.calls[0].ID] {
93 continue
94 }
95 out = append(out, ChatMessage{
96 Role: "assistant", Content: m.Content, ToolCalls: p.calls,
97 })
98 } else if strings.TrimSpace(m.Content) != "" {
99 out = append(out, ChatMessage{Role: "assistant", Content: m.Content})
100 }
101 case "tool":
102 if m.ToolCallID != "" && valid[m.ToolCallID] {
103 out = append(out, ChatMessage{
104 Role: "tool", Content: m.Content, ToolCallID: m.ToolCallID, Name: m.Name,
105 })
106 }
107 }
108 }
109 // A tool message must never lead the history.
110 for len(out) > 0 && out[0].Role == "tool" {
111 out = out[1:]
112 }
113 return out
114}