feat: initialize Eino examples and ADK applications
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>
This commit is contained in:
commit
81deca8c8e
75 files changed
+7048
No files matched your search
+102
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"example.com/ueino/legacy/round"
|
||||
"example.com/ueino/pkg/memory"
|
||||
"example.com/ueino/pkg/model"
|
||||
"example.com/ueino/pkg/opt"
|
||||
"example.com/ueino/pkg/provider"
|
||||
"example.com/ueino/pkg/tool"
|
||||
)
|
||||
|
||||
var (
|
||||
baseURL string
|
||||
modelName string
|
||||
apiKeyEnv string
|
||||
maxToken int
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&baseURL, "base-url", "https://ai.loveuer.com/v1", "")
|
||||
flag.StringVar(&modelName, "model", "local-mini", "")
|
||||
flag.StringVar(&apiKeyEnv, "api-key-env", "AI_KEY", "")
|
||||
flag.IntVar(&maxToken, "max-token", 4096, "")
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
run(ctx)
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
fmt.Println()
|
||||
case <-done:
|
||||
}
|
||||
}
|
||||
|
||||
func run(ctx context.Context) {
|
||||
chat := provider.NewChat(
|
||||
provider.ChatBaseURL(baseURL),
|
||||
provider.ChatModel(modelName),
|
||||
provider.ChatApiKeyByEnv(apiKeyEnv),
|
||||
)
|
||||
|
||||
mem := memory.NewMemory(maxToken)
|
||||
tools := []tool.Tool{tool.NewWeather()}
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
fmt.Println("输入消息开始聊天,按 Ctrl+C 退出。")
|
||||
|
||||
for ctx.Err() == nil {
|
||||
fmt.Print("📝 > ")
|
||||
if !scanner.Scan() {
|
||||
break
|
||||
}
|
||||
|
||||
input := strings.TrimSpace(scanner.Text())
|
||||
if input == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
messages := []model.ChatMessage{{Role: "system", Content: opt.SYSTEM_PROMPT}}
|
||||
messages = append(messages, mem.LoadHistory()...)
|
||||
messages = append(messages, model.ChatMessage{Role: "user", Content: input})
|
||||
|
||||
fmt.Println("🤖 thinking...")
|
||||
reply, err := round.Complete(ctx, chat, messages, tools, func(chunk string) {
|
||||
fmt.Print(chunk)
|
||||
})
|
||||
fmt.Println()
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Printf("请求失败: %v", err)
|
||||
continue
|
||||
}
|
||||
if reply != "" {
|
||||
mem.Save(input, reply)
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
log.Printf("读取输入失败: %v", err)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"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 TestTerminalWeatherAndMemory(t *testing.T) {
|
||||
previousTransport := http.DefaultTransport
|
||||
weatherCalls := 0
|
||||
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||||
http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
var body string
|
||||
switch r.URL.Host {
|
||||
case "geocoding-api.open-meteo.com":
|
||||
if r.URL.Query().Get("name") != "北京" {
|
||||
t.Errorf("地点查询错误: %s", r.URL)
|
||||
}
|
||||
body = `{"results":[{"name":"北京","country":"中国","latitude":39.9,"longitude":116.4}]}`
|
||||
case "api.open-meteo.com":
|
||||
if r.URL.Query().Get("start_date") != today || r.URL.Query().Get("end_date") != today {
|
||||
t.Errorf("默认日期错误: %s", r.URL)
|
||||
}
|
||||
body = fmt.Sprintf(`{"daily":{"time":[%q],"weather_code":[0],"temperature_2m_min":[10],"temperature_2m_max":[20],"precipitation_probability_max":[0]}}`, today)
|
||||
default:
|
||||
return previousTransport.RoundTrip(r)
|
||||
}
|
||||
weatherCalls++
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||||
})
|
||||
t.Cleanup(func() { http.DefaultTransport = previousTransport })
|
||||
var step atomic.Int32
|
||||
requests := make(chan model.ChatCompletionRequest, 4)
|
||||
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\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"weather-1\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"location\\\":\\\"北京\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\ndata: [DONE]\n\n")
|
||||
case 3:
|
||||
fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"未完成\"}}]}\n\ndata: invalid-json\n\n")
|
||||
default:
|
||||
fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"北京晴天\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
stdin := os.Stdin
|
||||
originalURL, originalModel, originalKey, originalMax := baseURL, modelName, apiKeyEnv, maxToken
|
||||
reader, writer, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
if _, err := writer.WriteString("北京天气\n中断\n继续\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writer.Close()
|
||||
os.Stdin = reader
|
||||
baseURL, modelName, apiKeyEnv, maxToken = server.URL, "test-model", "TEST_WEATHER_KEY", 4096
|
||||
defer func() {
|
||||
os.Stdin = stdin
|
||||
baseURL, modelName, apiKeyEnv, maxToken = originalURL, originalModel, originalKey, originalMax
|
||||
}()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
run(ctx)
|
||||
if weatherCalls != 2 || step.Load() != 4 {
|
||||
t.Fatalf("调用次数不正确: 天气 %d,模型 %d", weatherCalls, step.Load())
|
||||
}
|
||||
first, second, third, fourth := <-requests, <-requests, <-requests, <-requests
|
||||
if len(first.Tools) != 1 || len(second.Messages) != 4 || second.Messages[2].ToolCalls[0].ID != "weather-1" || second.Messages[3].ToolCallID != "weather-1" {
|
||||
t.Fatalf("工具调用续接不正确: %+v", second)
|
||||
}
|
||||
var forecast model.WeatherForecast
|
||||
if err := json.Unmarshal([]byte(second.Messages[3].Content.(string)), &forecast); err != nil || len(forecast.Days) != 1 || forecast.Days[0].Date != today || forecast.Days[0].Condition != "晴" {
|
||||
t.Fatalf("天气结果不正确: %+v,%v", forecast, err)
|
||||
}
|
||||
for _, request := range []model.ChatCompletionRequest{third, fourth} {
|
||||
if len(request.Messages) != 4 || request.Messages[1].Content != "北京天气" || request.Messages[2].Content != "北京晴天" {
|
||||
t.Fatalf("只应保存用户问题和最终回答: %+v", request.Messages)
|
||||
}
|
||||
}
|
||||
if fourth.Messages[3].Content != "继续" {
|
||||
t.Fatalf("流失败后未继续: %+v", fourth)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package round
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"example.com/ueino/pkg/opt"
|
||||
"example.com/ueino/pkg/tool"
|
||||
)
|
||||
|
||||
// Client 只负责模型请求,不执行工具或保存记忆。
|
||||
type Client interface {
|
||||
ChatCompletion(context.Context, []model.ChatMessage, []model.ToolDefinition, func(string)) (*model.ChatMessage, error)
|
||||
}
|
||||
|
||||
// Complete 完成当前一轮的模型和工具交互,仅返回最终回答。
|
||||
func Complete(ctx context.Context, chat Client, messages []model.ChatMessage, tools []tool.Tool, onChunk func(string)) (string, error) {
|
||||
var definitions []model.ToolDefinition
|
||||
available := make(map[string]tool.Tool)
|
||||
for _, t := range tools {
|
||||
definition := t.Definition()
|
||||
definitions = append(definitions, definition)
|
||||
available[definition.Function.Name] = t
|
||||
}
|
||||
for step := 0; step < opt.MAX_TOOL_ROUND; step++ {
|
||||
assistant, err := chat.ChatCompletion(ctx, messages, definitions, onChunk)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(assistant.ToolCalls) == 0 {
|
||||
fmt.Println()
|
||||
log.Printf("[DEBUG] 无需工具调用")
|
||||
return assistant.Content.(string), nil
|
||||
}
|
||||
|
||||
if step == opt.MAX_TOOL_ROUND-1 {
|
||||
return "", fmt.Errorf("本轮已达到 %d 次模型请求上限", opt.MAX_TOOL_ROUND)
|
||||
}
|
||||
|
||||
messages = append(messages, *assistant)
|
||||
for _, call := range assistant.ToolCalls {
|
||||
fmt.Println()
|
||||
log.Printf("[DEBUG] 调用工具 %s,ID=%s,参数=%s", call.Function.Name, call.ID, call.Function.Arguments)
|
||||
result := ""
|
||||
if t, ok := available[call.Function.Name]; ok {
|
||||
result, err = t.Execute(ctx, call.Function.Arguments)
|
||||
if err != nil {
|
||||
result = "工具执行失败: " + err.Error()
|
||||
}
|
||||
} else {
|
||||
result = "工具执行失败: 未知工具 " + call.Function.Name
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
messages = append(messages, model.ChatMessage{Role: "tool", Content: result, ToolCallID: call.ID})
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("本轮已达到模型请求上限")
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package round
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"example.com/ueino/pkg/tool"
|
||||
)
|
||||
|
||||
type fakeChat struct {
|
||||
responses []model.ChatMessage
|
||||
err error
|
||||
requests []model.ChatCompletionRequest
|
||||
}
|
||||
|
||||
func (c *fakeChat) ChatCompletion(_ context.Context, messages []model.ChatMessage, tools []model.ToolDefinition, onText func(string)) (*model.ChatMessage, error) {
|
||||
c.requests = append(c.requests, model.ChatCompletionRequest{Messages: slices.Clone(messages), Tools: tools})
|
||||
if c.err != nil {
|
||||
return nil, c.err
|
||||
}
|
||||
message := c.responses[0]
|
||||
c.responses = c.responses[1:]
|
||||
if text, ok := message.Content.(string); ok && onText != nil {
|
||||
onText(text)
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
type fakeTool struct {
|
||||
arguments []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (t *fakeTool) Definition() model.ToolDefinition {
|
||||
return model.ToolDefinition{Type: "function", Function: model.ToolFunctionDefinition{Name: "get_weather"}}
|
||||
}
|
||||
func (t *fakeTool) Execute(_ context.Context, arguments string) (string, error) {
|
||||
t.arguments = append(t.arguments, arguments)
|
||||
return "天气结果", t.err
|
||||
}
|
||||
|
||||
func toolMessage(id, arguments string) model.ChatMessage {
|
||||
return model.ChatMessage{Role: "assistant", Content: "", ToolCalls: []model.ToolCall{{ID: id, Type: "function", Function: model.ToolFunction{Name: "get_weather", Arguments: arguments}}}}
|
||||
}
|
||||
func finalMessage(text string) model.ChatMessage {
|
||||
return model.ChatMessage{Role: "assistant", Content: text}
|
||||
}
|
||||
|
||||
func TestCompleteRoundTools(t *testing.T) {
|
||||
weather := &fakeTool{}
|
||||
message := toolMessage("first", `{"location":"北京"}`)
|
||||
message.ToolCalls = append(message.ToolCalls, toolMessage("second", `{"location":"上海"}`).ToolCalls...)
|
||||
chat := &fakeChat{responses: []model.ChatMessage{message, finalMessage("最终回答")}}
|
||||
|
||||
var output strings.Builder
|
||||
reply, err := Complete(context.Background(), chat, []model.ChatMessage{{Role: "user", Content: "两地天气"}}, []tool.Tool{weather}, func(text string) { output.WriteString(text) })
|
||||
if err != nil || reply != "最终回答" || output.String() != reply {
|
||||
t.Fatalf("回答 = %q,错误 = %v", reply, err)
|
||||
}
|
||||
if len(weather.arguments) != 2 || weather.arguments[0] != `{"location":"北京"}` || weather.arguments[1] != `{"location":"上海"}` {
|
||||
t.Fatalf("工具参数错误: %v", weather.arguments)
|
||||
}
|
||||
request := chat.requests[1]
|
||||
if len(request.Tools) != 1 || len(request.Messages) != 4 {
|
||||
t.Fatalf("续接请求不正确: %+v", request)
|
||||
}
|
||||
assistant := request.Messages[1]
|
||||
if assistant.Role != "assistant" || len(assistant.ToolCalls) != 2 || assistant.ToolCalls[0].ID != "first" || assistant.ToolCalls[0].Index != nil {
|
||||
t.Fatalf("模型工具调用消息不正确: %+v", assistant)
|
||||
}
|
||||
if request.Messages[2].Role != "tool" || request.Messages[2].ToolCallID != "first" || request.Messages[3].ToolCallID != "second" {
|
||||
t.Fatalf("工具结果对应关系不正确: %+v", request.Messages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteRoundToolErrors(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
tools []tool.Tool
|
||||
arguments string
|
||||
}{
|
||||
{name: "未知工具", arguments: `{}`},
|
||||
{name: "执行失败", tools: []tool.Tool{&fakeTool{err: errors.New("天气服务不可用")}}, arguments: `{}`},
|
||||
{name: "无效参数", tools: []tool.Tool{tool.NewWeather()}, arguments: `{`},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
chat := &fakeChat{responses: []model.ChatMessage{toolMessage("call-1", tt.arguments), finalMessage("无法查询")}}
|
||||
reply, err := Complete(context.Background(), chat, []model.ChatMessage{{Role: "user", Content: "天气"}}, tt.tools, func(string) {})
|
||||
if err != nil || reply != "无法查询" {
|
||||
t.Fatalf("回答 = %q,错误 = %v", reply, err)
|
||||
}
|
||||
result := chat.requests[1].Messages[2]
|
||||
if result.ToolCallID != "call-1" || !strings.Contains(result.Content.(string), "工具执行失败") {
|
||||
t.Fatalf("未回传工具错误: %+v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteRoundInterrupted(t *testing.T) {
|
||||
weather := &fakeTool{}
|
||||
chat := &fakeChat{err: io.ErrUnexpectedEOF}
|
||||
if _, err := Complete(context.Background(), chat, []model.ChatMessage{{Role: "user", Content: "天气"}}, []tool.Tool{weather}, func(string) {}); !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
t.Fatalf("流中断错误 = %v", err)
|
||||
}
|
||||
if len(weather.arguments) != 0 {
|
||||
t.Fatal("流未完成不能执行工具")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteRoundLimit(t *testing.T) {
|
||||
weather := &fakeTool{}
|
||||
chat := &fakeChat{}
|
||||
for i := 0; i < 5; i++ {
|
||||
chat.responses = append(chat.responses, toolMessage("call-1", `{}`))
|
||||
}
|
||||
if _, err := Complete(context.Background(), chat, []model.ChatMessage{{Role: "user", Content: "天气"}}, []tool.Tool{weather}, func(string) {}); err == nil {
|
||||
t.Fatal("应在五次请求后报错")
|
||||
}
|
||||
if len(chat.requests) != 5 || len(weather.arguments) != 4 {
|
||||
t.Fatalf("请求或执行次数不正确: %d / %d", len(chat.requests), len(weather.arguments))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user