Crestapps core resilience

From CrestApps/CrestApps.AgentSkills · View interactive version

Crestapps core resilience is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for retry and resilience middleware on Microsoft.Extensions.AI clients in CrestApps.Core 2.0 with the CrestApps.Core.AI.Resilience package. Covers UseDefaultResilience rate-limit retries and AIChatClientRetryOptions, fully custom Polly pipelines with UseResilience, applying them through IAICli

How to use this skill

Skill file

CrestApps.Core AI Resilience

Builder-based retry middleware for Microsoft.Extensions.AI clients, from the standalone CrestApps.Core.AI.Resilience package.

Guidelines

```xml

<PackageReference Include="CrestApps.Core.AI.Resilience" Version="*" />

```

It depends on Microsoft.Extensions.AI and Microsoft.Extensions.Resilience.

1. Resolve a chat client through IAIClientFactory.CreateChatClientAsync(deployment, configurePipeline). The factory passes a ChatClientBuilder to the callback and owns the final build.

2. Convert a raw client to its builder with .AsBuilder(), apply UseDefaultResilience() or UseResilience(...), then finish with Build(serviceProvider).

Default Policy

UseDefaultResilience() is intentionally narrow. It retries provider rate-limit failures such as HTTP 429 Too Many Requests. Tune it with AIChatClientRetryOptions.

| Setting | Default |

|---|---|

| MaxRateLimitRetries | 5 |

| RateLimitRetryDelay | 1 second |

| BackoffType | DelayBackoffType.Exponential |

| UseJitter | true |

| MaxRetryDelay | 32 seconds |

The default produces an approximate schedule of ~1-2s, ~2-4s, ~4-8s, ~8-16s, ~16-32s across five retries. Actual delays vary because jitter is on.

Chat Example

Through the factory (recommended when the factory creates the client):

var resilientClient = await aiClientFactory.CreateChatClientAsync(
    deployment,
    builder => builder.UseDefaultResilience());

From an existing raw IChatClient:

var resilientClient = chatClient
    .AsBuilder()
    .UseDefaultResilience()
    .Build(serviceProvider);

Customizing the Default Settings

Keep the built-in rate-limit handling but tune the retry shape:

var resilientClient = await aiClientFactory.CreateChatClientAsync(
    deployment,
    builder => builder.UseDefaultResilience(options =>
    {
        options.MaxRateLimitRetries = 3;
        options.RateLimitRetryDelay = TimeSpan.FromSeconds(2);
        options.BackoffType = DelayBackoffType.Exponential;
        options.UseJitter = true;
        options.MaxRetryDelay = TimeSpan.FromSeconds(20);
    }));

For a fixed (non-exponential) schedule:

var resilientClient = chatClient
    .AsBuilder()
    .UseDefaultResilience(options =>
    {
        options.MaxRateLimitRetries = 4;
        options.RateLimitRetryDelay = TimeSpan.FromSeconds(5);
        options.BackoffType = DelayBackoffType.Constant;
        options.UseJitter = false;
        options.MaxRetryDelay = TimeSpan.FromSeconds(5);
    })
    .Build(serviceProvider);

Fully Custom Pipelines

Use UseResilience(...) for full control over the Polly pipeline:

var resilientClient = chatClient
    .AsBuilder()
    .UseResilience(pipeline => pipeline.AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 2,
        Delay = TimeSpan.FromSeconds(1),
        BackoffType = DelayBackoffType.Exponential,
        UseJitter = true,
        ShouldHandle = args => ValueTask.FromResult(
            args.Outcome.Exception is HttpRequestException ex &&
            ex.StatusCode == HttpStatusCode.TooManyRequests),
    }))
    .Build(serviceProvider);

You can also pass a prebuilt ResiliencePipeline to share one pipeline across multiple clients.

Other Client Types

The same UseDefaultResilience() / UseResilience(...) extensions are available on the other builders. Factory and raw-builder forms both work.

// Embeddings
var embeddings = embeddingGenerator.AsBuilder().UseDefaultResilience().Build(serviceProvider);

// Image generation
var images = imageGenerator.AsBuilder().UseDefaultResilience().Build(serviceProvider);

// Speech to text
var stt = speechToTextClient.AsBuilder().UseDefaultResilience().Build(serviceProvider);

// Text to speech
var tts = textToSpeechClient.AsBuilder().UseDefaultResilience().Build(serviceProvider);

Streaming Notes

Telemetry

See crestapps-core-observability for collecting these metrics.

When to Use Which

Combining with Other Middleware

Resilience composes with the other pipeline extensions. Usage metering is applied at the provider client below the whole pipeline, wherever these calls sit:

var client = await aiClientFactory.CreateChatClientAsync(deployment, builder => builder
    .UseDefaultResilience()
    .UseUsageLabels(contextType: "Reports", purpose: "Summary")
    .UseModelParameters(parameterApplier, deployment, completionContext, AIDeploymentParameterScope.Utility));

AIProviderErrorHelper.IsRateLimitException(ex) (used by the default policy) and IsNotFoundException(ex) (a missing model or deployment, such as an Ollama model that was never pulled) help write custom ShouldHandle predicates and error messages.

Upgrading from 1.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.