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
@@ -0,0 +1,23 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/cloudwego/eino-ext/components/model/openai"
|
||||
)
|
||||
|
||||
func MustNewChatModel(ctx context.Context, model string) *openai.ChatModel {
|
||||
chat, err := openai.NewChatModel(ctx, &openai.ChatModelConfig{
|
||||
APIKey: os.Getenv("AI_KEY"),
|
||||
BaseURL: "https://ai.loveuer.com/v1",
|
||||
Model: model,
|
||||
ReasoningEffort: openai.ReasoningEffortLevelLow,
|
||||
})
|
||||
if err != nil {
|
||||
log.Panicf("new openai chat model failed: %v", err)
|
||||
}
|
||||
|
||||
return chat
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Memory 保存一个会话的历史和摘要。
|
||||
type Memory struct {
|
||||
maxToken int
|
||||
history []model.ChatMessage
|
||||
summary []string
|
||||
summarized int
|
||||
}
|
||||
|
||||
// NewMemory 设置历史和摘要共用的预算,按 UTF-8 字节数加消息开销保守估算。
|
||||
// 预算小于等于 0 时不保存记忆。
|
||||
func NewMemory(maxToken int) *Memory {
|
||||
return &Memory{
|
||||
maxToken: maxToken,
|
||||
}
|
||||
}
|
||||
|
||||
// Save 在工具调用和流式输出结束后保存一轮完整对话。
|
||||
func (m *Memory) Save(req, res string) {
|
||||
if m.maxToken <= 0 {
|
||||
return
|
||||
}
|
||||
m.history = append(m.history,
|
||||
model.ChatMessage{Role: "user", Content: req},
|
||||
model.ChatMessage{Role: "assistant", Content: res},
|
||||
)
|
||||
if len(m.history)/2-m.summarized >= 10 {
|
||||
for i := m.summarized * 2; i < len(m.history); i += 2 {
|
||||
m.summary = append(m.summary, m.history[i].Content.(string))
|
||||
}
|
||||
m.summarized = len(m.history) / 2
|
||||
}
|
||||
|
||||
size := 0
|
||||
for _, message := range m.history {
|
||||
size += len(message.Content.(string)) + 4
|
||||
}
|
||||
for _, input := range m.summary {
|
||||
size += len(input) + len("\n---\n")
|
||||
}
|
||||
// 按完整条目淘汰,先删除最旧的摘要,再删除最旧的历史。
|
||||
for size > m.maxToken && len(m.summary) > 0 {
|
||||
size -= len(m.summary[0]) + len("\n---\n")
|
||||
m.summary = slices.Delete(m.summary, 0, 1)
|
||||
}
|
||||
for size > m.maxToken && len(m.history) > 0 {
|
||||
size -= len(m.history[0].Content.(string)) + len(m.history[1].Content.(string)) + 8
|
||||
m.history = slices.Delete(m.history, 0, 2)
|
||||
if m.summarized > 0 {
|
||||
m.summarized--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LoadHistory 按用户、模型顺序返回最近 N 轮消息,默认返回 10 轮(20 条)。
|
||||
// N 小于等于 0 时返回空历史;只使用 maxRound 的第一个值。
|
||||
func (m *Memory) LoadHistory(maxRound ...int) []model.ChatMessage {
|
||||
limit := 10
|
||||
if len(maxRound) > 0 {
|
||||
limit = maxRound[0]
|
||||
}
|
||||
if limit <= 0 {
|
||||
return nil
|
||||
}
|
||||
start := 0
|
||||
if limit < len(m.history)/2 {
|
||||
start = len(m.history) - limit*2
|
||||
}
|
||||
return slices.Clone(m.history[start:])
|
||||
}
|
||||
|
||||
// LoadSummary 返回每 10 轮归档的用户输入,用于嵌入系统提示词。
|
||||
func (m *Memory) LoadSummary() string {
|
||||
return strings.Join(m.summary, "\n---\n")
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadHistoryMessages(t *testing.T) {
|
||||
m := NewMemory(4096)
|
||||
for i := 0; i < 12; i++ {
|
||||
m.Save(fmt.Sprintf("问题%d", i), fmt.Sprintf("回答%d", i))
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
limit []int
|
||||
rounds int
|
||||
}{
|
||||
{name: "默认十轮", rounds: 10},
|
||||
{name: "最近两轮", limit: []int{2}, rounds: 2},
|
||||
{name: "全部历史", limit: []int{100}, rounds: 12},
|
||||
{name: "零轮", limit: []int{0}},
|
||||
{name: "负数轮", limit: []int{-1}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
messages := m.LoadHistory(tt.limit...)
|
||||
if len(messages) != tt.rounds*2 {
|
||||
t.Fatalf("消息数 = %d,期望 %d", len(messages), tt.rounds*2)
|
||||
}
|
||||
for i := 0; i < tt.rounds; i++ {
|
||||
round := 12 - tt.rounds + i
|
||||
if messages[i*2].Role != "user" || messages[i*2].Content != fmt.Sprintf("问题%d", round) || messages[i*2+1].Role != "assistant" || messages[i*2+1].Content != fmt.Sprintf("回答%d", round) {
|
||||
t.Fatalf("第 %d 轮消息内容或顺序不正确: %+v", round, messages[i*2:i*2+2])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
messages := m.LoadHistory(1)
|
||||
messages[0].Content = "修改"
|
||||
if m.LoadHistory(1)[0].Content != "问题11" {
|
||||
t.Fatal("修改返回消息不应影响保存的历史")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryBudget(t *testing.T) {
|
||||
for _, budget := range []int{0, -1, 40, 200, 1000} {
|
||||
t.Run(fmt.Sprint(budget), func(t *testing.T) {
|
||||
m := NewMemory(budget)
|
||||
for i := 0; i < 1000; i++ {
|
||||
m.Save(fmt.Sprintf("问题%d", i), "回答")
|
||||
size := len(m.LoadSummary())
|
||||
for _, message := range m.LoadHistory(10000) {
|
||||
size += len(message.Content.(string)) + 4
|
||||
}
|
||||
if size > max(budget, 0) {
|
||||
t.Fatalf("memory size %d exceeds budget %d", size, budget)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryDropsOversizedRound(t *testing.T) {
|
||||
m := NewMemory(40)
|
||||
m.Save("old", "reply")
|
||||
m.Save(strings.Repeat("中", 100), "reply")
|
||||
if len(m.LoadHistory()) != 0 || m.LoadSummary() != "" {
|
||||
t.Fatal("oversized round should be dropped")
|
||||
}
|
||||
m.Save("new", "reply")
|
||||
if got := m.LoadHistory(); len(got) != 2 || got[0].Role != "user" || got[0].Content != "new" || got[1].Role != "assistant" || got[1].Content != "reply" {
|
||||
t.Fatalf("memory did not recover: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryEmptyRoundsAreBounded(t *testing.T) {
|
||||
m := NewMemory(80)
|
||||
for i := 0; i < 1000; i++ {
|
||||
m.Save("", "")
|
||||
}
|
||||
if len(m.LoadHistory(10000)) > 20 {
|
||||
t.Fatal("empty history grows without bound")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummaryAfterHistoryEviction(t *testing.T) {
|
||||
m := NewMemory(200)
|
||||
for i := 0; i < 10; i++ {
|
||||
m.Save(fmt.Sprint(i), "")
|
||||
}
|
||||
m.Save(strings.Repeat("x", 201), "")
|
||||
for i := 10; i < 20; i++ {
|
||||
m.Save(fmt.Sprint(i), "")
|
||||
}
|
||||
want := make([]string, 10)
|
||||
for i := range want {
|
||||
want[i] = fmt.Sprint(i + 10)
|
||||
}
|
||||
if got := m.LoadSummary(); got != strings.Join(want, "\n---\n") {
|
||||
t.Fatalf("summary after eviction = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package model
|
||||
|
||||
// ASREvent 只包含实时转写接口使用的事件字段。
|
||||
type ASREvent struct {
|
||||
Type string `json:"type"`
|
||||
ItemID string `json:"item_id,omitempty"`
|
||||
Delta string `json:"delta,omitempty"`
|
||||
Transcript string `json:"transcript,omitempty"`
|
||||
Audio string `json:"audio,omitempty"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ASRSessionUpdate 配置中文、单声道 PCM 输入和手动提交。
|
||||
type ASRSessionUpdate struct {
|
||||
Type string `json:"type"`
|
||||
Session ASRSession `json:"session"`
|
||||
}
|
||||
|
||||
type ASRSession struct {
|
||||
Type string `json:"type"`
|
||||
Audio struct {
|
||||
Input struct {
|
||||
Format struct {
|
||||
Type string `json:"type"`
|
||||
Rate int `json:"rate"`
|
||||
} `json:"format"`
|
||||
Transcription struct {
|
||||
Model string `json:"model"`
|
||||
Language string `json:"language"`
|
||||
} `json:"transcription"`
|
||||
TurnDetection any `json:"turn_detection"`
|
||||
} `json:"input"`
|
||||
} `json:"audio"`
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package model
|
||||
|
||||
// ChatCompletionRequest 表示对话接口的请求参数。
|
||||
type ChatCompletionRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []ChatMessage `json:"messages"`
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
Tools []ToolDefinition `json:"tools,omitempty"`
|
||||
}
|
||||
|
||||
// ChatCompletionResponse 表示对话接口的响应。
|
||||
type ChatCompletionResponse struct {
|
||||
Choices []ChatCompletionChoice `json:"choices"`
|
||||
}
|
||||
|
||||
// ChatCompletionChoice 表示模型返回的一个候选回答。
|
||||
type ChatCompletionChoice struct {
|
||||
Message ChatMessage `json:"message"`
|
||||
Delta ChatCompletionDelta `json:"delta"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
}
|
||||
|
||||
// ChatCompletionDelta 表示流式响应中的增量内容。
|
||||
type ChatCompletionDelta struct {
|
||||
Content string `json:"content"`
|
||||
ToolCalls []ToolCall `json:"tool_calls"`
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package model
|
||||
|
||||
// ImageGenerationRequest 是 OpenAI 兼容图片接口的请求。
|
||||
type ImageGenerationRequest struct {
|
||||
Model string `json:"model"`
|
||||
Prompt string `json:"prompt"`
|
||||
N int `json:"n"`
|
||||
}
|
||||
|
||||
type ImageGenerationResponse struct {
|
||||
Data []ImageGenerationData `json:"data"`
|
||||
}
|
||||
|
||||
type ImageGenerationData struct {
|
||||
Base64 string `json:"b64_json"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// ImageArguments 是生图工具接收的创作提示词。
|
||||
type ImageArguments struct {
|
||||
Prompt string `json:"prompt"`
|
||||
}
|
||||
|
||||
// ImageResult 返回已经保存到本地的图片路径。
|
||||
type ImageResult struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package model
|
||||
|
||||
import "strings"
|
||||
|
||||
type ChatInputType string
|
||||
|
||||
const (
|
||||
ChatInputTypeTxt ChatInputType = "text"
|
||||
ChatInputTypeImg ChatInputType = "image"
|
||||
)
|
||||
|
||||
type ChatInput struct {
|
||||
Type ChatInputType
|
||||
// 文字为原文,图片为图片地址或 base64 data URL。
|
||||
Data string
|
||||
}
|
||||
|
||||
type ChatInputs []*ChatInput
|
||||
|
||||
// Text 返回用于保存历史的文字,图片用占位文字表示。
|
||||
func (i ChatInputs) Text() string {
|
||||
var texts []string
|
||||
for _, input := range i {
|
||||
if input == nil {
|
||||
continue
|
||||
}
|
||||
switch input.Type {
|
||||
case ChatInputTypeTxt:
|
||||
texts = append(texts, input.Data)
|
||||
case ChatInputTypeImg:
|
||||
texts = append(texts, "[图片]")
|
||||
}
|
||||
}
|
||||
return strings.Join(texts, "\n")
|
||||
}
|
||||
|
||||
func (i ChatInputs) Format() *ChatMessage {
|
||||
if len(i) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
cs := make([]any, 0)
|
||||
|
||||
for _, item := range i {
|
||||
if item == nil || item.Data == "" {
|
||||
continue
|
||||
}
|
||||
switch item.Type {
|
||||
case ChatInputTypeTxt:
|
||||
cs = append(cs, map[string]string{
|
||||
"type": "text",
|
||||
"text": item.Data,
|
||||
})
|
||||
case ChatInputTypeImg:
|
||||
cs = append(cs, map[string]any{
|
||||
"type": "image_url",
|
||||
"image_url": map[string]string{"url": item.Data},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(cs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &ChatMessage{
|
||||
Role: "user",
|
||||
Content: cs,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package model
|
||||
|
||||
// ChatMessage 表示用户、模型或工具的一条消息。
|
||||
type ChatMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content"`
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
}
|
||||
|
||||
// ChatContentPart 表示用户消息中的一段文字或图片。
|
||||
type ChatContentPart struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL *ChatImageURL `json:"image_url,omitempty"`
|
||||
}
|
||||
|
||||
// ChatImageURL 保存图片地址,也支持 base64 data URL。
|
||||
type ChatImageURL struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// ToolCall 表示模型请求执行的工具调用。
|
||||
type ToolCall struct {
|
||||
Index *int `json:"index,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Function ToolFunction `json:"function"`
|
||||
}
|
||||
|
||||
// ToolFunction 表示工具调用的函数名称和参数。
|
||||
type ToolFunction struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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"`
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package model
|
||||
|
||||
// TravelRequest 是主助手提取的出行需求,日期使用北京时间。
|
||||
type TravelRequest struct {
|
||||
Location string `json:"location"`
|
||||
StartDate string `json:"start_date"`
|
||||
EndDate string `json:"end_date,omitempty"`
|
||||
Requirements string `json:"requirements,omitempty"`
|
||||
}
|
||||
|
||||
// TravelGuide 在 Graph 节点之间传递天气、行程和图片结果。
|
||||
type TravelGuide struct {
|
||||
Request TravelRequest `json:"request"`
|
||||
Weather WeatherForecast `json:"weather"`
|
||||
Plan string `json:"plan,omitempty"`
|
||||
ImagePrompt string `json:"image_prompt,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Problem string `json:"problem,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package model
|
||||
|
||||
// WeatherArguments 指定地点,以及可选的预报日期范围。
|
||||
type WeatherArguments struct {
|
||||
Location string `json:"location"`
|
||||
StartDate string `json:"start_date,omitempty"`
|
||||
EndDate string `json:"end_date,omitempty"`
|
||||
}
|
||||
|
||||
// WeatherLocations 是 Open-Meteo 的城市搜索结果,使用首个匹配项。
|
||||
type WeatherLocations struct {
|
||||
Results []struct {
|
||||
Name string `json:"name"`
|
||||
Admin1 string `json:"admin1"`
|
||||
Country string `json:"country"`
|
||||
Latitude float64 `json:"latitude"`
|
||||
Longitude float64 `json:"longitude"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
// WeatherDailyResponse 只保留本示例使用的逐日预报字段。
|
||||
type WeatherDailyResponse struct {
|
||||
Daily struct {
|
||||
Dates []string `json:"time"`
|
||||
Codes []*int `json:"weather_code"`
|
||||
MaxTemps []*float64 `json:"temperature_2m_max"`
|
||||
MinTemps []*float64 `json:"temperature_2m_min"`
|
||||
RainChances []*float64 `json:"precipitation_probability_max"`
|
||||
} `json:"daily"`
|
||||
}
|
||||
|
||||
// WeatherForecast 向模型返回实际匹配地点和指定日期的预报。
|
||||
type WeatherForecast struct {
|
||||
Location string `json:"location"`
|
||||
Timezone string `json:"timezone"`
|
||||
Days []WeatherDay `json:"days"`
|
||||
}
|
||||
|
||||
type WeatherDay struct {
|
||||
Date string `json:"date"`
|
||||
Condition string `json:"condition"`
|
||||
MinTemperatureC float64 `json:"min_temperature_c"`
|
||||
MaxTemperatureC float64 `json:"max_temperature_c"`
|
||||
PrecipitationChancePct float64 `json:"precipitation_probability_max_pct"`
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package opt
|
||||
|
||||
const SYSTEM_PROMPT = `你是一个可靠、务实的对话助手。默认使用中文,回答准确、清晰、简洁。不确定时如实说明,必要时向用户澄清。涉及代码时,优先给出简单、直接、可运行的实现。`
|
||||
|
||||
const (
|
||||
MIN_TOKEN = 1024
|
||||
MAX_TOOL_ROUND = 5
|
||||
)
|
||||
@@ -0,0 +1,152 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// ASR 调用 OpenAI Realtime 的纯转写接口。
|
||||
type ASR struct {
|
||||
BaseURL string
|
||||
Model string
|
||||
APIKey string
|
||||
}
|
||||
|
||||
// Transcribe 读取最长 15 秒的 PCM 流,临时文字回调展示,最终文字单独返回。
|
||||
// audio 如果实现 io.Closer,结束或取消时会关闭它,以解除正在等待的音频读取。
|
||||
func (a *ASR) Transcribe(ctx context.Context, audio io.Reader, onDelta func(string)) (string, error) {
|
||||
return a.transcribe(ctx, audio, onDelta, 30*time.Second)
|
||||
}
|
||||
|
||||
func (a *ASR) transcribe(ctx context.Context, audio io.Reader, onDelta func(string), timeout time.Duration) (string, error) {
|
||||
endpoint, err := url.Parse(strings.TrimRight(a.BaseURL, "/") + "/realtime")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
query := endpoint.Query()
|
||||
query.Set("model", a.Model)
|
||||
endpoint.RawQuery = query.Encode()
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: timeout,
|
||||
Subprotocols: []string{"realtime", "openai-insecure-api-key." + a.APIKey},
|
||||
}
|
||||
conn, resp, err := dialer.DialContext(ctx, endpoint.String(), nil)
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
return "", fmt.Errorf("连接语音识别服务失败: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
stop := context.AfterFunc(runCtx, func() {
|
||||
conn.Close()
|
||||
if closer, ok := audio.(io.Closer); ok {
|
||||
closer.Close()
|
||||
}
|
||||
})
|
||||
defer stop()
|
||||
// 返回时也关闭输入,确保发送协程不会留在 Read 中。
|
||||
if closer, ok := audio.(io.Closer); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
sendErr := make(chan error, 1)
|
||||
started := false
|
||||
for {
|
||||
var event model.ASREvent
|
||||
if err := conn.ReadJSON(&event); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
select {
|
||||
case err := <-sendErr:
|
||||
return "", err
|
||||
default:
|
||||
return "", fmt.Errorf("读取语音识别结果失败: %w", err)
|
||||
}
|
||||
}
|
||||
switch event.Type {
|
||||
case "session.created":
|
||||
update := model.ASRSessionUpdate{Type: "session.update"}
|
||||
update.Session.Type = "transcription"
|
||||
input := &update.Session.Audio.Input
|
||||
input.Format.Type, input.Format.Rate = "audio/pcm", 24000
|
||||
input.Transcription.Model, input.Transcription.Language = a.Model, "zh"
|
||||
conn.SetWriteDeadline(time.Now().Add(timeout))
|
||||
if err := conn.WriteJSON(update); err != nil {
|
||||
return "", err
|
||||
}
|
||||
case "session.updated":
|
||||
if started {
|
||||
continue
|
||||
}
|
||||
started = true
|
||||
// 初始化完成后取消读超时,提交时再设置最终结果的等待时间。
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
go func() {
|
||||
if err := sendAudio(runCtx, conn, audio, timeout); err != nil {
|
||||
sendErr <- err
|
||||
conn.Close()
|
||||
}
|
||||
}()
|
||||
case "conversation.item.input_audio_transcription.delta":
|
||||
if onDelta != nil {
|
||||
onDelta(event.Delta)
|
||||
}
|
||||
case "conversation.item.input_audio_transcription.completed":
|
||||
return strings.TrimSpace(event.Transcript), nil
|
||||
case "error", "conversation.item.input_audio_transcription.failed":
|
||||
if event.Error != nil {
|
||||
return "", fmt.Errorf("语音识别失败: %s", event.Error.Message)
|
||||
}
|
||||
return "", fmt.Errorf("语音识别失败: %s", event.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sendAudio(ctx context.Context, conn *websocket.Conn, audio io.Reader, timeout time.Duration) error {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
buffer := make([]byte, 4800)
|
||||
total := 0
|
||||
// 即使调用方提供更长音频,也不跨过服务端的 20 秒自动分段边界。
|
||||
audio = io.LimitReader(audio, 15*48000)
|
||||
for {
|
||||
n, err := io.ReadFull(audio, buffer)
|
||||
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
|
||||
return fmt.Errorf("读取录音失败: %w", err)
|
||||
}
|
||||
n -= n % 2
|
||||
if n > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
conn.SetWriteDeadline(time.Now().Add(timeout))
|
||||
if err := conn.WriteJSON(model.ASREvent{Type: "input_audio_buffer.append", Audio: base64.StdEncoding.EncodeToString(buffer[:n])}); err != nil {
|
||||
return fmt.Errorf("发送录音失败: %w", err)
|
||||
}
|
||||
total += n
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if total < 4800 {
|
||||
return fmt.Errorf("录音不足 100ms,请重新录音")
|
||||
}
|
||||
conn.UnderlyingConn().SetReadDeadline(time.Now().Add(timeout))
|
||||
conn.SetWriteDeadline(time.Now().Add(timeout))
|
||||
return conn.WriteJSON(model.ASREvent{Type: "input_audio_buffer.commit"})
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func asrServer(t *testing.T, handle func(*websocket.Conn)) *ASR {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/realtime" || r.URL.Query().Get("model") != "local-asr" {
|
||||
t.Errorf("连接地址不正确: %s", r.URL)
|
||||
}
|
||||
protocols := websocket.Subprotocols(r)
|
||||
if len(protocols) != 2 || protocols[0] != "realtime" || protocols[1] != "openai-insecure-api-key.test-key" {
|
||||
t.Error("未使用预期的认证子协议")
|
||||
}
|
||||
upgrader := websocket.Upgrader{Subprotocols: []string{"realtime"}}
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||
handle(conn)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return &ASR{BaseURL: "ws" + strings.TrimPrefix(server.URL, "http"), Model: "local-asr", APIKey: "test-key"}
|
||||
}
|
||||
|
||||
func initASR(t *testing.T, conn *websocket.Conn) bool {
|
||||
t.Helper()
|
||||
if err := conn.WriteJSON(model.ASREvent{Type: "session.created"}); err != nil {
|
||||
return false
|
||||
}
|
||||
var update model.ASRSessionUpdate
|
||||
if err := conn.ReadJSON(&update); err != nil {
|
||||
t.Error(err)
|
||||
return false
|
||||
}
|
||||
input := update.Session.Audio.Input
|
||||
if update.Type != "session.update" || update.Session.Type != "transcription" || input.Format.Rate != 24000 || input.Format.Type != "audio/pcm" || input.Transcription.Model != "local-asr" || input.Transcription.Language != "zh" || input.TurnDetection != nil {
|
||||
t.Errorf("会话配置错误: %+v", update)
|
||||
}
|
||||
return conn.WriteJSON(model.ASREvent{Type: "session.updated"}) == nil
|
||||
}
|
||||
|
||||
func TestASRTranscribe(t *testing.T) {
|
||||
pcm := bytes.Repeat([]byte{1, 2}, 4801)
|
||||
asr := asrServer(t, func(conn *websocket.Conn) {
|
||||
if !initASR(t, conn) {
|
||||
return
|
||||
}
|
||||
var received []byte
|
||||
for {
|
||||
kind, data, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if kind != websocket.TextMessage {
|
||||
t.Error("音频必须使用 JSON 文本帧")
|
||||
}
|
||||
var event model.ASREvent
|
||||
if err := json.Unmarshal(data, &event); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if event.Type == "input_audio_buffer.commit" {
|
||||
break
|
||||
}
|
||||
chunk, err := base64.StdEncoding.DecodeString(event.Audio)
|
||||
if err != nil || event.Type != "input_audio_buffer.append" || len(chunk) > 4800 || len(chunk)%2 != 0 {
|
||||
t.Errorf("音频包错误: %s,%v", event.Type, err)
|
||||
}
|
||||
received = append(received, chunk...)
|
||||
}
|
||||
if !bytes.Equal(received, pcm) {
|
||||
t.Error("收到的 PCM 与输入不一致")
|
||||
}
|
||||
conn.WriteJSON(model.ASREvent{Type: "conversation.item.input_audio_transcription.delta", ItemID: "one", Delta: "查天气"})
|
||||
conn.WriteJSON(model.ASREvent{Type: "conversation.item.input_audio_transcription.completed", ItemID: "one", Transcript: " 画一只猫。 "})
|
||||
})
|
||||
var delta string
|
||||
text, err := asr.Transcribe(context.Background(), bytes.NewReader(pcm), func(s string) { delta += s })
|
||||
if err != nil || delta != "查天气" || text != "画一只猫。" {
|
||||
t.Fatalf("结果 = %q,临时文字 = %q,错误 = %v", text, delta, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestASRFailures(t *testing.T) {
|
||||
for _, mode := range []string{"空结果", "服务端错误", "转写失败", "断连", "等待最终结果超时", "初始化超时", "录音过短", "读取音频失败", "取消"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
asr := asrServer(t, func(conn *websocket.Conn) {
|
||||
if mode == "初始化超时" {
|
||||
conn.ReadMessage()
|
||||
return
|
||||
}
|
||||
if !initASR(t, conn) {
|
||||
return
|
||||
}
|
||||
for {
|
||||
var event model.ASREvent
|
||||
if conn.ReadJSON(&event) != nil {
|
||||
return
|
||||
}
|
||||
if mode == "取消" {
|
||||
cancel()
|
||||
conn.ReadMessage()
|
||||
return
|
||||
}
|
||||
if event.Type == "input_audio_buffer.commit" {
|
||||
break
|
||||
}
|
||||
}
|
||||
switch mode {
|
||||
case "空结果":
|
||||
conn.WriteJSON(model.ASREvent{Type: "conversation.item.input_audio_transcription.completed"})
|
||||
case "服务端错误", "转写失败":
|
||||
kind := "error"
|
||||
if mode == "转写失败" {
|
||||
kind = "conversation.item.input_audio_transcription.failed"
|
||||
}
|
||||
conn.WriteJSON(map[string]any{"type": kind, "error": map[string]string{"message": "测试失败"}})
|
||||
case "等待最终结果超时":
|
||||
conn.ReadMessage()
|
||||
}
|
||||
})
|
||||
var audio io.Reader = bytes.NewReader(make([]byte, 4800))
|
||||
if mode == "录音过短" {
|
||||
audio = bytes.NewReader(make([]byte, 4798))
|
||||
}
|
||||
if mode == "读取音频失败" {
|
||||
audio = failedAudio{}
|
||||
}
|
||||
text, err := asr.transcribe(ctx, audio, nil, 100*time.Millisecond)
|
||||
if mode == "空结果" {
|
||||
if err != nil || text != "" {
|
||||
t.Fatalf("空结果 = %q,错误 = %v", text, err)
|
||||
}
|
||||
} else if err == nil {
|
||||
t.Fatal("预期失败")
|
||||
}
|
||||
if mode == "取消" && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("预期取消,得到 %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type failedAudio struct{}
|
||||
|
||||
func (failedAudio) Read([]byte) (int, error) {
|
||||
return 0, errors.New("录音设备断开")
|
||||
}
|
||||
|
||||
func TestASRCancelBlockedAudio(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
reader, writer := io.Pipe()
|
||||
defer writer.Close()
|
||||
asr := asrServer(t, func(conn *websocket.Conn) {
|
||||
if initASR(t, conn) {
|
||||
cancel()
|
||||
conn.ReadMessage()
|
||||
}
|
||||
})
|
||||
if _, err := asr.Transcribe(ctx, reader, nil); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("预期取消,得到 %v", err)
|
||||
}
|
||||
if _, err := reader.Read(make([]byte, 2)); err == nil {
|
||||
t.Fatal("取消后应该关闭阻塞的音频读取")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
type option struct {
|
||||
baseURL string
|
||||
modelName string
|
||||
apiKey string
|
||||
}
|
||||
|
||||
type ChatOption func(*option)
|
||||
|
||||
func ChatBaseURL(baseURL string) ChatOption {
|
||||
return func(o *option) {
|
||||
if _, err := url.Parse(baseURL); err == nil {
|
||||
o.baseURL = strings.TrimRight(baseURL, "/")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ChatModel(modelName string) ChatOption {
|
||||
return func(o *option) {
|
||||
if modelName != "" {
|
||||
o.modelName = modelName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ChatApiKey(apiKey string) ChatOption {
|
||||
return func(o *option) {
|
||||
o.apiKey = apiKey
|
||||
}
|
||||
}
|
||||
|
||||
func ChatApiKeyByEnv(env string) ChatOption {
|
||||
return func(o *option) {
|
||||
if val := os.Getenv(env); val != "" {
|
||||
o.apiKey = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type _chat struct {
|
||||
opt *option
|
||||
}
|
||||
|
||||
func NewChat(options ...ChatOption) *_chat {
|
||||
o := &option{
|
||||
modelName: "gpt-4o",
|
||||
baseURL: "https://api.openai.com/v1",
|
||||
apiKey: "",
|
||||
}
|
||||
|
||||
for _, fn := range options {
|
||||
fn(o)
|
||||
}
|
||||
|
||||
return &_chat{
|
||||
opt: o,
|
||||
}
|
||||
}
|
||||
|
||||
// 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, Tools: tools}
|
||||
headers := map[string]string{"Accept": "text/event-stream"}
|
||||
if c.opt.apiKey != "" {
|
||||
headers["Authorization"] = "Bearer " + c.opt.apiKey
|
||||
}
|
||||
|
||||
endpoint := c.opt.baseURL + "/chat/completions"
|
||||
resp, err := PostJSONResponse(ctx, endpoint, headers, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||
return nil, fmt.Errorf("模型接口未返回流式响应")
|
||||
}
|
||||
|
||||
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,52 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// httpClient 由所有 provider 请求共用。
|
||||
var httpClient = &http.Client{}
|
||||
|
||||
// PostJSON 发送 JSON 请求,将响应解码到 result,并检查 HTTP 状态码。
|
||||
func PostJSON(ctx context.Context, endpoint string, headers map[string]string, body, result any) error {
|
||||
resp, err := PostJSONResponse(ctx, endpoint, headers, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return json.NewDecoder(resp.Body).Decode(result)
|
||||
}
|
||||
|
||||
// PostJSONResponse 发送 JSON 请求并检查状态码,调用方负责关闭响应体。
|
||||
func PostJSONResponse(ctx context.Context, endpoint string, headers map[string]string, body any) (*http.Response, error) {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
for key, value := range headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("接口返回 %s,读取错误信息失败: %w", resp.Status, err)
|
||||
}
|
||||
return nil, fmt.Errorf("接口返回 %s: %s", resp.Status, data)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Image 请求图片接口并把结果保存到本地。
|
||||
type Image struct {
|
||||
endpoint string
|
||||
model string
|
||||
apiKey string
|
||||
outputDir string
|
||||
}
|
||||
|
||||
func NewImage(baseURL, modelName, apiKey, outputDir string) *Image {
|
||||
return &Image{endpoint: strings.TrimRight(baseURL, "/") + "/images/generations", model: modelName, apiKey: apiKey, outputDir: outputDir}
|
||||
}
|
||||
|
||||
func (i *Image) Generate(ctx context.Context, prompt string) (*model.ImageResult, error) {
|
||||
if strings.TrimSpace(prompt) == "" {
|
||||
return nil, fmt.Errorf("生图提示词不能为空")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
|
||||
defer cancel()
|
||||
headers := map[string]string{}
|
||||
if i.apiKey != "" {
|
||||
headers["Authorization"] = "Bearer " + i.apiKey
|
||||
}
|
||||
var response model.ImageGenerationResponse
|
||||
if err := PostJSON(ctx, i.endpoint, headers, model.ImageGenerationRequest{Model: i.model, Prompt: prompt, N: 1}, &response); err != nil {
|
||||
return nil, fmt.Errorf("生成图片失败: %w", err)
|
||||
}
|
||||
if len(response.Data) == 0 {
|
||||
return nil, fmt.Errorf("生图接口没有返回图片")
|
||||
}
|
||||
data := response.Data[0]
|
||||
var content []byte
|
||||
var err error
|
||||
switch {
|
||||
case data.Base64 != "":
|
||||
content, err = base64.StdEncoding.DecodeString(data.Base64)
|
||||
case data.URL != "":
|
||||
content, err = downloadImage(ctx, data.URL)
|
||||
default:
|
||||
return nil, fmt.Errorf("生图结果缺少图片数据或 URL")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取图片失败: %w", err)
|
||||
}
|
||||
extension := ""
|
||||
switch http.DetectContentType(content) {
|
||||
case "image/png":
|
||||
extension = ".png"
|
||||
case "image/jpeg":
|
||||
extension = ".jpg"
|
||||
case "image/webp":
|
||||
extension = ".webp"
|
||||
default:
|
||||
return nil, fmt.Errorf("图片格式不支持,仅支持 PNG、JPEG 和 WebP")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
directory, err := filepath.Abs(i.outputDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(directory, 0755); err != nil {
|
||||
return nil, fmt.Errorf("创建图片目录失败: %w", err)
|
||||
}
|
||||
file, err := os.CreateTemp(directory, "image-*"+extension)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建图片文件失败: %w", err)
|
||||
}
|
||||
_, writeErr := file.Write(content)
|
||||
closeErr := file.Close()
|
||||
if writeErr == nil {
|
||||
writeErr = closeErr
|
||||
}
|
||||
if writeErr == nil {
|
||||
writeErr = ctx.Err()
|
||||
}
|
||||
if writeErr != nil {
|
||||
os.Remove(file.Name())
|
||||
return nil, fmt.Errorf("保存图片失败: %w", writeErr)
|
||||
}
|
||||
return &model.ImageResult{Path: file.Name()}, nil
|
||||
}
|
||||
|
||||
func downloadImage(ctx context.Context, url string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 下载地址可能属于另一服务,不转发模型接口的认证信息。
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("图片下载返回 %s", resp.Status)
|
||||
}
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
const testPNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jKioAAAAASUVORK5CYII="
|
||||
|
||||
func TestGenerateImage(t *testing.T) {
|
||||
for _, name := range []string{"base64", "url", "HTTP错误", "JSON错误", "没有图片", "空结果", "无效base64", "格式不支持", "下载失败", "保存失败"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
png, _ := base64.StdEncoding.DecodeString(testPNG)
|
||||
download := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "" {
|
||||
t.Error("下载不应携带模型认证头")
|
||||
}
|
||||
if name == "下载失败" {
|
||||
http.Error(w, "不存在", 404)
|
||||
return
|
||||
}
|
||||
w.Write(png)
|
||||
}))
|
||||
defer download.Close()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var request model.ImageGenerationRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if r.URL.Path != "/v1/images/generations" || r.Method != http.MethodPost || r.Header.Get("Authorization") != "Bearer image-key" || request.Model != "image-model" || request.Prompt != "画一只猫" || request.N != 1 {
|
||||
t.Errorf("生图请求不正确: %s, %+v", r.URL, request)
|
||||
}
|
||||
if name == "HTTP错误" {
|
||||
http.Error(w, "接口失败", 400)
|
||||
return
|
||||
}
|
||||
if name == "JSON错误" {
|
||||
fmt.Fprint(w, "invalid-json")
|
||||
return
|
||||
}
|
||||
response := model.ImageGenerationResponse{Data: []model.ImageGenerationData{{Base64: testPNG}}}
|
||||
switch name {
|
||||
case "url", "下载失败":
|
||||
response.Data[0] = model.ImageGenerationData{URL: download.URL}
|
||||
case "没有图片":
|
||||
response.Data = nil
|
||||
case "空结果":
|
||||
response.Data[0] = model.ImageGenerationData{}
|
||||
case "无效base64":
|
||||
response.Data[0].Base64 = "invalid"
|
||||
case "格式不支持":
|
||||
response.Data[0].Base64 = base64.StdEncoding.EncodeToString([]byte("不是图片"))
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}))
|
||||
defer server.Close()
|
||||
directory := t.TempDir()
|
||||
if name == "保存失败" {
|
||||
blocked := filepath.Join(directory, "file")
|
||||
if err := os.WriteFile(blocked, []byte("阻止创建目录"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
directory = filepath.Join(blocked, "images")
|
||||
}
|
||||
client := NewImage(server.URL+"/v1/", "image-model", "image-key", directory)
|
||||
result, err := client.Generate(context.Background(), "画一只猫")
|
||||
if name != "base64" && name != "url" {
|
||||
if err == nil || result != nil {
|
||||
t.Fatalf("异常结果 = %+v,错误 = %v", result, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content, err := os.ReadFile(result.Path)
|
||||
if err != nil || string(content) != string(png) || !filepath.IsAbs(result.Path) || filepath.Ext(result.Path) != ".png" {
|
||||
t.Fatalf("保存结果 = %+v,错误 = %v", result, err)
|
||||
}
|
||||
// 相同请求使用不同文件名,已有图片不会被覆盖。
|
||||
second, err := client.Generate(context.Background(), "画一只猫")
|
||||
if err != nil || second.Path == result.Path {
|
||||
t.Fatalf("重复保存结果 = %+v,错误 = %v", second, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageCancellation(t *testing.T) {
|
||||
for _, phase := range []string{"生成", "下载"} {
|
||||
t.Run(phase, func(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
download := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer download.Close()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if phase == "生成" {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(model.ImageGenerationResponse{Data: []model.ImageGenerationData{{URL: download.URL}}})
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
directory := t.TempDir()
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := NewImage(server.URL, "image-model", "", directory).Generate(ctx, "画猫")
|
||||
result <- err
|
||||
}()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("请求未开始")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-result:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("取消错误 = %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("取消后请求未退出")
|
||||
}
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatalf("取消后不应保存图片: %v, %v", files, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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,47 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"example.com/ueino/pkg/provider"
|
||||
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// Image 根据完整提示词调用图片接口并保存结果。
|
||||
type Image struct {
|
||||
client *provider.Image
|
||||
}
|
||||
|
||||
func NewImage(client *provider.Image) *Image { return &Image{client: client} }
|
||||
|
||||
func (i *Image) Info(context.Context) (*schema.ToolInfo, error) {
|
||||
return &schema.ToolInfo{
|
||||
Name: "generate_image",
|
||||
Desc: "根据完整的创作提示词生成一张图片,保存到本地并返回实际路径。",
|
||||
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
|
||||
"prompt": {Type: schema.String, Required: true, Desc: "包含主体、构图、风格及用户约束的完整创作提示词"},
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (i *Image) InvokableRun(ctx context.Context, arguments string, _ ...einotool.Option) (string, error) {
|
||||
var args model.ImageArguments
|
||||
if err := json.Unmarshal([]byte(arguments), &args); err != nil {
|
||||
return "", fmt.Errorf("生图参数无效: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(args.Prompt) == "" {
|
||||
return "", fmt.Errorf("生图提示词不能为空")
|
||||
}
|
||||
result, err := i.client.Generate(ctx, args.Prompt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
return string(data), err
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestImageArguments(t *testing.T) {
|
||||
image := NewImage(nil)
|
||||
for _, arguments := range []string{`{`, `{}`, `{"prompt":" "}`} {
|
||||
if _, err := image.InvokableRun(context.Background(), arguments); err == nil {
|
||||
t.Fatalf("应拒绝无效参数: %s", arguments)
|
||||
}
|
||||
}
|
||||
info, err := image.Info(context.Background())
|
||||
if err != nil || info.Name != "generate_image" {
|
||||
t.Fatalf("工具定义 = %+v,错误 = %v", info, 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,63 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Weather 通过 Open-Meteo 查询指定地点的逐日天气预报。
|
||||
type Weather struct {
|
||||
client *http.Client
|
||||
geocodingURL string
|
||||
forecastURL string
|
||||
}
|
||||
|
||||
func NewWeather() *Weather {
|
||||
return &Weather{
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
geocodingURL: "https://geocoding-api.open-meteo.com/v1/search",
|
||||
forecastURL: "https://api.open-meteo.com/v1/forecast",
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Weather) Definition() model.ToolDefinition {
|
||||
return model.ToolDefinition{
|
||||
Type: "function",
|
||||
Function: model.ToolFunctionDefinition{
|
||||
Name: "get_weather",
|
||||
Description: "查询指定地点天气。不传日期查询北京时间今天的预报;传 start_date 查询该日,end_date 可指定结束日期(含)。预报支持北京时间今天起共16天,不支持历史天气。日期必须是 YYYY-MM-DD,明天、本周末等需根据系统当前日期换算。地点可从对话获取,缺少地点时先询问,不要猜测。",
|
||||
Parameters: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"location": map[string]string{"type": "string", "description": "需要查询的城市或地点,例如北京、上海"},
|
||||
"start_date": map[string]string{"type": "string", "description": "预报开始日期,YYYY-MM-DD;不传则查北京时间今天的预报"},
|
||||
"end_date": map[string]string{"type": "string", "description": "预报结束日期,YYYY-MM-DD,含当天;不传则只查开始日期,不能单独提供"},
|
||||
},
|
||||
"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 {
|
||||
log.Printf("[D] unmarshal weather arguments failed, err = %v, raw = %s", err, arguments)
|
||||
return "", fmt.Errorf("天气参数无效: %w", err)
|
||||
}
|
||||
location := strings.TrimSpace(args.Location)
|
||||
if location == "" {
|
||||
return "", fmt.Errorf("请提供要查询的地点")
|
||||
}
|
||||
args.Location = location
|
||||
args.StartDate = strings.TrimSpace(args.StartDate)
|
||||
args.EndDate = strings.TrimSpace(args.EndDate)
|
||||
return w.forecast(ctx, args)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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: "需要查询的城市或地点,例如北京、上海"},
|
||||
"start_date": {Type: schema.String, Desc: "预报开始日期,日期格式: YYYY-MM-DD"},
|
||||
"end_date": {Type: schema.String, Desc: "预报结束日期,日期格式: YYYY-MM-DD"},
|
||||
}),
|
||||
}, 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,151 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
func forecastDates(args model.WeatherArguments, now time.Time) (time.Time, time.Time, error) {
|
||||
zone := time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
now = now.In(zone)
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, zone)
|
||||
start := today
|
||||
var err error
|
||||
if args.StartDate != "" {
|
||||
start, err = time.ParseInLocation(time.DateOnly, args.StartDate, zone)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("start_date 必须是 YYYY-MM-DD 格式的有效日期")
|
||||
}
|
||||
} else if args.EndDate != "" {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("end_date 不能单独提供,请同时提供 start_date")
|
||||
}
|
||||
end := start
|
||||
if args.EndDate != "" {
|
||||
end, err = time.ParseInLocation(time.DateOnly, args.EndDate, zone)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("end_date 必须是 YYYY-MM-DD 格式的有效日期")
|
||||
}
|
||||
}
|
||||
last := today.AddDate(0, 0, 15)
|
||||
if end.Before(start) {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("结束日期不能早于开始日期")
|
||||
}
|
||||
if start.Before(today) || end.After(last) {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("预报仅支持 %s 至 %s,不支持历史或更远日期", today.Format(time.DateOnly), last.Format(time.DateOnly))
|
||||
}
|
||||
return start, end, nil
|
||||
}
|
||||
|
||||
func (w *Weather) forecast(ctx context.Context, args model.WeatherArguments) (string, error) {
|
||||
start, end, err := forecastDates(args, time.Now())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
search := url.Values{"name": {args.Location}, "count": {"1"}, "language": {"zh"}, "format": {"json"}}
|
||||
var locations model.WeatherLocations
|
||||
if err := w.getWeatherJSON(ctx, w.geocodingURL+"?"+search.Encode(), &locations); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(locations.Results) == 0 {
|
||||
return "", fmt.Errorf("未找到地点 %q,请提供明确的城市名称", args.Location)
|
||||
}
|
||||
location := locations.Results[0]
|
||||
query := url.Values{
|
||||
"latitude": {strconv.FormatFloat(location.Latitude, 'f', -1, 64)},
|
||||
"longitude": {strconv.FormatFloat(location.Longitude, 'f', -1, 64)},
|
||||
"start_date": {start.Format(time.DateOnly)}, "end_date": {end.Format(time.DateOnly)},
|
||||
"timezone": {"Asia/Shanghai"},
|
||||
"daily": {"weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"},
|
||||
}
|
||||
var response model.WeatherDailyResponse
|
||||
if err := w.getWeatherJSON(ctx, w.forecastURL+"?"+query.Encode(), &response); err != nil {
|
||||
return "", err
|
||||
}
|
||||
result := model.WeatherForecast{
|
||||
Location: strings.TrimSpace(location.Name + " " + location.Admin1 + " " + location.Country),
|
||||
Timezone: "Asia/Shanghai",
|
||||
}
|
||||
daily := response.Daily
|
||||
for date := start; !date.After(end); date = date.AddDate(0, 0, 1) {
|
||||
day := date.Format(time.DateOnly)
|
||||
index := slices.Index(daily.Dates, day)
|
||||
if index < 0 || index >= len(daily.Codes) || index >= len(daily.MaxTemps) || index >= len(daily.MinTemps) || index >= len(daily.RainChances) {
|
||||
return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day)
|
||||
}
|
||||
if daily.Codes[index] == nil || daily.MaxTemps[index] == nil || daily.MinTemps[index] == nil || daily.RainChances[index] == nil {
|
||||
return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day)
|
||||
}
|
||||
result.Days = append(result.Days, model.WeatherDay{
|
||||
Date: day, Condition: weatherCondition(*daily.Codes[index]),
|
||||
MinTemperatureC: *daily.MinTemps[index], MaxTemperatureC: *daily.MaxTemps[index],
|
||||
PrecipitationChancePct: *daily.RainChances[index],
|
||||
})
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
return string(data), err
|
||||
}
|
||||
|
||||
func (w *Weather) getWeatherJSON(ctx context.Context, endpoint string, result any) error {
|
||||
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)
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
|
||||
return fmt.Errorf("解析天气接口响应失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func weatherCondition(code int) string {
|
||||
switch code {
|
||||
case 0:
|
||||
return "晴"
|
||||
case 1:
|
||||
return "大部晴朗"
|
||||
case 2:
|
||||
return "多云"
|
||||
case 3:
|
||||
return "阴"
|
||||
case 45, 48:
|
||||
return "雾"
|
||||
case 51, 53, 55:
|
||||
return "毛毛雨"
|
||||
case 56, 57, 66, 67:
|
||||
return "冻雨"
|
||||
case 61:
|
||||
return "小雨"
|
||||
case 63:
|
||||
return "中雨"
|
||||
case 65:
|
||||
return "大雨"
|
||||
case 71, 73, 75, 77:
|
||||
return "雪"
|
||||
case 80, 81, 82:
|
||||
return "阵雨"
|
||||
case 85, 86:
|
||||
return "阵雪"
|
||||
case 95:
|
||||
return "雷暴"
|
||||
case 96, 99:
|
||||
return "雷暴伴冰雹"
|
||||
default:
|
||||
return fmt.Sprintf("未知天气(WMO %d)", code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
func TestForecastDates(t *testing.T) {
|
||||
// UTC 尚未跨年,北京时间已是下一年的第一天。
|
||||
now := time.Date(2026, 12, 31, 16, 30, 0, 0, time.UTC)
|
||||
for _, tt := range []struct {
|
||||
name, start, end, wantEnd string
|
||||
invalid bool
|
||||
}{
|
||||
{name: "默认今天", wantEnd: "2027-01-01"},
|
||||
{name: "单日", start: "2027-01-02", wantEnd: "2027-01-02"},
|
||||
{name: "整个窗口", start: "2027-01-01", end: "2027-01-16", wantEnd: "2027-01-16"},
|
||||
{name: "缺少开始日期", end: "2027-01-02", invalid: true},
|
||||
{name: "相对日期", start: "明天", invalid: true},
|
||||
{name: "无效日期", start: "2027-02-30", invalid: true},
|
||||
{name: "无效结束", start: "2027-01-02", end: "周末", invalid: true},
|
||||
{name: "过去日期", start: "2026-12-31", invalid: true},
|
||||
{name: "超出窗口", start: "2027-01-16", end: "2027-01-17", invalid: true},
|
||||
{name: "反向范围", start: "2027-01-02", end: "2027-01-01", invalid: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
start, end, err := forecastDates(model.WeatherArguments{StartDate: tt.start, EndDate: tt.end}, now)
|
||||
if tt.invalid {
|
||||
if err == nil {
|
||||
t.Fatal("预期参数错误")
|
||||
}
|
||||
return
|
||||
}
|
||||
wantStart := tt.start
|
||||
if wantStart == "" {
|
||||
wantStart = "2027-01-01"
|
||||
}
|
||||
if err != nil || start.Format(time.DateOnly) != wantStart || end.Format(time.DateOnly) != tt.wantEnd {
|
||||
t.Fatalf("日期范围 = %s 至 %s,错误 = %v", start, end, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeatherForecast(t *testing.T) {
|
||||
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
|
||||
for _, days := range []int{1, 2} {
|
||||
t.Run(fmt.Sprintf("%d天", days), func(t *testing.T) {
|
||||
start := today.AddDate(0, 0, 1).Format(time.DateOnly)
|
||||
end := today.AddDate(0, 0, days).Format(time.DateOnly)
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != http.MethodGet {
|
||||
t.Error("应使用 GET")
|
||||
}
|
||||
query := r.URL.Query()
|
||||
if r.URL.Path == "/search" {
|
||||
if query.Get("name") != "北京 海淀/?&" || query.Get("count") != "1" || query.Get("language") != "zh" {
|
||||
t.Errorf("地点查询编码错误: %v", query)
|
||||
}
|
||||
fmt.Fprint(w, `{"results":[{"name":"北京","admin1":"北京市","country":"中国","latitude":39.9,"longitude":116.4}]}`)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/forecast" || query.Get("latitude") != "39.9" || query.Get("longitude") != "116.4" || query.Get("start_date") != start || query.Get("end_date") != end || query.Get("timezone") != "Asia/Shanghai" || query.Get("daily") != "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max" {
|
||||
t.Errorf("预报请求错误: %s", r.URL)
|
||||
}
|
||||
// 返回乱序日期及额外日期,必须按请求范围提取排序。
|
||||
json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{
|
||||
"time": []string{today.AddDate(0, 0, 2).Format(time.DateOnly), start, today.Format(time.DateOnly)},
|
||||
"weather_code": []int{61, 0, 3}, "temperature_2m_max": []float64{12, 18, 15},
|
||||
"temperature_2m_min": []float64{3, 8, 6}, "precipitation_probability_max": []float64{80, 0, 30},
|
||||
}})
|
||||
}))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
|
||||
args := model.WeatherArguments{Location: " 北京 海淀/?& ", StartDate: start}
|
||||
if days == 2 {
|
||||
args.EndDate = end
|
||||
}
|
||||
arguments, _ := json.Marshal(args)
|
||||
result, err := weather.Execute(context.Background(), string(arguments))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var forecast model.WeatherForecast
|
||||
if err := json.Unmarshal([]byte(result), &forecast); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 2 || forecast.Location != "北京 北京市 中国" || forecast.Timezone != "Asia/Shanghai" || len(forecast.Days) != days {
|
||||
t.Fatalf("预报结果 = %+v,调用次数 = %d", forecast, calls)
|
||||
}
|
||||
first := forecast.Days[0]
|
||||
if first.Date != start || first.Condition != "晴" || first.MinTemperatureC != 8 || first.MaxTemperatureC != 18 || first.PrecipitationChancePct != 0 {
|
||||
t.Fatalf("单日数据错误: %+v", first)
|
||||
}
|
||||
if days == 2 && (forecast.Days[1].Date != end || forecast.Days[1].Condition != "小雨") {
|
||||
t.Fatalf("日期顺序错误: %+v", forecast.Days)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestForecastInvalidArguments(t *testing.T) {
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ }))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.geocodingURL = server.URL
|
||||
for _, args := range []string{
|
||||
`{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`,
|
||||
`{"location":"北京","end_date":"2026-11-20"}`,
|
||||
`{"location":"北京","start_date":"明天"}`,
|
||||
`{"location":"北京","start_date":"2000-01-01"}`,
|
||||
`{"location":"北京","start_date":"2999-01-01"}`,
|
||||
`{"start_date":"2026-11-19"}`,
|
||||
`{"location":"北京","start_date":123}`,
|
||||
} {
|
||||
if _, err := weather.Execute(context.Background(), args); err == nil {
|
||||
t.Errorf("参数 %s 应返回错误", args)
|
||||
}
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("无效参数请求了接口 %d 次", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForecastResponseErrors(t *testing.T) {
|
||||
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||||
for _, mode := range []string{"查无城市", "搜索失败", "预报失败", "错误JSON", "缺少日期", "缺少字段", "字段为空"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.URL.Path == "/search" {
|
||||
switch mode {
|
||||
case "查无城市":
|
||||
fmt.Fprint(w, `{}`)
|
||||
case "搜索失败":
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
case "错误JSON":
|
||||
fmt.Fprint(w, "{")
|
||||
default:
|
||||
fmt.Fprint(w, `{"results":[{"name":"北京","latitude":39.9,"longitude":116.4}]}`)
|
||||
}
|
||||
return
|
||||
}
|
||||
if mode == "预报失败" {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
daily := map[string]any{
|
||||
"time": []string{date}, "weather_code": []int{0},
|
||||
"temperature_2m_max": []float64{18}, "temperature_2m_min": []float64{8},
|
||||
"precipitation_probability_max": []float64{0},
|
||||
}
|
||||
switch mode {
|
||||
case "缺少日期":
|
||||
daily["time"] = []string{}
|
||||
case "缺少字段":
|
||||
delete(daily, "temperature_2m_min")
|
||||
case "字段为空":
|
||||
daily["weather_code"] = []any{nil}
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"daily": daily})
|
||||
}))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
|
||||
args := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date)
|
||||
if _, err := weather.Execute(context.Background(), args); err == nil {
|
||||
t.Fatal("接口异常应返回错误")
|
||||
}
|
||||
if (mode == "查无城市" || mode == "搜索失败" || mode == "错误JSON") && calls != 1 {
|
||||
t.Fatal("城市查询失败后不应请求预报")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestForecastCancellationAndTimeout(t *testing.T) {
|
||||
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||||
arguments := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.geocodingURL = server.URL
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := weather.Execute(ctx, arguments); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("取消错误 = %v", err)
|
||||
}
|
||||
weather.client.Timeout = 20 * time.Millisecond
|
||||
if _, err := weather.Execute(context.Background(), arguments); err == nil || !strings.Contains(err.Error(), "Client.Timeout") {
|
||||
t.Fatalf("超时错误 = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
func TestWeatherDefaultsToToday(t *testing.T) {
|
||||
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.URL.Path == "/search" {
|
||||
if r.URL.Query().Get("name") != "北京" {
|
||||
t.Errorf("地点参数错误: %s", r.URL)
|
||||
}
|
||||
fmt.Fprint(w, `{"results":[{"name":"北京","country":"中国","latitude":39.9,"longitude":116.4}]}`)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/forecast" || r.URL.Query().Get("start_date") != today || r.URL.Query().Get("end_date") != today {
|
||||
t.Errorf("未指定日期时应查询北京时间今天: %s", r.URL)
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{
|
||||
"time": []string{today}, "weather_code": []int{0},
|
||||
"temperature_2m_min": []int{10}, "temperature_2m_max": []int{20},
|
||||
"precipitation_probability_max": []int{0},
|
||||
}})
|
||||
}))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
|
||||
result, err := weather.Execute(context.Background(), `{"location":" 北京 "}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var forecast model.WeatherForecast
|
||||
if err := json.Unmarshal([]byte(result), &forecast); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 2 || len(forecast.Days) != 1 || forecast.Days[0].Date != today || forecast.Days[0].Condition != "晴" {
|
||||
t.Fatalf("默认查询结果不正确: %+v,请求次数=%d", forecast, calls)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user