0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Claude SDKの二重リトライ、送信9件が3件になった

0
Posted at

3回のループから、送信が9件出た。ClaudeのPython SDKに429を返すモックを作り、今日、手元で数えた。

自分は再実行のコードを確認してて、外側の回数だけではログが足りないな、と感じた。SDK内の再試行も数えたい。

外側3回、SDKの内側も3回

検証環境はmacOS、CPython 3.12.13、anthropic==0.102.0、httpx==0.28.1。MockTransportで毎回429を返す。実APIへの接続はない。

max_retriesは「最初の送信を除く再試行回数」。既定値2なら、1回のmessages.create()で最大3件送る。全回が再試行対象のエラーなら、外側3回と掛け合わさって9件になる。

RateLimitErrorを受け取った時点で、SDKは再試行を使い切っている。ループを続けると、新しいSDK呼び出しとして再び最大3件が走る。

外側の試行3回に対し、SDKの再試行が2回なら各試行で3件ずつ合計9件、再試行が0回なら1件ずつ合計3件をモックへ送信する流れ。

モックで送信を数える

SDKが送信時に付けるx-stainless-retry-countを記録する。modelもAPIキーもダミー。認証情報は不要だ。

import httpx
from anthropic import Anthropic, RateLimitError

def probe(retries):
    sent = []

    def reply(request):
        sent.append(request.headers['x-stainless-retry-count'])
        return httpx.Response(
            429, headers={'retry-after-ms': '1'},
            json={'type': 'error', 'error': {
                'type': 'rate_limit_error', 'message': 'mock 429'}},
        )

    with Anthropic(
        api_key='dummy', max_retries=retries,
        base_url='https://example.invalid',
        http_client=httpx.Client(transport=httpx.MockTransport(reply)),
    ) as client:
        for _ in range(3):
            try:
                client.messages.create(
                    model='mock-model', max_tokens=1,
                    messages=[{'role': 'user', 'content': 'ping'}],
                )
                break
            except RateLimitError:
                pass
    return len(sent), ','.join(sent)

for retries in (2, 0):
    count, trace = probe(retries)
    print(f'max_retries={retries}: {count}件 / {trace}')
max_retries=2: 9件 / 0,1,2,0,1,2,0,1,2
max_retries=0: 3件 / 0,0,0

0,1,2が3組並ぶ。例外を捕まえて再び呼ぶと、番号が0へ戻った。x-stainless-retry-count、ログの列名としてはさすがに長い。

SDKの実装を読む

同梱ソースも読んだ。_constants.pyにDEFAULT_MAX_RETRIES = 2があり、_base_client.pyではrange(max_retries + 1)で送信する。429も再試行対象だった。

retry-after-ms: 1でSDK内の待機を1ミリ秒にした。この版では、指定された正の待機時間が60秒以下ならその値を使う。

常に429なので9件まで進む。途中の成功や再試行抑止ヘッダーで件数は変わる。今回はモックへの送信件数を数えた。モデルの実行回数や課金額は測っていない。

再試行をどこで持つか

外側で再試行を管理するなら、SDKのmax_retries=0と組み合わせ、待機や打ち切りも外側で扱う。このコードは外側の待機を省いたので、本番の429対応にはRetry-Afterの扱いやバックオフを足す。単発なら、外側のループを外してSDKに任せる方法もある。ゲートウェイにも再試行を足す構成では、ジョブ回数と送信件数を並べたログが、負荷を調べる入口になりそうだ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?