commit 43fc905c82eabaf31e98b87fd2f58a7e0d76706a Author: loveuer Date: Fri Nov 13 18:55:08 2026 +0800 feat: initialize terminal chat example with streaming and memory diff --git a/AGENT.md b/AGENT.md new file mode 100644 index 0000000..544691a --- /dev/null +++ b/AGENT.md @@ -0,0 +1,15 @@ +# 项目定位 + +这是一个 example 样例项目,用于演示功能和帮助理解用法,不是生产项目。 + +## 实现原则 + +- 始终选择最简单、最直接、最容易读懂的实现,以示例能运行、意图清晰为标准。 +- 只解决当前示例的具体需求,不考虑后期扩展、长期维护或生产环境的工程化建设。 +- 不为未来可能出现的需求预留接口、增加配置或设计抽象层。 +- 不引入不必要的分层、设计模式、通用框架或依赖;能用几行代码说明的问题,就直接写清楚。 +- 优先使用直观的顺序代码和具体实现,允许少量重复,避免为了复用增加理解成本。 +- 只保留运行示例所需的配置、错误处理和验证,不添加与演示无关的基础设施。 +- 修改范围保持最小,遵循现有代码风格,不顺手重构无关内容。 + +如果有多种实现方式,优先选择代码更少、依赖更少、读者更容易理解的方案。 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4505891 --- /dev/null +++ b/go.mod @@ -0,0 +1,12 @@ +module example.com/ueino + +go 1.24.13 + +require github.com/cloudwego/eino v0.9.23 // indirect + +require ( + github.com/tidwall/gjson v1.14.4 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.1 // indirect + github.com/tidwall/sjson v1.2.5 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..77cf7d6 --- /dev/null +++ b/go.sum @@ -0,0 +1,10 @@ +github.com/cloudwego/eino v0.9.23 h1:f369x1HXckTj6SlMQccgyvKWr+QMMr2yxunqTAOAF1E= +github.com/cloudwego/eino v0.9.23/go.mod h1:OBD1mrkfkt/pJa4rkg1P0VnaMeOVl7l8IAdEqY//3IQ= +github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= diff --git a/internal/opt/const.go b/internal/opt/const.go new file mode 100644 index 0000000..250c946 --- /dev/null +++ b/internal/opt/const.go @@ -0,0 +1,8 @@ +package opt + +const SYSTEM_PROMPT = `你是一个可靠、务实的对话助手。默认使用中文,回答准确、清晰、简洁。不确定时如实说明,必要时向用户澄清。涉及代码时,优先给出简单、直接、可运行的实现。` + +const ( + MIN_TOKEN = 1024 + RESPONSE_CHAN_SIZE = 32 +) diff --git a/legacy/main.go b/legacy/main.go new file mode 100644 index 0000000..749d085 --- /dev/null +++ b/legacy/main.go @@ -0,0 +1,108 @@ +package main + +import ( + "bufio" + "context" + "flag" + "fmt" + "log" + "os" + "os/signal" + "strings" + "syscall" + + "example.com/ueino/internal/opt" + "example.com/ueino/pkg/memory" + "example.com/ueino/pkg/model" + "example.com/ueino/pkg/provider" +) + +var ( + baseURL string + modelName string + apiKeyEnv string + maxToken int +) + +func init() { + flag.StringVar(&baseURL, "base-url", "https://ai.loveuer.com/v1", "") + flag.StringVar(&modelName, "model", "local-mini", "") + flag.StringVar(&apiKeyEnv, "api-key-env", "AI_KEY", "") + flag.IntVar(&maxToken, "max-token", 4096, "") + + flag.Parse() +} + +func main() { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + + done := make(chan struct{}) + go func() { + defer close(done) + run(ctx) + }() + select { + case <-ctx.Done(): + fmt.Println() + case <-done: + } +} + +func run(ctx context.Context) { + chat := provider.NewChat( + provider.ChatBaseURL(baseURL), + provider.ChatModel(modelName), + provider.ChatApiKeyByEnv(apiKeyEnv), + ) + + mem := memory.NewMemory(maxToken) + scanner := bufio.NewScanner(os.Stdin) + fmt.Println("输入消息开始聊天,按 Ctrl+C 退出。") + + for ctx.Err() == nil { + fmt.Print("你> ") + if !scanner.Scan() { + break + } + + input := strings.TrimSpace(scanner.Text()) + if input == "" { + continue + } + + messages := []model.ChatMessage{{Role: "system", Content: opt.SYSTEM_PROMPT}} + messages = append(messages, mem.LoadHistory()...) + messages = append(messages, model.ChatMessage{Role: "user", Content: input}) + + stream, err := chat.ChatCompletion(ctx, messages) + if err != nil { + if ctx.Err() != nil { + return + } + log.Printf("请求失败: %v", err) + continue + } + + fmt.Print("助手> ") + var reply strings.Builder + + for chunk := range stream { + fmt.Print(chunk) + reply.WriteString(chunk) + } + fmt.Println() + + if ctx.Err() != nil { + return + } + + if reply.Len() > 0 { + mem.Save(input, reply.String()) + } + } + if err := scanner.Err(); err != nil { + log.Printf("读取输入失败: %v", err) + } + +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..1edbced --- /dev/null +++ b/main.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("hello eino") +} diff --git a/pkg/memory/memory.go b/pkg/memory/memory.go new file mode 100644 index 0000000..8a36e7a --- /dev/null +++ b/pkg/memory/memory.go @@ -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") +} diff --git a/pkg/memory/memory_test.go b/pkg/memory/memory_test.go new file mode 100644 index 0000000..30b62b0 --- /dev/null +++ b/pkg/memory/memory_test.go @@ -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) + } +} diff --git a/pkg/model/chat.go b/pkg/model/chat.go new file mode 100644 index 0000000..0060009 --- /dev/null +++ b/pkg/model/chat.go @@ -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"` +} diff --git a/pkg/model/input.go b/pkg/model/input.go new file mode 100644 index 0000000..f34cb35 --- /dev/null +++ b/pkg/model/input.go @@ -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, + } +} diff --git a/pkg/model/message.go b/pkg/model/message.go new file mode 100644 index 0000000..d1f1d46 --- /dev/null +++ b/pkg/model/message.go @@ -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"` +} diff --git a/pkg/provider/chat.go b/pkg/provider/chat.go new file mode 100644 index 0000000..cfe2004 --- /dev/null +++ b/pkg/provider/chat.go @@ -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 +} diff --git a/pkg/provider/client.go b/pkg/provider/client.go new file mode 100644 index 0000000..dfa6a52 --- /dev/null +++ b/pkg/provider/client.go @@ -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 +}