Skip to content

Commit 7e499a7

Browse files
committed
完善错误处理
1 parent e7248c5 commit 7e499a7

File tree

6 files changed

+100
-21
lines changed

6 files changed

+100
-21
lines changed

config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ use_private_config: false
5454
# 选择使用的模块
5555
selected_module:
5656
ASR: DoubaoASR
57-
TTS: DoubaoTTS
57+
TTS: EdgeTTS
5858
LLM: OllamaLLM
5959
VLLLM: ChatGLMVLLM
6060

src/core/connection.go

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,15 @@ func (h *ConnectionHandler) handleChatMessage(ctx context.Context, text string)
433433
}
434434

435435
func (h *ConnectionHandler) genResponseByLLM(ctx context.Context, messages []providers.Message, round int) error {
436+
defer func() {
437+
if r := recover(); r != nil {
438+
h.logger.Error(fmt.Sprintf("genResponseByLLM发生panic: %v", r))
439+
errorMsg := "抱歉,处理您的请求时发生了错误"
440+
h.tts_last_text_index = 1 // 重置文本索引
441+
h.SpeakAndPlay(errorMsg, 1, round)
442+
}
443+
}()
444+
436445
llmStartTime := time.Now()
437446
h.logger.FormatInfo("开始生成LLM回复, round:%d 打印message", round)
438447
for _, msg := range messages {
@@ -463,6 +472,14 @@ func (h *ConnectionHandler) genResponseByLLM(ctx context.Context, messages []pro
463472
content := response.Content
464473
toolCall := response.ToolCalls
465474

475+
if response.Error != "" {
476+
h.logger.Error(fmt.Sprintf("LLM响应错误: %s", response.Error))
477+
errorMsg := "抱歉,服务暂时不可用,请稍后再试"
478+
h.tts_last_text_index = 1 // 重置文本索引
479+
h.SpeakAndPlay(errorMsg, 1, round)
480+
return fmt.Errorf("LLM响应错误: %s", response.Error)
481+
}
482+
466483
if content != "" {
467484
// 累加content_arguments
468485
contentArguments += content
@@ -486,11 +503,23 @@ func (h *ConnectionHandler) genResponseByLLM(ctx context.Context, messages []pro
486503
}
487504

488505
if content != "" {
506+
if strings.Contains(content, "服务响应异常") {
507+
h.logger.Error(fmt.Sprintf("检测到LLM服务异常: %s", content))
508+
errorMsg := "抱歉,服务暂时不可用,请稍后再试"
509+
h.tts_last_text_index = 1 // 重置文本索引
510+
h.SpeakAndPlay(errorMsg, 1, round)
511+
return fmt.Errorf("LLM服务异常")
512+
}
513+
489514
if !toolCallFlag {
490515
responseMessage = append(responseMessage, content)
491516
}
492517
// 处理分段
493518
fullText := utils.JoinStrings(responseMessage)
519+
if len(fullText) <= processedChars {
520+
h.logger.Warn(fmt.Sprintf("文本处理异常: fullText长度=%d, processedChars=%d", len(fullText), processedChars))
521+
continue
522+
}
494523
currentText := fullText[processedChars:]
495524

496525
// 按标点符号分割
@@ -562,12 +591,17 @@ func (h *ConnectionHandler) genResponseByLLM(ctx context.Context, messages []pro
562591
}
563592

564593
// 处理剩余文本
565-
remainingText := utils.JoinStrings(responseMessage)[processedChars:]
566-
if remainingText != "" {
567-
textIndex++
568-
h.logger.Info(fmt.Sprintf("LLM回复分段[剩余文本]: %s, index: %d, round:%d", remainingText, textIndex, round))
569-
h.tts_last_text_index = textIndex
570-
h.SpeakAndPlay(remainingText, textIndex, round)
594+
fullResponse := utils.JoinStrings(responseMessage)
595+
if len(fullResponse) > processedChars {
596+
remainingText := fullResponse[processedChars:]
597+
if remainingText != "" {
598+
textIndex++
599+
h.logger.Info(fmt.Sprintf("LLM回复分段[剩余文本]: %s, index: %d, round:%d", remainingText, textIndex, round))
600+
h.tts_last_text_index = textIndex
601+
h.SpeakAndPlay(remainingText, textIndex, round)
602+
}
603+
} else {
604+
h.logger.Info(fmt.Sprintf("无剩余文本需要处理: fullResponse长度=%d, processedChars=%d", len(fullResponse), processedChars))
571605
}
572606

573607
// 分析回复并发送相应的情绪

src/core/mcp/client.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ func NewClient(config *Config, logger *utils.Logger) (*Client, error) {
6666
}
6767
c.stdioClient = stdioClient
6868
c.useStdioClient = true
69+
} else {
70+
fmt.Println("Unsupported MCP client type, only stdio client is supported")
6971
}
7072

7173
return c, nil

src/core/mcp/manager.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,22 +120,27 @@ func (m *Manager) preInitializeServers() error {
120120
}
121121

122122
srvConfigMap, ok := srvConfig.(map[string]interface{})
123+
123124
if !ok {
125+
m.logger.Warn(fmt.Sprintf("Invalid configuration format for server %s", name))
124126
continue
125127
}
126128

127129
// 创建并启动外部MCP客户端
128130
clientConfig, err := convertConfig(srvConfigMap)
129131
if err != nil {
132+
m.logger.Error(fmt.Sprintf("Failed to convert config for server %s: %v", name, err))
130133
continue
131134
}
132135

133136
client, err := NewClient(clientConfig, m.logger)
134137
if err != nil {
138+
m.logger.Error(fmt.Sprintf("Failed to create MCP client for server %s: %v", name, err))
135139
continue
136140
}
137141

138142
if err := client.Start(context.Background()); err != nil {
143+
m.logger.Error(fmt.Sprintf("Failed to start MCP client %s: %v", name, err))
139144
continue
140145
}
141146
m.clients[name] = client

src/core/providers/asr/doubao/doubao.go

Lines changed: 52 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"encoding/binary"
88
"encoding/json"
99
"fmt"
10+
"net"
1011
"net/http"
1112
"os"
1213
"path/filepath"
@@ -474,37 +475,68 @@ func (p *Provider) AddAudioWithContext(ctx context.Context, data []byte) error {
474475
p.isStreaming = true
475476
// 开启一个协程来处理响应,读取最后的结果,读取完成后关闭协程
476477
go func() {
478+
defer func() {
479+
if r := recover(); r != nil {
480+
p.logger.Error(fmt.Sprintf("流式识别协程发生错误: %v", r))
481+
}
482+
p.connMutex.Lock()
483+
p.isStreaming = false // 标记流式识别结束
484+
if p.conn != nil {
485+
p.closeConnection()
486+
}
487+
p.connMutex.Unlock()
488+
}()
489+
477490
for {
478-
_, response, err := p.conn.ReadMessage()
479-
if err != nil {
480-
p.connMutex.Lock()
481-
p.err = fmt.Errorf("读取响应失败: %v", err)
491+
// 检查连接状态,避免在连接关闭后继续读取
492+
p.connMutex.Lock()
493+
if !p.isStreaming || p.conn == nil {
482494
p.connMutex.Unlock()
483495
return
484496
}
497+
conn := p.conn
498+
p.connMutex.Unlock()
499+
500+
conn.SetReadDeadline(time.Now().Add(30 * time.Second))
501+
502+
_, response, err := conn.ReadMessage()
503+
if err != nil {
504+
var shouldStop bool
505+
var logMsg string
506+
507+
if websocket.IsCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
508+
logMsg = "WebSocket连接正常关闭"
509+
shouldStop = false
510+
} else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
511+
logMsg = "WebSocket读取超时,可能连接空闲"
512+
shouldStop = true
513+
} else {
514+
logMsg = fmt.Sprintf("读取响应失败: %v", err)
515+
shouldStop = true
516+
}
517+
518+
p.logger.Info(logMsg)
519+
if shouldStop {
520+
p.setErrorAndStop(fmt.Errorf("%s", logMsg))
521+
}
522+
}
485523

486524
result, err := p.parseResponse(response)
487525
if err != nil {
488-
p.connMutex.Lock()
489-
p.err = fmt.Errorf("解析响应失败: %v", err)
490-
p.connMutex.Unlock()
526+
p.setErrorAndStop(fmt.Errorf("解析响应失败: %v", err))
491527
return
492528
}
493529

494530
var respPayload responsePayload
495531

496532
payloadMsgData, err := json.Marshal(result["payload_msg"])
497533
if err != nil {
498-
p.connMutex.Lock()
499-
p.err = fmt.Errorf("重新序列化响应payload_msg失败: %v", err)
500-
p.connMutex.Unlock()
534+
p.setErrorAndStop(fmt.Errorf("重新序列化响应payload_msg失败: %v", err))
501535
return
502536
}
503537

504538
if err := json.Unmarshal(payloadMsgData, &respPayload); err != nil {
505-
p.connMutex.Lock()
506-
p.err = fmt.Errorf("解析最终响应payload失败: %v. Raw: %s", err, string(payloadMsgData))
507-
p.connMutex.Unlock()
539+
p.setErrorAndStop(fmt.Errorf("解析最终响应payload失败: %v", err))
508540
return
509541
}
510542

@@ -547,6 +579,13 @@ func (p *Provider) AddAudioWithContext(ctx context.Context, data []byte) error {
547579
return nil
548580
}
549581

582+
func (p *Provider) setErrorAndStop(err error) {
583+
p.connMutex.Lock()
584+
p.err = err
585+
p.isStreaming = false
586+
p.connMutex.Unlock()
587+
}
588+
550589
func (p *Provider) closeConnection() {
551590
defer func() {
552591
if r := recover(); r != nil {

src/core/providers/llm/openai/openai.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,6 @@ func (p *Provider) ResponseWithFunctions(ctx context.Context, sessionID string,
192192
}
193193
}
194194
chunk.ToolCalls = toolCalls
195-
fmt.Println("openai tool calls:", chunk.ToolCalls)
196195
}
197196

198197
responseChan <- chunk

0 commit comments

Comments
 (0)