From 66925d188ac003b816fc0ecc8cd2c732cb112c51 Mon Sep 17 00:00:00 2001 From: Kayvan Sylvan Date: Sun, 29 Jun 2025 23:27:24 -0700 Subject: [PATCH] fix: move channel close to defer statement in OpenAI streaming methods ## CHANGES - Move close(channel) to defer statement - Ensure channel closes even on errors - Apply fix to sendStreamChatCompletions method - Apply fix to sendStreamResponses method - Improve error handling reliability - Prevent potential channel leaks --- plugins/ai/openai/chat_completions.go | 3 ++- plugins/ai/openai/openai.go | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/plugins/ai/openai/chat_completions.go b/plugins/ai/openai/chat_completions.go index ede434d9..f04a615d 100644 --- a/plugins/ai/openai/chat_completions.go +++ b/plugins/ai/openai/chat_completions.go @@ -32,6 +32,8 @@ func (o *Client) sendChatCompletions(ctx context.Context, msgs []*chat.ChatCompl func (o *Client) sendStreamChatCompletions( msgs []*chat.ChatCompletionMessage, opts *common.ChatOptions, channel chan string, ) (err error) { + defer close(channel) + req := o.buildChatCompletionParams(msgs, opts) stream := o.ApiClient.Chat.Completions.NewStreaming(context.Background(), req) for stream.Next() { @@ -43,7 +45,6 @@ func (o *Client) sendStreamChatCompletions( if stream.Err() == nil { channel <- "\n" } - close(channel) return stream.Err() } diff --git a/plugins/ai/openai/openai.go b/plugins/ai/openai/openai.go index 635999bb..f8ab9329 100644 --- a/plugins/ai/openai/openai.go +++ b/plugins/ai/openai/openai.go @@ -99,6 +99,8 @@ func (o *Client) SendStream( func (o *Client) sendStreamResponses( msgs []*chat.ChatCompletionMessage, opts *common.ChatOptions, channel chan string, ) (err error) { + defer close(channel) + req := o.buildResponseParams(msgs, opts) stream := o.ApiClient.Responses.NewStreaming(context.Background(), req) for stream.Next() { @@ -113,7 +115,6 @@ func (o *Client) sendStreamResponses( if stream.Err() == nil { channel <- "\n" } - close(channel) return stream.Err() }