feat: add weather tools to legacy and Eino chat

This commit is contained in:
loveuer committed 2026-11-16 19:08:18 +08:00
1 parent 6e6171f481
commit 86e86bc9fa
18 files changed
+926 -77

No files matched your search

+6 -49
View File
@@ -1,17 +1,12 @@
package provider
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strings"
"example.com/ueino/internal/opt"
"example.com/ueino/pkg/model"
)
@@ -73,15 +68,13 @@ func NewChat(options ...ChatOption) *_chat {
}
}
// ChatCompletion 原样发送上层组装的消息,通过通道返回文本片段。
// 流开始后的错误记录日志并关闭通道。
// 调用方应持续读取通道,提前停止时取消 ctx。
func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage) (<-chan string, error) {
// ChatCompletion 通过回调输出文字,完整接收后返回助手消息;失败时直接返回错误。
func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage, tools []model.ToolDefinition, onText func(string)) (*model.ChatMessage, error) {
if len(messages) == 0 {
return nil, fmt.Errorf("至少需要一条消息")
}
body := model.ChatCompletionRequest{Model: c.opt.modelName, Messages: messages, Stream: true}
body := model.ChatCompletionRequest{Model: c.opt.modelName, Messages: messages, Stream: true, Tools: tools}
headers := map[string]string{"Accept": "text/event-stream"}
if c.opt.apiKey != "" {
headers["Authorization"] = "Bearer " + c.opt.apiKey
@@ -93,47 +86,11 @@ func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage
return nil, err
}
defer resp.Body.Close()
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
return readStream(ctx, resp.Body, onText)
}
+124
View File
@@ -0,0 +1,124 @@
package provider
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"example.com/ueino/pkg/model"
)
func TestChatCompletionTools(t *testing.T) {
t.Setenv("CHAT_TEST_KEY", "local-key")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/chat/completions" || r.Header.Get("Authorization") != "Bearer local-key" {
t.Errorf("请求不正确: %s", r.URL)
}
var request model.ChatCompletionRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Error(err)
}
if !request.Stream || request.Model != "test-model" || len(request.Tools) != 1 || request.Tools[0].Function.Name != "get_weather" {
t.Errorf("请求参数不正确: %+v", request)
}
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, `: heartbeat
data: {"choices":[{"delta":{"content":"查询中","tool_calls":[{"index":0,"id":"call-1","type":"function","function":{"name":"get_weather","arguments":"{\"location\":"}}]}}]}
data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"北京\"}"}}]},"finish_reason":"tool_calls"}]}
data: {"choices":[]}
data: [DONE]
`)
}))
defer server.Close()
chat := NewChat(ChatBaseURL(server.URL+"/v1/"), ChatModel("test-model"), ChatApiKeyByEnv("CHAT_TEST_KEY"))
var output strings.Builder
message, err := chat.ChatCompletion(context.Background(), []model.ChatMessage{{Role: "user", Content: "北京天气"}}, []model.ToolDefinition{{Type: "function", Function: model.ToolFunctionDefinition{Name: "get_weather"}}}, func(text string) { output.WriteString(text) })
if err != nil {
t.Fatal(err)
}
if message.Role != "assistant" || message.Content != "查询中" || output.String() != "查询中" || len(message.ToolCalls) != 1 {
t.Fatalf("助手消息不正确: %+v", message)
}
call := message.ToolCalls[0]
if call.ID != "call-1" || call.Index != nil || call.Function.Name != "get_weather" || call.Function.Arguments != `{"location":"北京"}` {
t.Fatalf("工具调用不正确: %+v", call)
}
}
func TestChatCompletionStreamErrors(t *testing.T) {
for _, tt := range []struct {
name, body string
wantUnexpected bool
}{
{name: "无效JSON", body: "data: invalid-json\n\n"},
{name: "缺少完成标记", body: "data: {\"choices\":[{\"delta\":{\"content\":\"部分回答\"}}]}\n\n", wantUnexpected: true},
} {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, tt.body)
}))
defer server.Close()
chat := NewChat(ChatBaseURL(server.URL))
message, err := chat.ChatCompletion(context.Background(), []model.ChatMessage{{Role: "user", Content: "你好"}}, nil, nil)
if message != nil || err == nil || (tt.wantUnexpected && !errors.Is(err, io.ErrUnexpectedEOF)) {
t.Fatalf("消息 = %+v,流错误 = %v", message, err)
}
})
}
}
func TestChatCompletionHTTPError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400); fmt.Fprint(w, "参数错误") }))
defer server.Close()
chat := NewChat(ChatBaseURL(server.URL))
if _, err := chat.ChatCompletion(context.Background(), nil, nil, nil); err == nil {
t.Fatal("空消息应报错")
}
if _, err := chat.ChatCompletion(context.Background(), []model.ChatMessage{{Role: "user", Content: "你好"}}, nil, nil); err == nil || !strings.Contains(err.Error(), "400") {
t.Fatalf("请求错误 = %v", err)
}
}
func TestChatCompletionCancel(t *testing.T) {
started := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
w.(http.Flusher).Flush()
close(started)
<-r.Context().Done()
}))
defer server.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
result := make(chan error, 1)
go func() {
_, err := NewChat(ChatBaseURL(server.URL)).ChatCompletion(ctx, []model.ChatMessage{{Role: "user", Content: "你好"}}, nil, nil)
result <- err
}()
<-started
cancel()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("取消错误 = %v", err)
}
case <-time.After(time.Second):
t.Fatal("取消后请求未结束")
}
}
+102
View File
@@ -0,0 +1,102 @@
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
}
+70
View File
@@ -0,0 +1,70 @@
package provider
import (
"context"
"fmt"
"io"
"strings"
"testing"
)
func TestReadStreamInterleavedTools(t *testing.T) {
body := `data: {"choices":[{"delta":{"tool_calls":[{"index":1,"id":"second","type":"function","function":{"name":"get_","arguments":"{\"location\":\"上"}},{"index":0,"id":"first","type":"function","function":{"name":"get_weather","arguments":"{\"location\":\"北"}}]}}]}
data: {"choices":[{"delta":{"tool_calls":[{"index":1,"function":{"name":"weather","arguments":"海\"}"}},{"index":0,"function":{"arguments":"京\"}"}}]},"finish_reason":"tool_calls"}]}
data: [DONE]
`
message, err := readStream(context.Background(), strings.NewReader(body), nil)
if err != nil {
t.Fatal(err)
}
if len(message.ToolCalls) != 2 {
t.Fatalf("工具调用 = %+v", message.ToolCalls)
}
for i, want := range []struct{ id, args string }{{"first", `{"location":"北京"}`}, {"second", `{"location":"上海"}`}} {
call := message.ToolCalls[i]
if call.ID != want.id || call.Index != nil || call.Function.Name != "get_weather" || call.Function.Arguments != want.args {
t.Fatalf("工具调用 = %+v", call)
}
}
}
func TestReadStreamInvalidCompletion(t *testing.T) {
for _, choice := range []string{
`{"delta":{"tool_calls":[{"id":"call-1"}]},"finish_reason":"tool_calls"}`,
`{"delta":{"tool_calls":[{"index":-1}]},"finish_reason":"tool_calls"}`,
`{"delta":{"tool_calls":[{"index":0,"type":"function","function":{"name":"get_weather"}}]},"finish_reason":"tool_calls"}`,
`{"delta":{"tool_calls":[{"index":0,"id":"call-1","type":"function","function":{"name":"get_weather"}}]},"finish_reason":"stop"}`,
`{"delta":{},"finish_reason":"tool_calls"}`,
`{"delta":{"content":"部分回答"},"finish_reason":"length"}`,
`{"delta":{"content":"部分回答"}}`,
} {
body := "data: {\"choices\":[" + choice + "]}\n\ndata: [DONE]\n"
if message, err := readStream(context.Background(), strings.NewReader(body), nil); message != nil || err == nil {
t.Fatalf("异常响应应报错: %s, %+v, %v", choice, message, err)
}
}
}
func TestReadStreamLiveText(t *testing.T) {
reader, writer := io.Pipe()
defer reader.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
defer writer.Close()
fmt.Fprint(writer, "data: {\"choices\":[{\"delta\":{\"content\":\"你好\"}}]}\n")
// 等回调收到文字再发送结尾,证明回调不需要等待整个响应结束。
<-ctx.Done()
fmt.Fprint(writer, "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\ndata: [DONE]\n")
}()
// 使用独立上下文,cancel 只用于通知写入方。
message, err := readStream(context.Background(), reader, func(text string) {
if text != "你好" {
t.Errorf("文字 = %q", text)
}
cancel()
})
if err != nil || message.Content != "你好" {
t.Fatalf("消息 = %+v,错误 = %v", message, err)
}
}