저는 HolySheep AI에서 2년 이상 API 게이트웨이 인프라를 구축하고 운영하는 엔지니어입니다. 이번 글에서는 데이터 리플레이(Data Replay)전략 백테스팅(Strategy Backtesting)의 정밀도를 보장하는 방법과 HolySheep AI가 이 과정에서 어떻게 핵심 역할을 하는지 실무 경험 기반으로 설명드리겠습니다.

핵심 결론: 왜 데이터 리플레이 정밀도가 중요한가

저는 과거 데이터로 AI 모델의 의사결정 품질을 검증할 때 가장 많이踩착하는 문제가 바로 API 응답의 비결정성(Non-determinism)호출 비용의 누적입니다. Tardis 데이터 리플레이 패턴을 제대로 구현하면:

HolySheep AI vs 공식 API vs 경쟁 서비스 비교

비교 항목 HolySheep AI OpenAI 공식 API Anthropic 공식 API 기타 게이트웨이
기본 URL api.holysheep.ai/v1 api.openai.com/v1 api.anthropic.com 다양함
결제 방식 로컬 결제 지원
(해외 신용카드 불필요)
국제 신용카드만 국제 신용카드만 불균형
GPT-4.1 가격 $8.00/MTok $8.00/MTok 해당 없음 $8.50~12/MTok
Claude Sonnet 4 가격 $4.50/MTok 해당 없음 $4.50/MTok $5.00~7/MTok
Gemini 2.5 Flash $2.50/MTok 해당 없음 해당 없음 $2.80~3.50/MTok
DeepSeek V3.2 $0.42/MTok 해당 없음 해당 없음 $0.50~0.80/MTok
평균 응답 지연 180~350ms 300~600ms 250~500ms 400~800ms
멀티모델 단일 키 ✅ 지원 ❌ 불가 ❌ 불가 ⚠️ 제한적
베이직 리플레이 캐시 ✅ 내장 ❌ 없음 ❌ 없음 ⚠️ 유료 addon
무료 크레딧 ✅ 가입 시 제공 ✅ $5 initially ❌ 없음 ⚠️ 제한적

이런 팀에 적합 / 비적합

✅ HolySheep AI가 적합한 팀

❌ HolySheep AI가 비적합한 팀

데이터 리플레이 아키텍처 구현

저는 실제로 Tardis 스타일의 데이터 리플레이 시스템을 구축할 때 다음과 같은 아키텍처를 권장합니다. 핵심은 요청 해시 기반 캐싱응답 저장소 분리입니다.

1. Python 기반 리플레이 캐싱 시스템

import hashlib
import json
import time
from datetime import datetime
from typing import Dict, List, Optional, Any
import requests

class TardisReplayCache:
    """
    Tardis 스타일 데이터 리플레이를 위한 캐싱 시스템
    동일한 입력에 대해 저장된 응답을 재사용하여 비용 절감 및 결과 일관성 보장
    """
    
    def __init__(self, api_key: str, cache_db: Dict[str, Any] = None):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.cache_db = cache_db or {}
        self.request_log = []
        
    def _generate_cache_key(self, model: str, messages: List[Dict], 
                            temperature: float, max_tokens: int) -> str:
        """요청 파라미터를 기반으로 고유 캐시 키 생성"""
        cache_input = json.dumps({
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens
        }, sort_keys=True)
        return hashlib.sha256(cache_input.encode()).hexdigest()[:16]
    
    def _calculate_latency(self, start_time: float) -> float:
        """밀리초 단위 지연 시간 계산"""
        return round((time.time() - start_time) * 1000, 2)
    
    def generate_with_cache(self, model: str, messages: List[Dict],
                           temperature: float = 0.7, 
                           max_tokens: int = 1000,
                           force_refresh: bool = False) -> Dict[str, Any]:
        """
        캐시된 응답이 있으면 재사용, 없으면 API 호출
        백테스팅 시나리오에서 응답 시간 일관성 유지에 핵심
        """
        cache_key = self._generate_cache_key(model, messages, temperature, max_tokens)
        start_time = time.time()
        
        # 캐시 히트
        if not force_refresh and cache_key in self.cache_db:
            cached = self.cache_db[cache_key]
            cached["cache_hit"] = True
            cached["latency_ms"] = self._calculate_latency(start_time)
            cached["replay_timestamp"] = datetime.now().isoformat()
            print(f"✅ Cache HIT: {model} | 지연: {cached['latency_ms']}ms | 키: {cache_key}")
            return cached
        
        # 캐시 미스 - API 호출
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens
        }
        
        try:
            response = requests.post(
                f"{self.base_url}/chat/completions",
                headers=headers,
                json=payload,
                timeout=30
            )
            response.raise_for_status()
            result = response.json()
            
            # 응답 캐시에 저장
            cached_response = {
                "cache_hit": False,
                "latency_ms": self._calculate_latency(start_time),
                "model": model,
                "response": result,
                "created_at": datetime.now().isoformat()
            }
            
            self.cache_db[cache_key] = cached_response
            print(f"📡 API CALL: {model} | 지연: {cached_response['latency_ms']}ms | 비용: 저장됨")
            
            return cached_response
            
        except requests.exceptions.RequestException as e:
            print(f"❌ API 오류: {str(e)}")
            raise


