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
This commit is contained in:
Kayvan Sylvan
2025-06-29 23:27:24 -07:00
parent 6179742e79
commit 66925d188a
2 changed files with 4 additions and 2 deletions

View File

@@ -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()
}

View File

@@ -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()
}