feat: add weather tools to legacy and Eino chat
This commit is contained in:
1 parent
6e6171f481
commit
86e86bc9fa
18 files changed
+926
-77
No files matched your search
+15
-3
@@ -7,9 +7,12 @@ import (
|
||||
|
||||
"example.com/ueino/internal/opt"
|
||||
"example.com/ueino/pkg/memory"
|
||||
"example.com/ueino/pkg/tool"
|
||||
|
||||
"github.com/cloudwego/eino-ext/components/model/openai"
|
||||
"github.com/cloudwego/eino/adk"
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/compose"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
@@ -37,9 +40,11 @@ func New(ctx context.Context, config Config) (*Agent, error) {
|
||||
return nil, err
|
||||
}
|
||||
chatAgent, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
|
||||
Name: "terminal_chat",
|
||||
Instruction: opt.SYSTEM_PROMPT,
|
||||
Model: chat,
|
||||
Name: "terminal_chat",
|
||||
Instruction: opt.SYSTEM_PROMPT,
|
||||
Model: chat,
|
||||
MaxIterations: opt.MAX_TOOL_ROUND,
|
||||
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: []einotool.BaseTool{tool.NewWeather()}}},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -87,6 +92,13 @@ func readResponse(events *adk.AsyncIterator[*adk.AgentEvent], onChunk func(strin
|
||||
continue
|
||||
}
|
||||
output := event.Output.MessageOutput
|
||||
if output.Role != schema.Assistant {
|
||||
if output.IsStreaming {
|
||||
output.MessageStream.Close()
|
||||
}
|
||||
continue
|
||||
}
|
||||
reply.Reset()
|
||||
if !output.IsStreaming {
|
||||
onChunk(output.Message.Content)
|
||||
reply.WriteString(output.Message.Content)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
type roundTripperFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func TestChatWeatherAndHistory(t *testing.T) {
|
||||
previous := http.DefaultTransport
|
||||
var weatherCalls atomic.Int32
|
||||
http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Host != "wttr.in" {
|
||||
return previous.RoundTrip(r)
|
||||
}
|
||||
weatherCalls.Add(1)
|
||||
if r.URL.Path != "/北京" {
|
||||
t.Errorf("天气请求 = %s", r.URL)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("北京: 晴 +20°C")), Header: make(http.Header), Request: r}, nil
|
||||
})
|
||||
t.Cleanup(func() { http.DefaultTransport = previous })
|
||||
var step atomic.Int32
|
||||
requests := make(chan model.ChatCompletionRequest, 3)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var request model.ChatCompletionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
requests <- request
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
switch step.Add(1) {
|
||||
case 1:
|
||||
fmt.Fprint(w, `data: {"choices":[{"index":0,"delta":{"role":"assistant","content":"查询中","tool_calls":[{"index":0,"id":"weather-1","type":"function","function":{"name":"get_weather","arguments":"{\"location\":\"北京\"}"}}]},"finish_reason":"tool_calls"}]}
|
||||
|
||||
data: [DONE]
|
||||
|
||||
`)
|
||||
default:
|
||||
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"北京晴天\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
chat, err := New(ctx, Config{BaseURL: server.URL, Model: "test-model", APIKey: "test-key", MaxToken: 4096})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output strings.Builder
|
||||
if err := chat.Chat(ctx, "北京天气", func(text string) { output.WriteString(text) }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(output.String(), "北京晴天") || strings.Contains(output.String(), "+20°C") {
|
||||
t.Fatalf("终端输出 = %q", output.String())
|
||||
}
|
||||
if err := chat.Chat(ctx, "继续", func(string) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if step.Load() != 3 || weatherCalls.Load() != 1 {
|
||||
t.Fatalf("请求次数:模型 %d,天气 %d", step.Load(), weatherCalls.Load())
|
||||
}
|
||||
first, second, third := <-requests, <-requests, <-requests
|
||||
if len(first.Tools) != 1 || first.Tools[0].Function.Name != "get_weather" {
|
||||
t.Fatalf("工具定义 = %+v", first.Tools)
|
||||
}
|
||||
last := second.Messages[len(second.Messages)-1]
|
||||
if last.Role != "tool" || last.ToolCallID != "weather-1" || !strings.Contains(last.Content.(string), "北京: 晴 +20°C") {
|
||||
t.Fatalf("工具结果 = %+v", last)
|
||||
}
|
||||
if len(third.Messages) != 4 || third.Messages[1].Content != "北京天气" || third.Messages[2].Content != "北京晴天" || third.Messages[3].Content != "继续" {
|
||||
t.Fatalf("对话历史 = %+v", third.Messages)
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -2,9 +2,10 @@ package model
|
||||
|
||||
// ChatCompletionRequest 表示对话接口的请求参数。
|
||||
type ChatCompletionRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []ChatMessage `json:"messages"`
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
Model string `json:"model"`
|
||||
Messages []ChatMessage `json:"messages"`
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
Tools []ToolDefinition `json:"tools,omitempty"`
|
||||
}
|
||||
|
||||
// ChatCompletionResponse 表示对话接口的响应。
|
||||
|
||||
@@ -22,6 +22,7 @@ type ChatImageURL struct {
|
||||
|
||||
// ToolCall 表示模型请求执行的工具调用。
|
||||
type ToolCall struct {
|
||||
Index *int `json:"index,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Function ToolFunction `json:"function"`
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package model
|
||||
|
||||
// ToolDefinition 描述可供模型调用的工具。
|
||||
type ToolDefinition struct {
|
||||
Type string `json:"type"`
|
||||
Function ToolFunctionDefinition `json:"function"`
|
||||
}
|
||||
|
||||
// ToolFunctionDefinition 包含工具名称、用途和参数的 JSON Schema。
|
||||
type ToolFunctionDefinition struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
}
|
||||
|
||||
// WeatherArguments 指定要查询当前天气的地点。
|
||||
type WeatherArguments struct {
|
||||
Location string `json:"location"`
|
||||
}
|
||||
+6
-49
@@ -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)
|
||||
}
|
||||
@@ -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("取消后请求未结束")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Tool 提供模型可见的定义和实际执行方法。
|
||||
type Tool interface {
|
||||
Definition() model.ToolDefinition
|
||||
Execute(ctx context.Context, arguments string) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Weather 通过 wttr.in 查询当前天气。
|
||||
type Weather struct {
|
||||
client *http.Client
|
||||
baseURL string
|
||||
}
|
||||
|
||||
func NewWeather() *Weather {
|
||||
return &Weather{client: &http.Client{Timeout: 10 * time.Second}, baseURL: "https://wttr.in"}
|
||||
}
|
||||
|
||||
func (w *Weather) Definition() model.ToolDefinition {
|
||||
return model.ToolDefinition{
|
||||
Type: "function",
|
||||
Function: model.ToolFunctionDefinition{
|
||||
Name: "get_weather",
|
||||
Description: "查询指定地点的当前天气,不提供未来预报。地点可从当前对话中获取;如果未提供地点,先询问用户,不要猜测。",
|
||||
Parameters: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"location": map[string]string{"type": "string", "description": "需要查询的城市或地点,例如北京、上海"},
|
||||
},
|
||||
"required": []string{"location"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Weather) Execute(ctx context.Context, arguments string) (string, error) {
|
||||
var args model.WeatherArguments
|
||||
if err := json.Unmarshal([]byte(arguments), &args); err != nil {
|
||||
return "", fmt.Errorf("天气参数无效: %w", err)
|
||||
}
|
||||
location := strings.TrimSpace(args.Location)
|
||||
if location == "" {
|
||||
return "", fmt.Errorf("请提供要查询的地点")
|
||||
}
|
||||
query := url.Values{"format": {"3"}, "lang": {"zh"}, "m": {""}}
|
||||
endpoint := w.baseURL + "/" + url.PathEscape(location) + "?" + query.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := w.client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("天气接口返回 %s", resp.Status)
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
result := strings.TrimSpace(string(body))
|
||||
if result == "" {
|
||||
return "", fmt.Errorf("天气接口返回空结果")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// Info 提供 Eino 所需的天气工具定义。
|
||||
func (w *Weather) Info(ctx context.Context) (*schema.ToolInfo, error) {
|
||||
definition := w.Definition().Function
|
||||
return &schema.ToolInfo{
|
||||
Name: definition.Name,
|
||||
Desc: definition.Description,
|
||||
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
|
||||
"location": {Type: schema.String, Required: true, Desc: "需要查询的城市或地点,例如北京、上海"},
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// InvokableRun 直接复用天气查询,执行失败时把错误交回模型。
|
||||
func (w *Weather) InvokableRun(ctx context.Context, arguments string, _ ...einotool.Option) (string, error) {
|
||||
result, err := w.Execute(ctx, arguments)
|
||||
if err != nil {
|
||||
return "工具执行失败: " + err.Error(), nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWeatherExecute(t *testing.T) {
|
||||
location := "北京 海淀/?&"
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != http.MethodGet || r.URL.EscapedPath() != "/"+url.PathEscape(location) {
|
||||
t.Errorf("地点编码不正确: %s", r.URL)
|
||||
}
|
||||
query := r.URL.Query()
|
||||
if query.Get("format") != "3" || query.Get("lang") != "zh" || !query.Has("m") {
|
||||
t.Errorf("查询参数不正确: %v", query)
|
||||
}
|
||||
fmt.Fprint(w, "北京: 晴 +20°C\n")
|
||||
}))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.baseURL = server.URL
|
||||
got, err := weather.Execute(context.Background(), `{"location":" 北京 海淀/?& "}`)
|
||||
if err != nil || got != "北京: 晴 +20°C" {
|
||||
t.Fatalf("天气 = %q,错误 = %v", got, err)
|
||||
}
|
||||
for _, arguments := range []string{`{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`} {
|
||||
if _, err := weather.Execute(context.Background(), arguments); err == nil {
|
||||
t.Fatalf("参数 %s 应报错", arguments)
|
||||
}
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("无效参数不应请求接口,实际请求 %d 次", calls)
|
||||
}
|
||||
definition := weather.Definition()
|
||||
if definition.Type != "function" || definition.Function.Name != "get_weather" {
|
||||
t.Fatalf("工具定义不正确: %+v", definition)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeatherResponseErrors(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{name: "接口错误", status: 503, body: "unavailable"},
|
||||
{name: "空结果", status: 200, body: " \n"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(tt.status); fmt.Fprint(w, tt.body) }))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.baseURL = server.URL
|
||||
if _, err := weather.Execute(context.Background(), `{"location":"北京"}`); err == nil {
|
||||
t.Fatal("期望返回错误")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeatherCancellationAndTimeout(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.baseURL = server.URL
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := weather.Execute(ctx, `{"location":"北京"}`); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("取消错误 = %v", err)
|
||||
}
|
||||
weather.client.Timeout = 50 * time.Millisecond
|
||||
if _, err := weather.Execute(context.Background(), `{"location":"北京"}`); err == nil || !strings.Contains(err.Error(), "Client.Timeout") {
|
||||
t.Fatalf("超时错误 = %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user