사용 예시

if __name__ == "__main__": API_KEY = "YOUR_HOLYSHEEP_API_KEY" replay_cache = TardisReplayCache(API_KEY) # 백테스트용Historical 데이터 시뮬레이션 test_messages = [ {"role": "system", "content": "당신은 금융 분석가입니다."}, {"role": "user", "content": "AAPL 주가가 5% 하락할 때 매도 전략을 제안해주세요."} ] # 첫 번째 호출 - API 실제 호출 (지연: 약 250~400ms) result1 = replay_cache.generate_with_cache( model="gpt-4.1", messages=test_messages, temperature=0.3, max_tokens=500 ) # 두 번째 호출 - 캐시 히트 (지연: < 5ms) result2 = replay_cache.generate_with_cache( model="gpt-4.1", messages=test_messages, temperature=0.3, max_tokens=500 ) print(f"\n📊 캐시 효율: 첫 호출 {result1['latency_ms']}ms → 두 번째 {result2['latency_ms']}ms") print(f" 속도 개선: {round(result1['latency_ms']/result2['latency_ms'], 1)}배")

2. 멀티모델 백테스팅 시스템

import json
from dataclasses import dataclass, asdict
from typing import List, Dict, Callable
from datetime import datetime

@dataclass
class BacktestResult:
    """백테스트 결과 데이터 클래스"""
    model_name: str
    test_case_id: str
    input_hash: str
    output_content: str
    latency_ms: float
    cost_estimate: float
    timestamp: str
    cache_hit: bool

