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>
92 lines
2.1 KiB
Go
92 lines
2.1 KiB
Go
// Package terminal 提供 ADK 示例的终端交互。
|
|
package terminal
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"strings"
|
|
|
|
"example.com/ueino/adk/internal/agent"
|
|
"example.com/ueino/adk/internal/config"
|
|
)
|
|
|
|
func Run(ctx context.Context, cfg config.Config, voice bool) error {
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
chat, err := agent.New(ctx, cfg)
|
|
if err != nil {
|
|
return fmt.Errorf("创建 Agent 失败: %w", err)
|
|
}
|
|
inputReader := newInput(ctx, os.Stdin)
|
|
if voice {
|
|
fmt.Println("语音聊天模式,每轮自动开始录音,回车结束录音,按 Ctrl+C 退出。")
|
|
} else {
|
|
fmt.Println("输入消息开始聊天,按 Ctrl+C 退出。")
|
|
}
|
|
for ctx.Err() == nil {
|
|
var input string
|
|
if voice {
|
|
input, err = readVoice(ctx, cfg.ASR, inputReader)
|
|
} else {
|
|
fmt.Print("你> ")
|
|
input, err = inputReader.next(ctx)
|
|
}
|
|
if errors.Is(err, io.EOF) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
input = strings.TrimSpace(input)
|
|
if input == "" {
|
|
continue
|
|
}
|
|
fmt.Println("助手>")
|
|
err = chat.Chat(ctx, input,
|
|
func(text string) { fmt.Print(text) },
|
|
func(status string) { fmt.Printf("\n[%s]\n", status) },
|
|
func(prompt string) (bool, error) { return confirmImage(ctx, inputReader, prompt) },
|
|
)
|
|
fmt.Println()
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
if errors.Is(err, io.EOF) {
|
|
return nil
|
|
}
|
|
if errors.Is(err, agent.ErrImageRejected) {
|
|
fmt.Println(agent.ErrImageRejected)
|
|
continue
|
|
}
|
|
if err != nil {
|
|
fmt.Printf("请求失败: %v\n", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func confirmImage(ctx context.Context, input *terminalInput, prompt string) (bool, error) {
|
|
fmt.Printf("\n即将生成图片,提示词:\n%s\n", prompt)
|
|
for {
|
|
if err := ctx.Err(); err != nil {
|
|
return false, err
|
|
}
|
|
fmt.Print("确认生成?[y/N] ")
|
|
line, err := input.next(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
switch strings.ToLower(strings.TrimSpace(line)) {
|
|
case "y", "yes", "确认":
|
|
return true, nil
|
|
case "", "n", "no", "取消", "拒绝":
|
|
return false, nil
|
|
default:
|
|
fmt.Println("请输入 y 确认或 n 取消。")
|
|
}
|
|
}
|
|
}
|