feat: demonstrate streaming ASR composition with Eino Chain
This commit is contained in:
1 parent
1373f0903f
commit
2cf82034ec
8 files changed
+685
-8
No files matched your search
@@ -0,0 +1,198 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
wire "example.com/ueino/pkg/model"
|
||||
"example.com/ueino/pkg/provider"
|
||||
"github.com/cloudwego/eino-ext/components/model/openai"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func TestASRChain(t *testing.T) {
|
||||
for _, mode := range []string{"定稿", "多段定稿", "空转写", "转写失败"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 9*time.Second)
|
||||
defer cancel()
|
||||
deltaShown := make(chan struct{})
|
||||
segmentShown := make(chan struct{})
|
||||
var sessions atomic.Int32
|
||||
wantText := "最终文字"
|
||||
if mode == "多段定稿" {
|
||||
wantText += "\n末段文字"
|
||||
}
|
||||
success := mode == "定稿" || mode == "多段定稿"
|
||||
asrServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session := sessions.Add(1)
|
||||
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(7 * time.Second))
|
||||
send := func(event wire.ASREvent) {
|
||||
if err := conn.WriteJSON(event); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
receive := func(want string) bool {
|
||||
var event wire.ASREvent
|
||||
if err := conn.ReadJSON(&event); err != nil || event.Type != want {
|
||||
t.Errorf("收到 %q,预期 %q,错误 %v", event.Type, want, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
send(wire.ASREvent{Type: "session.created"})
|
||||
if !receive("session.update") {
|
||||
return
|
||||
}
|
||||
send(wire.ASREvent{Type: "session.updated"})
|
||||
blocks := 2
|
||||
if mode == "多段定稿" {
|
||||
blocks = 30
|
||||
if session == 2 {
|
||||
blocks = 1 // 短尾段补齐到一个块后提交。
|
||||
}
|
||||
}
|
||||
for i := 0; i < blocks; i++ {
|
||||
if !receive("input_audio_buffer.append") {
|
||||
return
|
||||
}
|
||||
if i == 0 && session == 1 {
|
||||
send(wire.ASREvent{Type: "conversation.item.input_audio_transcription.delta", Delta: "临时文字"})
|
||||
}
|
||||
}
|
||||
if !receive("input_audio_buffer.commit") {
|
||||
return
|
||||
}
|
||||
switch mode {
|
||||
case "定稿", "多段定稿":
|
||||
text := "最终文字"
|
||||
if session == 2 {
|
||||
text = "末段文字"
|
||||
}
|
||||
send(wire.ASREvent{Type: "conversation.item.input_audio_transcription.completed", Transcript: text})
|
||||
case "空转写":
|
||||
send(wire.ASREvent{Type: "conversation.item.input_audio_transcription.completed"})
|
||||
case "转写失败":
|
||||
send(wire.ASREvent{Type: "conversation.item.input_audio_transcription.failed"})
|
||||
}
|
||||
}))
|
||||
defer asrServer.Close()
|
||||
|
||||
var calls atomic.Int32
|
||||
finalShown := make(chan struct{})
|
||||
chatServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
select {
|
||||
case <-finalShown:
|
||||
default:
|
||||
t.Error("聊天请求早于最终转写")
|
||||
}
|
||||
var request wire.ChatCompletionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if !request.Stream || len(request.Messages) != 2 || request.Messages[1].Role != "user" || request.Messages[1].Content != wantText {
|
||||
t.Errorf("聊天模型应以流式方式接收最终转写:%+v", request)
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"收到\"}}]}\n\ndata: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"定稿\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
|
||||
}))
|
||||
defer chatServer.Close()
|
||||
|
||||
chat, err := openai.NewChatModel(ctx, &openai.ChatModelConfig{BaseURL: chatServer.URL, Model: "test", APIKey: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
asr := &provider.ASR{BaseURL: "ws" + strings.TrimPrefix(asrServer.URL, "http"), Model: "test", APIKey: "test"}
|
||||
chain, err := NewChain(ctx, asr, chat, func(event Transcript) {
|
||||
if event.Kind == Final {
|
||||
close(finalShown)
|
||||
} else if event.Kind == Segment && mode == "多段定稿" && event.Text == "最终文字" {
|
||||
if calls.Load() != 0 {
|
||||
t.Error("首段定稿不能触发聊天请求")
|
||||
}
|
||||
close(segmentShown)
|
||||
} else if event.Kind == Delta && event.Text == "临时文字" {
|
||||
close(deltaShown)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
audio, writer := schema.Pipe[[]byte](0)
|
||||
go func() {
|
||||
defer writer.Close()
|
||||
if writer.Send(make([]byte, pcmChunkSize), nil) {
|
||||
return
|
||||
}
|
||||
// 第二块尚未输入时,就必须能向用户展示临时转写。
|
||||
select {
|
||||
case <-deltaShown:
|
||||
blocks := 1
|
||||
if mode == "多段定稿" {
|
||||
blocks = 29
|
||||
}
|
||||
for i := 0; i < blocks; i++ {
|
||||
if writer.Send(make([]byte, pcmChunkSize), nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if mode == "多段定稿" {
|
||||
select {
|
||||
case <-segmentShown:
|
||||
writer.Send([]byte{1, 2}, nil)
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}()
|
||||
reply, err := chain.Transform(ctx, audio)
|
||||
if err != nil {
|
||||
if success || calls.Load() != 0 ||
|
||||
(mode == "空转写" && !strings.Contains(err.Error(), "未识别到文字")) ||
|
||||
(mode == "转写失败" && !strings.Contains(err.Error(), "语音识别失败")) {
|
||||
t.Fatalf("聊天调用=%d,错误=%v", calls.Load(), err)
|
||||
}
|
||||
return
|
||||
}
|
||||
defer reply.Close()
|
||||
if !success {
|
||||
t.Fatalf("%s 不应产生回复", mode)
|
||||
}
|
||||
var text strings.Builder
|
||||
for {
|
||||
message, err := reply.Recv()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text.WriteString(message.Content)
|
||||
}
|
||||
if mode == "多段定稿" && sessions.Load() != 2 {
|
||||
t.Fatalf("应有两次 ASR 会话,实际 %d", sessions.Load())
|
||||
}
|
||||
if calls.Load() != 1 || text.String() != "收到定稿" {
|
||||
t.Fatalf("聊天调用=%d,回复=%q", calls.Load(), text.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user