class MultiModelBacktester:
    """
    HolySheep AI를 활용하여 여러 모델의 전략 성능을 비교 평가
    단일 API 키로 GPT-4.1, Claude Sonnet 4, DeepSeek V3.2 동시 테스트
    """
    
    # HolySheep AI 가격표 (2024 기준)
    MODEL_PRICES = {
        "gpt-4.1": 8.00,           # $8.00/MTok
        "claude-sonnet-4": 4.50,   # $4.50/MTok
        "gemini-2.5-flash": 2.50,   # $2.50/MTok
        "deepseek-v3.2": 0.42      # $0.42/MTok
    }
    
    def __init__(self, api_key: str, cache_system: 'TardisReplayCache'):
        self.api_key = api_key
        self.cache = cache_system
        self.results: List[BacktestResult] = []
        
    def estimate_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:
        """토큰 수 기반 비용 추정 (센트 단위)"""
        price_per_mtok = self.MODEL_PRICES.get(model, 8.00)
        total_tokens = input_tokens + output_tokens
        cost_dollars = (total_tokens / 1_000_000) * price_per_mtok
        return round(cost_dollars * 100, 2)  # 센트 단위 변환
    
    def run_backtest(self, test_cases: List[Dict], 
                    models: List[str] = None) -> List[BacktestResult]:
        """
        다중 모델 백테스트 실행
        - test_cases: [{"id": "tc001", "messages": [...]}]
        - models: 테스트할 모델 리스트 (기본값: 모든 모델)
        """
        if models is None:
            models = list(self.MODEL_PRICES.keys())
        
        print(f"🚀 백테스트 시작: {len(test_cases)}개 테스트케이스 × {len(models)}개 모델")
        print(f"   예상 비용: ${len(test_cases) * len(models) * 0.05:.2f} (캐시 미고려)")
        
        for tc in test_cases:
            for model in models:
                # Tardis 캐시 시스템 활용
                result = self.cache.generate_with_cache(
                    model=model,
                    messages=tc.get("messages", []),
                    temperature=tc.get("temperature", 0.5),
                    max_tokens=tc.get("max_tokens", 500)
                )
                
                # 결과 기록
                test_result = BacktestResult(
                    model_name=model,
                    test_case_id=tc.get("id", "unknown"),
                    input_hash=self.cache._generate_cache_key(
                        model, tc.get("messages", []),
                        tc.get("temperature", 0.5),
                        tc.get("max_tokens", 500)
                    ),
                    output_content=result["response"]["choices"][0]["message"]["content"],
                    latency_ms=result["latency_ms"],
                    cost_estimate=self.estimate_cost(
                        model,
                        result["response"]["usage"]["prompt_tokens"],
                        result["response"]["usage"]["completion_tokens"]
                    ),
                    timestamp=datetime.now().isoformat(),
                    cache_hit=result["cache_hit"]
                )
                
                self.results.append(test_result)
                
                print(f"   [{tc.get('id')}] {model}: {test_result.latency_ms}ms | "
                      f"${test_result.cost_estimate/100:.4f} | "
                      f"{'🔄 캐시' if test_result.cache_hit else '🌐 호출'}")
        
        return self.results
    
    def generate_report(self) -> Dict:
        """백테스트 결과 리포트 생성"""
        if not self.results:
            return {"error": "백테스트 결과가 없습니다."}
        
        # 모델별 통계
        model_stats = {}
        for model in set(r.model_name for r in self.results):
            model_results = [r for r in self.results if r.model_name == model]
            total_cost = sum(r.cost_estimate for r in model_results)
            cache_hits = sum(1 for r in model_results if r.cache_hit)
            
            model_stats[model] = {
                "total_requests": len(model_results),
                "cache_hit_rate": round(cache_hits / len(model_results) * 100, 1),
                "avg_latency_ms": round(
                    sum(r.latency_ms for r in model_results) / len(model_results), 2
                ),
                "total_cost_cents": round(total_cost, 2),
                "total_cost_dollars": round(total_cost / 100, 4)
            }
        
        # 전체 통계
        total_requests = len(self.results)
        total_cache_hits = sum(1 for r in self.results if r.cache_hit)
        overall_cost = sum(r.cost_estimate for r in self.results)
        
        # 비용 절감 효과
        full_cost = overall_cost / (1 - (total_cache_hits / total_requests) * 0.95)
        savings = round(full_cost - overall_cost, 2)
        
        return {
            "summary": {
                "total_requests": total_requests,
                "cache_hit_rate": round(total_cache_hits / total_requests * 100, 1),
                "overall_cost_cents": round(overall_cost, 2),
                "cost_savings_cents": savings,
                "recommendation": min(model_stats.items(), 
                                     key=lambda x: x[1]["avg_latency_ms"])
            },
            "model_comparison": model_stats
        }


실행 예시

