feat: initialize Eino examples and ADK applications
Include chat, weather, image, travel, streaming ASR and text examples, shared model initialization, documentation, and existing tests. Co-authored-by: TRAE CLI <traecli@bytedance.com>
This commit is contained in:
commit
81deca8c8e
75 files changed
+7048
No files matched your search
@@ -0,0 +1,83 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Memory 保存一个会话的历史和摘要。
|
||||
type Memory struct {
|
||||
maxToken int
|
||||
history []model.ChatMessage
|
||||
summary []string
|
||||
summarized int
|
||||
}
|
||||
|
||||
// NewMemory 设置历史和摘要共用的预算,按 UTF-8 字节数加消息开销保守估算。
|
||||
// 预算小于等于 0 时不保存记忆。
|
||||
func NewMemory(maxToken int) *Memory {
|
||||
return &Memory{
|
||||
maxToken: maxToken,
|
||||
}
|
||||
}
|
||||
|
||||
// Save 在工具调用和流式输出结束后保存一轮完整对话。
|
||||
func (m *Memory) Save(req, res string) {
|
||||
if m.maxToken <= 0 {
|
||||
return
|
||||
}
|
||||
m.history = append(m.history,
|
||||
model.ChatMessage{Role: "user", Content: req},
|
||||
model.ChatMessage{Role: "assistant", Content: res},
|
||||
)
|
||||
if len(m.history)/2-m.summarized >= 10 {
|
||||
for i := m.summarized * 2; i < len(m.history); i += 2 {
|
||||
m.summary = append(m.summary, m.history[i].Content.(string))
|
||||
}
|
||||
m.summarized = len(m.history) / 2
|
||||
}
|
||||
|
||||
size := 0
|
||||
for _, message := range m.history {
|
||||
size += len(message.Content.(string)) + 4
|
||||
}
|
||||
for _, input := range m.summary {
|
||||
size += len(input) + len("\n---\n")
|
||||
}
|
||||
// 按完整条目淘汰,先删除最旧的摘要,再删除最旧的历史。
|
||||
for size > m.maxToken && len(m.summary) > 0 {
|
||||
size -= len(m.summary[0]) + len("\n---\n")
|
||||
m.summary = slices.Delete(m.summary, 0, 1)
|
||||
}
|
||||
for size > m.maxToken && len(m.history) > 0 {
|
||||
size -= len(m.history[0].Content.(string)) + len(m.history[1].Content.(string)) + 8
|
||||
m.history = slices.Delete(m.history, 0, 2)
|
||||
if m.summarized > 0 {
|
||||
m.summarized--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LoadHistory 按用户、模型顺序返回最近 N 轮消息,默认返回 10 轮(20 条)。
|
||||
// N 小于等于 0 时返回空历史;只使用 maxRound 的第一个值。
|
||||
func (m *Memory) LoadHistory(maxRound ...int) []model.ChatMessage {
|
||||
limit := 10
|
||||
if len(maxRound) > 0 {
|
||||
limit = maxRound[0]
|
||||
}
|
||||
if limit <= 0 {
|
||||
return nil
|
||||
}
|
||||
start := 0
|
||||
if limit < len(m.history)/2 {
|
||||
start = len(m.history) - limit*2
|
||||
}
|
||||
return slices.Clone(m.history[start:])
|
||||
}
|
||||
|
||||
// LoadSummary 返回每 10 轮归档的用户输入,用于嵌入系统提示词。
|
||||
func (m *Memory) LoadSummary() string {
|
||||
return strings.Join(m.summary, "\n---\n")
|
||||
}
|
||||
Reference in new issue
Block a user