Skill站外收录 @skilllib/skill-2117939930272411787
langchain-rate-limits
为 LangChain 应用提供弹性请求调控能力,通过内置重试、指数退避、令牌桶限流及异步并发控制等策略,应对大模型服务的配额限制与流量波动,在不中断业务的前提下保障调用稳定性与资源利用率。
数据与分析 AI 技能
Skills.MD
# LangChain Rate Limits
## Overview
Implement robust rate limiting and retry strategies for LangChain applications to handle API quotas gracefully.
## Prerequisites
- LangChain installed with LLM provider
- Understanding of provider rate limits
- tenacity package for advanced retry logic
## Instructions
### Step 1: Understand Provider Limits
```python
# Common rate limits by provider:
RATE_LIMITS = {
"openai": {
"gpt-4o": {"rpm": 10000, "tpm": 800000},
"gpt-4o-mini": {"rpm": 10000, "tpm": 4000000},
},
"anthropic": {
"claude-3-5-sonnet": {"rpm": 4000, "tpm": 400000},
},
"google": {
"gemini-1.5-pro": {"rpm": 360, "tpm": 4000000},
}
}
# rpm = requests per minute, tpm = tokens per minute
```
### Step 2: Built-in Retry Configuration
```python
from langchain_openai import ChatOpenAI
# LangChain has built-in retry with exponential backoff
llm = ChatOpenAI(
model="gpt-4o-mini",
max_retries=3, # Number of retries
request_timeout=30, # Timeout per request
)
```
### Step 3: Advanced Retry with Tenacity
```python
from tenacity import (
retry,
stop_after_attempt,
wait_exponential,
retry_if_exception_type
)
from openai import RateLimitError, APIError
@retry(
stop=stop_after_attempt(5),
wait=wait_exponential(multiplier=1, min=4, max=60),
retry=retry_if_exception_type((RateLimitError, APIError))
)
def call_with_retry(chain, input_data):
"""Call chain with exponential backoff."""
return chain.invoke(input_data)
# Usage
result = call_with_retry(chain, {"input": "Hello"})
```
### Step 4: Rate Limiter Wrapper
```python
import asyncio
import time
from collections import deque
from threading import Lock
class RateLimiter:
"""Token bucket rate limiter for API calls."""
def __init__(self, requests_per_minute: int = 60):
self.rpm = requests_per_minute
self.interval = 60.0 / requests_per_minute
self.timestamps = deque()
self.lock = Lock()
def acquire(self):
"""Block until request can be made."""
with self.lock:
now = time.time()
# Remove timestamps older than 1 minute
while self.timestamps and now - self.timestamps[0] > 60:
self.timestamps.popleft()
if len(self.timestamps) >= self.rpm:
sleep_time = 60 - (now - self.timestamps[0])
if sleep_time > 0:
time.sleep(sleep_time)
self.timestamps.append(time.time())
# Usage with LangChain
rate_limiter = RateLimiter(requests_per_minute=100)
def rate_limited_call(chain, input_data):
rate_limiter.acquire()
return chain.invoke(input_data)
```
### Step 5: Async Rate Limiting
```python
import asyncio
from asyncio import Semaphore
class AsyncRateLimiter:
"""Async rate limiter with semaphore."""
def __init__(self, max_concurrent: int = 10):
self.semaphore = Semaphore(max_concurrent)
async def call(self, chain, input_data):
async with self.semaphore:
return await chain.ainvoke(input_data)
# Batch processing with rate limiting
async def process_batch(chain, inputs: list, max_concurrent: int = 5):
limiter = AsyncRateLimiter(max_concurrent)
tasks = [limiter.call(chain, inp) for inp in inputs]
return await asyncio.gather(*tasks, return_exceptions=True)
```
## Output
- Configured retry logic with exponential backoff
- Rate limiter class for request throttling
- Async batch processing with concurrency control
- Graceful handling of rate limit errors
## Examples
### Handling Rate Limits in Production
```python
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnableConfig
llm = ChatOpenAI(
model="gpt-4o-mini",
max_retries=5,
)
# Use batch with max_concurrency
inputs = [{"input": f"Query {i}"} for i in range(100)]
results = chain.batch(
inputs,
config=RunnableConfig(max_concurrency=10) # Limit concurrent calls
)
```
### Fallback on Rate Limit
```python
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
primary = ChatOpenAI(model="gpt-4o-mini", max_retries=2)
fallback = ChatAnthropic(model="claude-3-5-sonnet-20241022")
# Automatically switch to fallback on rate limit
robust_llm = primary.with_fallbacks([fallback])
```
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| RateLimitError | Exceeded quota | Implement backoff, reduce concurrency |
| Timeout | Request too slow | Increase timeout, check network |
| 429 Too Many Requests | API throttled | Wait and retry with backoff |
| Quota Exceeded | Monthly limit hit | Upgrade plan or switch provider |
## Resources
- [OpenAI Rate Limits](https://platform.openai.com/docs/guides/rate-limits)
- [Anthropic Rate Limits](https://docs.anthropic.com/en/api/rate-limits)
- [tenacity Documentation](https://tenacity.readthedocs.io/)
## Next Steps
Proceed to `langchain-security-basics` for security best practices.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「langchain-rate-limits」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次