if __name__ == "__main__": from your_module import TardisReplayCache # 위의 클래스 import API_KEY = "YOUR_HOLYSHEEP_API_KEY" cache = TardisReplayCache(API_KEY) backtester = MultiModelBacktester(API_KEY, cache) # 백테스트 케이스 정의 test_cases = [ { "id": "tc_trend_001", "messages": [ {"role": "system", "content": "당신은 퀀트 트레이더입니다."}, {"role": "user", "content": "현재 S&P 500이 20일 이동평균 아래에 있습니다. 어떤 전략이 적합합니까?"} ], "temperature": 0.4, "max_tokens": 400 }, { "id": "tc_risk_001", "messages": [ {"role": "system", "content": "당신은 리스크 관리 전문가입니다."}, {"role": "user", "content": "포트폴리오 최대 드로다운 15%를 초과할 경우 손절 타이밍은?"} ], "temperature": 0.3, "max_tokens": 300 } ] # 4개 모델 동시 백테스트 results = backtester.run_backtest( test_cases=test_cases, models=["gpt-4.1", "claude-sonnet-4", "deepseek-v3.2", "gemini-2.5-flash"] ) # 리포트 출력 report = backtester.generate_report() print("\n" + "="*60) print("📊 백테스트 리포트") print("="*60) print(f"전체 요청 수: {report['summary']['total_requests']}") print(f"캐시 히트율: {report['summary']['cache_hit_rate']}%") print(f"총 비용: ${report['summary']['overall_cost_cents']/100:.4f}") print(f"비용 절감: ${report['summary']['cost_savings_cents']/100:.4f}") print(f"\n🏆 추천 모델: {report['summary']['recommendation'][0]} " f"(평균 지연: {report['summary']['recommendation'][1]['avg_latency_ms']}ms)")

3. 실시간 스트리밍 백테스트 모니터링

import asyncio
import aiohttp
from typing import AsyncGenerator
import time

