Overview
Creates a clean, production-grade client wrapper around one or more AI provider APIs. Covers client class design, retry + exponential backoff with jitter, streaming support, token counting, response parsing/normalization, error classification (rate limit, auth, server, timeout), provider-swappable interface, logging/cost tracking, and a complete, testable implementation (Python example with OpenAI + Anthropic, plus TypeScript notes).
When to Use This Skill
- You are using (or plan to use) one or more LLM APIs and want a consistent interface.
- You need robust error handling, retries, and observability around API calls.
- You want to make it easy to switch providers or add new ones later (multi-LLM strategy).
- Building internal SDKs or agent frameworks that call LLMs.
Prerequisites
- API keys for the provider(s) you will wrap.
- Understanding of the provider's SDK and response shapes.
- (Recommended)
tenacity or backoff for retries in Python; equivalent in TS.
Steps
Design the interface (provider-agnostic where possible):
complete(prompt, model, temperature, max_tokens, **kwargs) -> Response
stream(...) -> Iterator[Chunk]
count_tokens(text, model) -> int
- Common response shape:
text, usage (input/output tokens), model, finish_reason, raw (original response).
Error classification & handling:
- RateLimitError → retry with backoff, respect
retry-after when present.
- AuthenticationError → fail fast, do not retry.
- ServerError / Timeout → retry with jitter.
- ContextLengthExceeded → surface clearly to caller (or auto-truncate with warning).
Retry strategy:
- Exponential backoff + full jitter.
- Max attempts (e.g., 5).
- Distinguish transient vs permanent errors.
Streaming:
- Yield chunks as they arrive.
- Accumulate full text for the final response object when needed.
- Handle partial JSON or tool calls correctly.
Observability:
- Log every request (sanitized) with latency, tokens, cost estimate, error.
- Emit metrics (Prometheus, Datadog, etc.).
- Optional: send traces to LangSmith / Helicone / Phoenix.
Multi-provider:
- Use LiteLLM as a base (strongly recommended for most cases) or build a thin adapter layer.
- Config-driven model routing.
Output:
- Complete
LLMClient class (Python) with the methods above.
- Concrete implementations for OpenAI and Anthropic (or LiteLLM wrapper).
- Retry decorator / context manager.
- Token counter (tiktoken for OpenAI, anthropic tokenizer, or approximate).
- Example usage + tests (pytest or vitest).
- Cost calculator.
Examples
A full LLMClient that supports both OpenAI and Anthropic (via LiteLLM or direct), with robust retries, streaming, token counting, cost logging, and a clean Response dataclass is included, plus a minimal TypeScript equivalent.
Edge Cases & Error Handling
- Very long prompts: Pre-check token count and raise a clear
ContextLengthError before calling the API.
- Partial failures in streaming: Ensure the caller can still get whatever was generated.
- Provider-specific quirks: Document them and normalize in the wrapper.
Verification
- The wrapper can complete a simple prompt with both providers.
- Streaming works and the final accumulated text matches the non-streaming result.
- Token counting is accurate (or close) for the supported models.
- Rate limit simulation triggers retries and eventually succeeds or fails gracefully.
- Auth error fails immediately without retries.
- All calls are logged with token usage and approximate cost.
- Success: Calling code is much simpler and more robust than using the raw SDKs directly, and switching providers is a config change.
References
1---2name: api-wrapper-builder3description: Creates a clean Python/TypeScript wrapper around an external AI API (OpenAI, Anthropic, Google AI, etc.). Use when abstracting an AI provider for easier use, testing, or provider switching.4license: Apache-2.05---67## Overview89Creates a clean, production-grade client wrapper around one or more AI provider APIs. Covers client class design, retry + exponential backoff with jitter, streaming support, token counting, response parsing/normalization, error classification (rate limit, auth, server, timeout), provider-swappable interface, logging/cost tracking, and a complete, testable implementation (Python example with OpenAI + Anthropic, plus TypeScript notes).1011## When to Use This Skill1213- You are using (or plan to use) one or more LLM APIs and want a consistent interface.14- You need robust error handling, retries, and observability around API calls.15- You want to make it easy to switch providers or add new ones later (multi-LLM strategy).16- Building internal SDKs or agent frameworks that call LLMs.1718## Prerequisites1920- API keys for the provider(s) you will wrap.21- Understanding of the provider's SDK and response shapes.22- (Recommended) `tenacity` or `backoff` for retries in Python; equivalent in TS.2324## Steps25261. **Design the interface** (provider-agnostic where possible):27 - `complete(prompt, model, temperature, max_tokens, **kwargs) -> Response`28 - `stream(...) -> Iterator[Chunk]`29 - `count_tokens(text, model) -> int`30 - Common response shape: `text`, `usage` (input/output tokens), `model`, `finish_reason`, `raw` (original response).31322. **Error classification & handling**:33 - RateLimitError → retry with backoff, respect `retry-after` when present.34 - AuthenticationError → fail fast, do not retry.35 - ServerError / Timeout → retry with jitter.36 - ContextLengthExceeded → surface clearly to caller (or auto-truncate with warning).37383. **Retry strategy**:39 - Exponential backoff + full jitter.40 - Max attempts (e.g., 5).41 - Distinguish transient vs permanent errors.42434. **Streaming**:44 - Yield chunks as they arrive.45 - Accumulate full text for the final response object when needed.46 - Handle partial JSON or tool calls correctly.47485. **Observability**:49 - Log every request (sanitized) with latency, tokens, cost estimate, error.50 - Emit metrics (Prometheus, Datadog, etc.).51 - Optional: send traces to LangSmith / Helicone / Phoenix.52536. **Multi-provider**:54 - Use LiteLLM as a base (strongly recommended for most cases) or build a thin adapter layer.55 - Config-driven model routing.56577. **Output**:58 - Complete `LLMClient` class (Python) with the methods above.59 - Concrete implementations for OpenAI and Anthropic (or LiteLLM wrapper).60 - Retry decorator / context manager.61 - Token counter (tiktoken for OpenAI, anthropic tokenizer, or approximate).62 - Example usage + tests (pytest or vitest).63 - Cost calculator.6465## Examples6667A full `LLMClient` that supports both OpenAI and Anthropic (via LiteLLM or direct), with robust retries, streaming, token counting, cost logging, and a clean `Response` dataclass is included, plus a minimal TypeScript equivalent.6869## Edge Cases & Error Handling7071- **Very long prompts**: Pre-check token count and raise a clear `ContextLengthError` before calling the API.72- **Partial failures in streaming**: Ensure the caller can still get whatever was generated.73- **Provider-specific quirks**: Document them and normalize in the wrapper.7475## Verification76771. The wrapper can complete a simple prompt with both providers.782. Streaming works and the final accumulated text matches the non-streaming result.793. Token counting is accurate (or close) for the supported models.804. Rate limit simulation triggers retries and eventually succeeds or fails gracefully.815. Auth error fails immediately without retries.826. All calls are logged with token usage and approximate cost.837. Success: Calling code is much simpler and more robust than using the raw SDKs directly, and switching providers is a config change.8485## References8687- [OpenAI Python SDK](https://github.com/openai/openai-python)88- [Anthropic Python SDK](https://github.com/anthropics/anthropic-sdk-python)89- [LiteLLM](https://github.com/BerriAI/litellm) (highly recommended base)90- [Tenacity](https://tenacity.readthedocs.io/) (retry library)91- [tiktoken](https://github.com/openai/tiktoken)