thread-master/old/backend/internal/library/webpage/format.go

53 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package webpage
import (
"strings"
)
// FormatMarkdownBlock renders digests for LLM prompts.
func FormatMarkdownBlock(digests []Digest, maxTotal int) string {
if len(digests) == 0 {
return ""
}
if maxTotal <= 0 {
maxTotal = DefaultMaxMarkdown
}
var b strings.Builder
used := 0
for i, item := range digests {
if used >= maxTotal {
break
}
section := formatDigestSection(item)
if section == "" {
continue
}
if i > 0 {
b.WriteString("\n\n---\n\n")
}
remain := maxTotal - used
runes := []rune(section)
if len(runes) > remain {
section = string(runes[:remain]) + "…"
}
b.WriteString(section)
used += len([]rune(section))
}
return strings.TrimSpace(b.String())
}
func formatDigestSection(item Digest) string {
if strings.TrimSpace(item.Markdown) != "" {
var b strings.Builder
b.WriteString("來源:")
b.WriteString(item.URL)
b.WriteString("\n")
b.WriteString(item.Markdown)
return strings.TrimSpace(b.String())
}
if strings.TrimSpace(item.Error) == "" {
return ""
}
return "來源:" + item.URL + "\n抓取失敗" + item.Error + ""
}