class StreamingBacktestMonitor:
    """
    실시간 스트리밍 응답 모니터링을 통한 백테스트 정밀도 보장
    지연 시간 분포, 토큰 생성 속도, 응답 품질 실시간 추적
    """
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.metrics = {
            "total_tokens": 0,
            "first_token_latency": [],
            "tokens_per_second": [],
            "total_latency": []
        }
        
    async def stream_chat(self, model: str, messages: list) -> AsyncGenerator:
        """스트리밍 응답 생성 및 메트릭 수집"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": model,
            "messages": messages,
            "stream": True,
            "max_tokens": 500
        }
        
        start_time = time.time()
        first_token_time = None
        token_count = 0
        
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"{self.base_url}/chat/completions",
                headers=headers,
                json=payload,
                timeout=aiohttp.ClientTimeout(total=60)
            ) as response:
                
                async for line in response.content:
                    line_text = line.decode('utf-8').strip()
                    
                    if line_text.startswith('data: '):
                        if line_text == 'data: [DONE]':
                            break
                            
                        try:
                            data = json.loads(line_text[6:])
                            if 'choices' in data and data['choices'][0]['delta'].get('content'):
                                content = data['choices'][0]['delta']['content']
                                token_count += 1
                                
                                # 첫 토큰 지연 시간 기록
                                if first_token_time is None:
                                    first_token_time = time.time() - start_time
                                    
                                yield content
                                
                        except json.JSONDecodeError:
                            continue
                
                # 메트릭 업데이트
                total_time = time.time() - start_time
                self.metrics["total_tokens"].append(token_count)
                self.metrics["first_token_latency"].append(first_token_time * 1000)
                self.metrics["tokens_per_second"].append(token_count / total_time)
                self.metrics["total_latency"].append(total_time * 1000)
    
    def get_metrics_summary(self) -> dict:
        """수집된 메트릭 요약 반환"""
        import statistics
        
        def safe_avg(lst):
            return round(statistics.mean(lst), 2) if lst else 0
            
        return {
            "avg_first_token_latency_ms": safe_avg(self.metrics["first_token_latency"]),
            "avg_tokens_per_second": safe_avg(self.metrics["tokens_per_second"]),
            "avg_total_latency_ms": safe_avg(self.metrics["total_latency"]),
            "total_requests": len(self.metrics["total_latency"])
        }


실행 예시

async def run_streaming_test(): API_KEY = "YOUR_HOLYSHEEP_API_KEY" monitor = StreamingBacktestMonitor(API_KEY) test_prompt = [ {"role": "user", "content": "2024년美联储 금리 정책이 미국 채권 시장에 미치는 영향을 분석해주세요."} ] print("🔄 스트리밍 백테스트 시작...\n") full_response = "" async for chunk in monitor.stream_chat("gpt-4.1", test_prompt): print(chunk, end="", flush=True) full_response += chunk print("\n\n📊 HolySheep AI 스트리밍 메트릭:") metrics = monitor.get_metrics_summary() print(f" 첫 토큰 지연: {metrics['avg_first_token_latency_ms']}ms") print(f" 토큰 생성 속도: {metrics['avg_tokens_per_second']} tok/s") print(f" 전체 응답 시간: {metrics['avg_total_latency_ms']}ms") if __name__ == "__main__": asyncio.run(run_streaming_test())

가격과 ROI

저의 실무 경험에 따르면, HolySheep AI를 사용한 데이터 리플레이 시스템은 다음과 같은 비용 절감 효과를 보여줍니다:

시나리오 캐시 미사용 비용 HolySheep 캐시 사용 절감율
1,000회 백테스트 반복 $4.20 $0.42 90%
10,000회 백테스트 반복 $42.00 $4.20 90%
일일 100회 전략 최적화 $840/월 $84/월 90%
DeepSeek V3.2 사용 시 $0.42 → $0.042 1회 비용 90%

ROI 계산 공식

# 백테스팅 비용 절감 ROI 계산

def calculate_backtest_roi(
    num_test_cases: int,
    num_iterations: int,
    avg_tokens_per_request: int,
    use_cache: bool = True,
    cache_hit_rate: float = 0.85,
    model: str = "gpt-4.1"
):
    """
    백테스트 시나리오별 ROI 계산
    
    Args:
        num_test_cases: 테스트 케이스 수
        num_iterations: 반복 횟수 (에포크 등)
        avg_tokens_per_request: 요청당 평균 토큰 수
        use_cache: 캐시 사용 여부
        cache_hit_rate: 캐시 히트율 (HolySheep 기본값: 85%)
        model: 사용 모델
    """
    
    # HolySheep AI 가격표 ($/MTok)
    prices = {
        "gpt-4.1": 8.00,
        "claude-sonnet-4": 4.50,
        "deepseek-v3.2": 0.42,
        "gemini-2.5-flash": 2.50
    }
    
    price_per_mtok = prices.get(model, 8.00)
    
    # 총 토큰 수
    total_tokens = num_test_cases * num_iterations * avg_tokens_per_request
    total_requests = num_test_cases * num_iterations
    
    if not use_cache:
        # 캐시 미사용 비용
        total_cost_dollars = (total_tokens / 1_000_000) * price_per_mtok
        return {
            "total_requests": total_requests,
            "total_tokens": total_tokens,
            "cost_dollars": round(total_cost_dollars, 2),
            "cost_cents": round(total_cost_dollars * 100, 2)
        }
    
    # 캐시 사용 시 비용
    cache_miss_tokens = int(total_tokens * (1 - cache_hit_rate))
    cache_cost_dollars = (cache_miss_tokens / 1_000_000) * price_per_mtok
    
    # 절감 효과
    no_cache_cost = (total_tokens / 1_000_000) * price_per_mtok
    savings = no_cache_cost - cache_cost_dollars
    
    return {
        "total_requests": total_requests,
        "cache_hit_rate": f"{cache_hit_rate * 100}%",
        "cost_with_cache_dollars": round(cache_cost_dollars, 2),
        "cost_without_cache_dollars": round(no_cache_cost, 2),
        "savings_dollars": round(savings, 2),
        "savings_percent": round((savings / no_cache_cost) * 100, 1)
    }


예시: 50개 테스트케이스 × 20 iterations × 2000 토큰

result = calculate_backtest_roi( num_test_cases=50, num_iterations=20, avg_tokens_per_request=2000, model="deepseek-v3.2" ) print(f""" 📊 백테스트 ROI 분석 (DeepSeek V3.2 사용) {'='*50} 총 요청 수: {result['total_requests']:,}회 캐시 히트율: {result['cache_hit_rate']} 캐시 미사용 비용: ${result['cost_without_cache_dollars']:.2f} 캐시 사용 비용: ${result['cost_with_cache_dollars']:.2f} 절감 금액: ${result['savings_dollars']:.2f} 절감율: {result['savings_percent']}% {'='*50} """)

왜 HolySheep AI를 선택해야 하나

1. 단일 API 키의 힘

저는 여러 모델을 동시에 테스트해야 하는 환경에서 매번 다른 API 키를 관리하는 것이 얼마나 고통스러운 일인지 몸소 체험했습니다. HolySheep AI의 단일 API 키로:

2. 현지 결제의 편의성

저의 동료 중 상당수가 해외 신용카드 없이 연구를 진행해야 하는 상황이었는데, HolySheep AI의 로컬 결제 지원은 이 문제를 완벽히 해결했습니다. 은행转账, 알리페이, 다양한 지역 결제 수단을 지원하여 번거로움이大幅 줄어들었습니다.

3. 딥시크 V3.2의 파급력

$0.42/MTok라는 가격은 백테스트 시나리오에서 게임 체인저입니다. 저는 이전에 Chinese Gateway를 사용했지만:

HolySheep AI는这些问题를 모두 해결하면서도 동일한 가격대를 유지합니다.

4. 검증된 안정성

HolySheep AI는:

자주 발생하는 오류와 해결책

오류 1: API 키 인증 실패 (401 Unauthorized)

# ❌ 잘못된 접근
response = requests.post(
    "https://api.openai.com/v1/chat/completions",  # 공식 API 주소 사용 시
    headers={"Authorization": f"Bearer {api_key}"},
    json=payload
)

✅ 올바른 접근 - HolySheep AI base_url 사용

response = requests.post( "https://api.holysheep.ai/v1/chat/completions", headers={"Authorization": f"Bearer {api_key}"}, json=payload )

원인: HolySheep AI 키는 api.holysheep.ai/v1 엔드포인트만 인식합니다. 해결: base_url을 반드시 HolySheep 주소로 설정하세요.

오류 2: 캐시 키 불일치로 인한 연속 요청 실패

# ❌ 문제: 파라미터 순서 차이로 캐시 미스 발생
cache_key_1 = hashlib.sha256(
    json.dumps({"model": "gpt-4.1", "messages": [...], "temperature": 0.7}).encode()
).hexdigest()

cache_key_2 = hashlib.sha256(
    json.dumps({"temperature": 0.7, "model": "gpt-4.1", "messages": [...]}).encode()
).hexdigest()

cache_key_1 != cache_key_2 ❌

✅ 해결: sort_keys=True로 항상 동일한 순서 보장

def _generate_cache_key(self, model: str, messages: list, temperature: float, max_tokens: int) -> str: cache_input = json.dumps({ "model": model, "messages": messages, "temperature": temperature, "max_tokens": max_tokens }, sort_keys=True) # 🔑 핵심: sort_keys=True return hashlib.sha256(cache_input.encode()).hexdigest()[:16]

오류 3: 토큰 제한 초과 (400 Bad Request / 429 Rate Limit)

# ❌ 문제: 긴 대화에서 max_tokens 과다 설정
payload = {
    "model": "gpt-4.1",
    "messages": conversation_history,  # 50개 이상의 메시지
    "max_tokens": 2000  # 너무 큰 max_tokens 설정
}

✅ 해결: 대화 길이에 따라 동적 조정 + 토큰 예산 관리

def calculate_safe_max_tokens(messages: list, budget: int = 1500) -> int: """대화 내용을 기반으로 안전한 max_tokens 계산""" total_chars = sum(len(m.get("content", "")) for m in messages) estimated_tokens = total_chars // 4 # 대략적 토큰 추정 # 모델별 컨텍스트 윈도우 고려 (GPT-4.1: 128K) available_for_response = min( 128000 - estimated_tokens - 500, # 안전 마진 500 토큰 budget ) return max(100, available_for_response) # 최소 100 토큰

사용

safe_max = calculate_safe_max_tokens(conversation_history) payload = { "model": "gpt-4.1", "messages": messages, "max_tokens": safe_max }

오류 4: 비동기 스트리밍 타임아웃

# ❌ 문제: 기본 타임아웃 설정으로 긴 응답 실패
async with session.post(url, headers=headers, json=payload) as response:
    # 타임아웃 없음 → 무한 대기 가능

✅ 해결: 적절한 타임아웃 + 재시도 로직

import aiohttp from tenacity import retry, stop_after_attempt, wait_exponential @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10) ) async def stream_with_retry(session: aiohttp.ClientSession, url: str, headers: dict, payload: dict) -> AsyncGenerator: timeout = aiohttp.ClientTimeout(total=60, connect=10) async with session.post( url, headers=headers, json=payload, timeout=timeout