2026-06-09 23:53:08 +08:00
|
|
|
package service
|
2026-06-10 15:13:21 +08:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"ai-agent-scaffold-go/internal/model"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// RunnerImpl Runner 的默认实现
|
|
|
|
|
type RunnerImpl struct {
|
|
|
|
|
appName string
|
|
|
|
|
agent model.Agent
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewRunner 创建 Runner
|
|
|
|
|
func NewRunner(appName string, agent model.Agent) *RunnerImpl {
|
|
|
|
|
return &RunnerImpl{
|
|
|
|
|
appName: appName,
|
|
|
|
|
agent: agent,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// CreateSession 创建会话 ID
|
|
|
|
|
func (r *RunnerImpl) CreateSession(userID string) (string, error) {
|
|
|
|
|
if strings.TrimSpace(userID) == "" {
|
|
|
|
|
return "", fmt.Errorf("user id is required")
|
|
|
|
|
}
|
|
|
|
|
next := sessionCounter.Add(1)
|
|
|
|
|
return fmt.Sprintf("%s:%s:%d", r.appName, userID, next), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Run 同步执行
|
|
|
|
|
func (r *RunnerImpl) Run(userID, sessionID string, content model.ChatContent) ([]string, error) {
|
|
|
|
|
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
|
|
|
|
|
return nil, fmt.Errorf("user id and session id are required")
|
|
|
|
|
}
|
|
|
|
|
output, err := r.agent.Run(context.Background(), content)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
if output == "" {
|
|
|
|
|
return []string{}, nil
|
|
|
|
|
}
|
|
|
|
|
return []string{output}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stream 流式执行
|
|
|
|
|
func (r *RunnerImpl) Stream(userID, sessionID string, content model.ChatContent) (<-chan string, <-chan error) {
|
|
|
|
|
outputs := make(chan string, 8)
|
|
|
|
|
errs := make(chan error, 1)
|
|
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
defer close(outputs)
|
|
|
|
|
defer close(errs)
|
|
|
|
|
|
|
|
|
|
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
|
|
|
|
|
errs <- fmt.Errorf("user id and session id are required")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if err := r.agent.Stream(context.Background(), content, outputs); err != nil {
|
|
|
|
|
errs <- err
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
return outputs, errs
|
|
|
|
|
}
|