feat: initialize terminal chat example with streaming and memory

This commit is contained in:
loveuer committed 2026-11-13 18:55:08 +08:00
commit 43fc905c82
13 files changed
+666

No files matched your search

+83
View File
@@ -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")
}
+102
View File
@@ -0,0 +1,102 @@
package memory
import (
"fmt"
"strings"
"testing"
)
func TestLoadHistoryMessages(t *testing.T) {
m := NewMemory(4096)
for i := 0; i < 12; i++ {
m.Save(fmt.Sprintf("问题%d", i), fmt.Sprintf("回答%d", i))
}
for _, tt := range []struct {
name string
limit []int
rounds int
}{
{name: "默认十轮", rounds: 10},
{name: "最近两轮", limit: []int{2}, rounds: 2},
{name: "全部历史", limit: []int{100}, rounds: 12},
{name: "零轮", limit: []int{0}},
{name: "负数轮", limit: []int{-1}},
} {
t.Run(tt.name, func(t *testing.T) {
messages := m.LoadHistory(tt.limit...)
if len(messages) != tt.rounds*2 {
t.Fatalf("消息数 = %d,期望 %d", len(messages), tt.rounds*2)
}
for i := 0; i < tt.rounds; i++ {
round := 12 - tt.rounds + i
if messages[i*2].Role != "user" || messages[i*2].Content != fmt.Sprintf("问题%d", round) || messages[i*2+1].Role != "assistant" || messages[i*2+1].Content != fmt.Sprintf("回答%d", round) {
t.Fatalf("第 %d 轮消息内容或顺序不正确: %+v", round, messages[i*2:i*2+2])
}
}
})
}
messages := m.LoadHistory(1)
messages[0].Content = "修改"
if m.LoadHistory(1)[0].Content != "问题11" {
t.Fatal("修改返回消息不应影响保存的历史")
}
}
func TestMemoryBudget(t *testing.T) {
for _, budget := range []int{0, -1, 40, 200, 1000} {
t.Run(fmt.Sprint(budget), func(t *testing.T) {
m := NewMemory(budget)
for i := 0; i < 1000; i++ {
m.Save(fmt.Sprintf("问题%d", i), "回答")
size := len(m.LoadSummary())
for _, message := range m.LoadHistory(10000) {
size += len(message.Content.(string)) + 4
}
if size > max(budget, 0) {
t.Fatalf("memory size %d exceeds budget %d", size, budget)
}
}
})
}
}
func TestMemoryDropsOversizedRound(t *testing.T) {
m := NewMemory(40)
m.Save("old", "reply")
m.Save(strings.Repeat("中", 100), "reply")
if len(m.LoadHistory()) != 0 || m.LoadSummary() != "" {
t.Fatal("oversized round should be dropped")
}
m.Save("new", "reply")
if got := m.LoadHistory(); len(got) != 2 || got[0].Role != "user" || got[0].Content != "new" || got[1].Role != "assistant" || got[1].Content != "reply" {
t.Fatalf("memory did not recover: %v", got)
}
}
func TestMemoryEmptyRoundsAreBounded(t *testing.T) {
m := NewMemory(80)
for i := 0; i < 1000; i++ {
m.Save("", "")
}
if len(m.LoadHistory(10000)) > 20 {
t.Fatal("empty history grows without bound")
}
}
func TestSummaryAfterHistoryEviction(t *testing.T) {
m := NewMemory(200)
for i := 0; i < 10; i++ {
m.Save(fmt.Sprint(i), "")
}
m.Save(strings.Repeat("x", 201), "")
for i := 10; i < 20; i++ {
m.Save(fmt.Sprint(i), "")
}
want := make([]string, 10)
for i := range want {
want[i] = fmt.Sprint(i + 10)
}
if got := m.LoadSummary(); got != strings.Join(want, "\n---\n") {
t.Fatalf("summary after eviction = %q", got)
}
}
+26
View File
@@ -0,0 +1,26 @@
package model
// ChatCompletionRequest 表示对话接口的请求参数。
type ChatCompletionRequest struct {
Model string `json:"model"`
Messages []ChatMessage `json:"messages"`
Stream bool `json:"stream,omitempty"`
}
// ChatCompletionResponse 表示对话接口的响应。
type ChatCompletionResponse struct {
Choices []ChatCompletionChoice `json:"choices"`
}
// ChatCompletionChoice 表示模型返回的一个候选回答。
type ChatCompletionChoice struct {
Message ChatMessage `json:"message"`
Delta ChatCompletionDelta `json:"delta"`
FinishReason string `json:"finish_reason"`
}
// ChatCompletionDelta 表示流式响应中的增量内容。
type ChatCompletionDelta struct {
Content string `json:"content"`
ToolCalls []ToolCall `json:"tool_calls"`
}
+70
View File
@@ -0,0 +1,70 @@
package model
import "strings"
type ChatInputType string
const (
ChatInputTypeTxt ChatInputType = "text"
ChatInputTypeImg ChatInputType = "image"
)
type ChatInput struct {
Type ChatInputType
// 文字为原文,图片为图片地址或 base64 data URL。
Data string
}
type ChatInputs []*ChatInput
// Text 返回用于保存历史的文字,图片用占位文字表示。
func (i ChatInputs) Text() string {
var texts []string
for _, input := range i {
if input == nil {
continue
}
switch input.Type {
case ChatInputTypeTxt:
texts = append(texts, input.Data)
case ChatInputTypeImg:
texts = append(texts, "[图片]")
}
}
return strings.Join(texts, "\n")
}
func (i ChatInputs) Format() *ChatMessage {
if len(i) == 0 {
return nil
}
cs := make([]any, 0)
for _, item := range i {
if item == nil || item.Data == "" {
continue
}
switch item.Type {
case ChatInputTypeTxt:
cs = append(cs, map[string]string{
"type": "text",
"text": item.Data,
})
case ChatInputTypeImg:
cs = append(cs, map[string]any{
"type": "image_url",
"image_url": map[string]string{"url": item.Data},
})
}
}
if len(cs) == 0 {
return nil
}
return &ChatMessage{
Role: "user",
Content: cs,
}
}
+34
View File
@@ -0,0 +1,34 @@
package model
// ChatMessage 表示用户、模型或工具的一条消息。
type ChatMessage struct {
Role string `json:"role"`
Content any `json:"content"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
}
// ChatContentPart 表示用户消息中的一段文字或图片。
type ChatContentPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL *ChatImageURL `json:"image_url,omitempty"`
}
// ChatImageURL 保存图片地址,也支持 base64 data URL。
type ChatImageURL struct {
URL string `json:"url"`
}
// ToolCall 表示模型请求执行的工具调用。
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function ToolFunction `json:"function"`
}
// ToolFunction 表示工具调用的函数名称和参数。
type ToolFunction struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
}
+139
View File
@@ -0,0 +1,139 @@
package provider
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strings"
"example.com/ueino/internal/opt"
"example.com/ueino/pkg/model"
)
type option struct {
baseURL string
modelName string
apiKey string
}
type ChatOption func(*option)
func ChatBaseURL(baseURL string) ChatOption {
return func(o *option) {
if _, err := url.Parse(baseURL); err == nil {
o.baseURL = strings.TrimRight(baseURL, "/")
}
}
}
func ChatModel(modelName string) ChatOption {
return func(o *option) {
if modelName != "" {
o.modelName = modelName
}
}
}
func ChatApiKey(apiKey string) ChatOption {
return func(o *option) {
o.apiKey = apiKey
}
}
func ChatApiKeyByEnv(env string) ChatOption {
return func(o *option) {
if val := os.Getenv(env); val != "" {
o.apiKey = val
}
}
}
type _chat struct {
opt *option
}
func NewChat(options ...ChatOption) *_chat {
o := &option{
modelName: "gpt-4o",
baseURL: "https://api.openai.com/v1",
apiKey: "",
}
for _, fn := range options {
fn(o)
}
return &_chat{
opt: o,
}
}
// ChatCompletion 原样发送上层组装的消息,通过通道返回文本片段。
// 流开始后的错误记录日志并关闭通道。
// 调用方应持续读取通道,提前停止时取消 ctx。
func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage) (<-chan string, error) {
if len(messages) == 0 {
return nil, fmt.Errorf("至少需要一条消息")
}
body := model.ChatCompletionRequest{Model: c.opt.modelName, Messages: messages, Stream: true}
headers := map[string]string{"Accept": "text/event-stream"}
if c.opt.apiKey != "" {
headers["Authorization"] = "Bearer " + c.opt.apiKey
}
endpoint := c.opt.baseURL + "/chat/completions"
resp, err := PostJSONResponse(ctx, endpoint, headers, body)
if err != nil {
return nil, err
}
if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
resp.Body.Close()
return nil, fmt.Errorf("模型接口未返回流式响应")
}
out := make(chan string, opt.RESPONSE_CHAN_SIZE)
go func() {
defer close(out)
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 4096), 1024*1024)
for scanner.Scan() {
data, ok := bytes.CutPrefix(scanner.Bytes(), []byte("data:"))
if !ok {
continue
}
data = bytes.TrimSpace(data)
if bytes.Equal(data, []byte("[DONE]")) {
return
}
var chunk model.ChatCompletionResponse
if err := json.Unmarshal(data, &chunk); err != nil {
log.Printf("解析模型流式响应失败: %v", err)
return
}
if len(chunk.Choices) == 0 || chunk.Choices[0].Delta.Content == "" {
continue
}
select {
case out <- chunk.Choices[0].Delta.Content:
case <-ctx.Done():
return
}
}
if ctx.Err() == nil {
log.Printf("模型响应流未正常结束: %v", scanner.Err())
}
}()
return out, nil
}
+52
View File
@@ -0,0 +1,52 @@
package provider
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// httpClient 由所有 provider 请求共用。
var httpClient = &http.Client{}
// PostJSON 发送 JSON 请求,将响应解码到 result,并检查 HTTP 状态码。
func PostJSON(ctx context.Context, endpoint string, headers map[string]string, body, result any) error {
resp, err := PostJSONResponse(ctx, endpoint, headers, body)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(result)
}
// PostJSONResponse 发送 JSON 请求并检查状态码,调用方负责关闭响应体。
func PostJSONResponse(ctx context.Context, endpoint string, headers map[string]string, body any) (*http.Response, error) {
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("接口返回 %s,读取错误信息失败: %w", resp.Status, err)
}
return nil, fmt.Errorf("接口返回 %s: %s", resp.Status, data)
}
return resp, nil
}