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<