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)
}