From 8636b0c842a6251679947ca8b69d3a3ff5809918 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 15 Nov 2025 15:43:57 +0800 Subject: [PATCH] Enhance context cancellation support in OpenAI provider and tests - Added context cancellation handling in the OpenAI provider's Stream and Post methods, allowing for graceful termination of operations when the context is cancelled. - Implemented a new test, TestOpenAIStreamContextCancellation, to validate that streaming respects context cancellation, ensuring proper error handling and event emission during cancellation scenarios. - Refactored context usage in existing methods to improve consistency and reliability in handling context across streaming operations. --- agent/llm/providers/openai/openai.go | 96 +++++++++++++++++++++-- agent/llm/providers/openai/openai_test.go | 87 +++++++++++++++++++- 2 files changed, 174 insertions(+), 9 deletions(-) diff --git a/agent/llm/providers/openai/openai.go b/agent/llm/providers/openai/openai.go index 62d14b52..93917958 100644 --- a/agent/llm/providers/openai/openai.go +++ b/agent/llm/providers/openai/openai.go @@ -121,17 +121,39 @@ func (p *Provider) Stream(ctx *context.Context, messages []context.Message, opti maxValidationRetries := 3 var lastErr error + // Get Go context for cancellation support + goCtx := ctx.Context + if goCtx == nil { + goCtx = gocontext.Background() + } + // Make a copy of messages to avoid modifying the original currentMessages := make([]context.Message, len(messages)) copy(currentMessages, messages) // Outer loop: handle network/API errors with exponential backoff for attempt := 0; attempt < maxRetries; attempt++ { + // Check if context is cancelled before retry + select { + case <-goCtx.Done(): + return nil, fmt.Errorf("context cancelled: %w", goCtx.Err()) + default: + } + if attempt > 0 { // Exponential backoff: 1s, 2s, 4s backoff := time.Duration(1< 0 { // Exponential backoff backoff := time.Duration(1<