package ai import ( "context" "encoding/json" "fmt" "os" "strings" "time" "github.com/miaopanel/miaopanel/internal/store" "github.com/miaopanel/miaopanel/internal/system" ) // buildMessages turns the stored history into provider messages, prefixed with // the operator prompt and a short description of this host. func (s *Service) buildMessages(ctx context.Context, st Settings, sessionID string) ([]ChatMessage, error) { history, err := s.db.RecentAIMessages(ctx, sessionID, 30) if err != nil { return nil, err } host, _ := os.Hostname() distro := system.Detect() systemPrompt := fmt.Sprintf("%s\n\n当前环境:面板 v%s,主机 %s,系统 %s %s(%s),时间 %s。", st.SystemPrompt, s.version, host, distro.PrettyName, distro.Version, distro.Arch, time.Now().Format("2006-01-02 15:04:05")) out := []ChatMessage{{Role: "system", Content: systemPrompt}} out = append(out, convertHistory(history)...) return out, nil } // convertHistory replays stored messages, dropping orphaned tool exchanges so // the provider never sees a tool result without its assistant call. func convertHistory(history []*store.AIMessage) []ChatMessage { type parsed struct { msg *store.AIMessage calls []ToolCall } items := make([]parsed, 0, len(history)) for _, m := range history { p := parsed{msg: m} if m.Role == "assistant" && m.ToolCalls != "" { var calls []ToolCall if err := json.Unmarshal([]byte(m.ToolCalls), &calls); err == nil { p.calls = calls } } items = append(items, p) } // Only assistant messages whose every tool call has a following result are // safe to replay. valid := map[string]bool{} for i, p := range items { if len(p.calls) == 0 { continue } answers := map[string]bool{} for j := i + 1; j < len(items); j++ { if items[j].msg.Role == "assistant" { break } if items[j].msg.Role == "tool" && items[j].msg.ToolCallID != "" { answers[items[j].msg.ToolCallID] = true } } complete := true for _, c := range p.calls { if !answers[c.ID] { complete = false break } } if complete { for _, c := range p.calls { valid[c.ID] = true } } } out := make([]ChatMessage, 0, len(items)) for _, p := range items { m := p.msg switch m.Role { case "user": if strings.TrimSpace(m.Content) != "" { out = append(out, ChatMessage{Role: "user", Content: m.Content}) } case "assistant": if len(p.calls) > 0 { if !valid[p.calls[0].ID] { continue } out = append(out, ChatMessage{ Role: "assistant", Content: m.Content, ToolCalls: p.calls, }) } else if strings.TrimSpace(m.Content) != "" { out = append(out, ChatMessage{Role: "assistant", Content: m.Content}) } case "tool": if m.ToolCallID != "" && valid[m.ToolCallID] { out = append(out, ChatMessage{ Role: "tool", Content: m.Content, ToolCallID: m.ToolCallID, Name: m.Name, }) } } } // A tool message must never lead the history. for len(out) > 0 && out[0].Role == "tool" { out = out[1:] } return out }