Skip to content

Honor retry-after and related headers #169

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .dotnet/src/Custom/OpenAIClientOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ namespace OpenAI;
[CodeGenModel("OpenAIClientOptions")]
public partial class OpenAIClientOptions : ClientPipelineOptions
{
public OpenAIClientOptions()
{
RetryPolicy = new HeaderInformedRetryPolicy();
}

/// <summary>
/// A non-default base endpoint that clients should use when connecting.
/// </summary>
Expand All @@ -28,4 +33,32 @@ public partial class OpenAIClientOptions : ClientPipelineOptions
/// An optional ID added to OpenAI-Project header
/// </summary>
public string ProjectId { get; init; }

private class HeaderInformedRetryPolicy : ClientRetryPolicy
{
protected override TimeSpan GetNextDelay(PipelineMessage message, int tryCount)
{
TimeSpan? TryGetTimeSpanFromHeader(string headerName, int millisecondsPerValue = 1, bool allowDateTimeOffset = false)
{
if (double.TryParse(
message?.Response?.Headers?.TryGetValue(headerName, out string textValue) == true ? textValue : null,
out double doubleValue) == true)
{
return TimeSpan.FromMilliseconds(millisecondsPerValue * doubleValue);
}
else if (allowDateTimeOffset && DateTimeOffset.TryParse(headerName, out DateTimeOffset delayUntil))
{
return delayUntil - DateTimeOffset.Now;
}
return null;
}

TimeSpan? delayFromHeader =
TryGetTimeSpanFromHeader("retry-after-ms")
?? TryGetTimeSpanFromHeader("x-ms-retry-after-ms")
?? TryGetTimeSpanFromHeader("Retry-After", millisecondsPerValue: 1000, allowDateTimeOffset: true);

return delayFromHeader ?? base.GetNextDelay(message, tryCount);
}
}
}
Loading