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

+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"`
}