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>
103 lines
2.6 KiB
Go
103 lines
2.6 KiB
Go
package provider
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"strings"
|
|
|
|
"example.com/ueino/pkg/model"
|
|
)
|
|
|
|
// readStream 合并文字和工具调用片段,完整接收后才返回消息。
|
|
func readStream(ctx context.Context, reader io.Reader, onText func(string)) (*model.ChatMessage, error) {
|
|
var text strings.Builder
|
|
calls := make(map[int]*model.ToolCall)
|
|
reason := ""
|
|
done := false
|
|
scanner := bufio.NewScanner(reader)
|
|
scanner.Buffer(make([]byte, 4096), 1024*1024)
|
|
for scanner.Scan() {
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
data, ok := bytes.CutPrefix(scanner.Bytes(), []byte("data:"))
|
|
if !ok {
|
|
continue
|
|
}
|
|
data = bytes.TrimSpace(data)
|
|
if bytes.Equal(data, []byte("[DONE]")) {
|
|
done = true
|
|
break
|
|
}
|
|
var chunk model.ChatCompletionResponse
|
|
if err := json.Unmarshal(data, &chunk); err != nil {
|
|
return nil, fmt.Errorf("解析模型流式响应失败: %w", err)
|
|
}
|
|
if len(chunk.Choices) == 0 {
|
|
continue
|
|
}
|
|
choice := chunk.Choices[0]
|
|
if choice.Delta.Content != "" {
|
|
text.WriteString(choice.Delta.Content)
|
|
if onText != nil {
|
|
onText(choice.Delta.Content)
|
|
}
|
|
}
|
|
if choice.FinishReason != "" {
|
|
reason = choice.FinishReason
|
|
}
|
|
|
|
for _, delta := range choice.Delta.ToolCalls {
|
|
if delta.Index == nil || *delta.Index < 0 {
|
|
return nil, fmt.Errorf("工具调用缺少有效的 index")
|
|
}
|
|
index := *delta.Index
|
|
call := calls[index]
|
|
if call == nil {
|
|
call = &model.ToolCall{}
|
|
calls[index] = call
|
|
}
|
|
call.ID += delta.ID
|
|
if delta.Type != "" {
|
|
call.Type = delta.Type
|
|
}
|
|
call.Function.Name += delta.Function.Name
|
|
call.Function.Arguments += delta.Function.Arguments
|
|
}
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := scanner.Err(); err != nil {
|
|
return nil, fmt.Errorf("读取模型响应失败: %w", err)
|
|
}
|
|
if !done {
|
|
return nil, io.ErrUnexpectedEOF
|
|
}
|
|
assistant := model.ChatMessage{Role: "assistant", Content: text.String()}
|
|
indices := make([]int, 0, len(calls))
|
|
for index := range calls {
|
|
indices = append(indices, index)
|
|
}
|
|
sort.Ints(indices)
|
|
for _, index := range indices {
|
|
call := calls[index]
|
|
if call.ID == "" || call.Function.Name == "" || call.Type != "function" {
|
|
return nil, fmt.Errorf("工具调用信息不完整")
|
|
}
|
|
assistant.ToolCalls = append(assistant.ToolCalls, *call)
|
|
}
|
|
if len(assistant.ToolCalls) == 0 && reason != "stop" {
|
|
return nil, fmt.Errorf("模型未正常完成回答: %s", reason)
|
|
}
|
|
if len(assistant.ToolCalls) > 0 && reason != "tool_calls" {
|
|
return nil, fmt.Errorf("工具调用未正常完成: %s", reason)
|
|
}
|
|
return &assistant, nil
|
|
}
|