anthropic-sdk-python

Currently trending because

  • Long-running Claude agents that hit a tool-use or compaction limit now get distinct error types in the Python SDK, so code can tell which limit stopped the run. [1]

Activity, over time

Daily observations from the public event archive.

Attention

Daily stars & forks

Loading attention chart

Star accumulation

Cumulative stars

Loading star accumulation chart

Pull requests

Daily opens & merges

Loading pull requests chart

Conversations

Daily issues & comments

Loading conversations chart

Community

Daily accounts & reviews

Loading community chart

Releases

Daily releases

Loading releases chart

Mentions

27posts · 30d
Nov 30 posts
  1. if you run agents on claude, this one's in a release note, not a launch post v2.4.0 of the python sdk adds tool_use_limit_reached_error and compaction_limit_reached_error two annoying ways a long agent run stops. now each one has its own error type github.com/anthropics/anthropic-sdk-python/releas…

    28 views
  2. DEV · · @rihpig

    Claude Batch API: 비동기 작업을 절반 비용으로 실행하는 방법 --- title: "Claude Batch API: 비동기 작업을 절반 비용으로 실행하는 방법" description: "한 번의 호출로 최대 100,000개의 Claude 요청을 제출하고, 입력과 출력에 대해 절반 가격을 지불하며, 자신만의 custom_id를 키로 결과를 수집하세요. 다음은 전체 라이프사이클과, 확장하기 전에 테스트하는 방법입니다." canonical_url: "apidog.com" cover_image: "assets.apidog.com" --- 빠른 답변: Claude Batch API는 Messages API 요청을 비동기적으로 처리하며 입력과 출력 토큰 모두 50% 할인된 가격을 적용합니다. 한 번의 호출로 최대 100,000건의 요청(또는 256MB)을 제출하고, 배치가 끝날 때까지 폴링한 다음, 자신의 custom_id를 키로 결과를 읽습니다. 대부분의 배치는 1시간 이내에 완료되며, 최대 한도는 24시간입니다. {% cta apidog.com %} 지금 Apidog 사용해 보기 {% endcta %} 분류해야 할 지원 티켓 40,000건이 있거나, 다시 작성해야 할 제품 카탈로그가 있거나, 요약해야 할 한 달치 녹취록이 있습니다. 그중 급한 것은 아무것도 없습니다. 하지만 그 호출을 하나씩 실행하면 모두 정가로 청구되며, 오후 내내 속도 제한에 걸린 재시도를 감시하며 보내게 됩니다. Claude Batch API는 바로 이런 형태의 작업을 위해 존재합니다. Anthropic에 요청 목록을 넘기고 자리를 뜨면, 동일한 호출을 동기식으로 실행했을 때의 절반 비용이 드는 결과 파일을 받게 됩니다. 운영할 큐도, 동시성 튜닝도, 백오프 로직도 필요 없습니다. 이 가이드에서는 배치 엔드포인트가 하는 일, 비용, 작업을 제출하고 수집하는 방법, 그리고 실제 데이터에 적용하기 전에 코딩 에이전트가 Apidog CLI로 전체 과정을 테스트하게 하는 방법을 다룹니다. Claude Batch API란 무엇인가요? Claude Batch API는 /v1/messages/batches에 위치한 비동기 엔드포인트로, 여러 Messages API 요청을 한 번의 제출로 받아 처리가 끝나면 그 결과를 반환합니다. 지연 시간을 대가로 50% 할인을 제공합니다. Anthropic은 이를 배치 처리 문서에서 설명합니다. 설계할 때 고려해야 할 제약 사항은 다음과 같습니다. - 크기: 배치당 최대 100,000건의 요청 또는 256MB 중 먼저 도달하는 한도까지. - 시간: 대부분의 배치는 1시간 이내에 완료되며, 완료되지 않은 요청이 만료되기까지의 최대 시간은 24시간입니다. - 보존: 결과는 배치가 생성된 후 29일 동안 사용할 수 있습니다. - 기능 동등성: 비전, 도구 사용, 시스템 프롬프트, 프롬프트 캐싱이 모두 배치 안에서 작동합니다. - 순서: 결과는 임의의 순서로 반환되므로 위치가 아니라 custom_id를 키로 사용해야 합니다. 마지막 항목이 사람들을 당황하게 만드는 부분입니다. 배치는 큐가 아니라 주머니입니다. Claude Batch API 비용 할인은 입력과 출력 토큰 모두에 50% 정액으로 적용되며, 각 요청이 지정한 모델에 그대로 적용됩니다. 하나의 배치 안에서 모델을 섞을 수 있으므로 저렴한 분류기와 비싼 요약기를 함께 태울 수 있습니다. !Claude Batch API vs standard pricing: output price per million tokens for Opus 5.5, Sonnet 5.5 and Haiku 5.5 | 모델 | 표준 입력 / 출력 (MTok당) | 배치 입력 / 출력 (MTok당) | | --- | --- | --- | | Claude Opus 5.5 | $4.00 / $20.00 | $2.00 / $10.00 | | Claude Sonnet 5.5 | $2.00 / $10.00 | $1.00 / $5.00 | | Claude Haiku 5.5 (프롬프트 최대 100K) | $0.10 / $0.50 | $0.05 / $0.25 | | Claude Haiku 5.5 (프롬프트 100K 초과) | $0.50 / $2.50 | $0.25 / $1.25 | Haiku 행을 주의 깊게 보세요. Haiku 5.5는 프롬프트 크기로 가격을 책정하므로, 하나의 프롬프트가 100,000 토큰을 넘으면 배치 할인 여부와 관계없이 짧은 프롬프트 요율의 5배가 청구됩니다. 장문 컨텍스트 Haiku 작업은 $0.05 / $0.25가 아니라 $0.25 / $1.25로 예측하세요. 이 수치를 바탕으로 예측을 세우기 전에 Anthropic의 가격 페이지를 확인하고, 청구서가 이 글을 읽는 이유라면 Claude API 지출이 어디로 가는지에 대한 분석을 읽어보세요. 배치 가격은 프롬프트 캐싱과도 중첩되며, 진정한 절감은 바로 여기서 나옵니다. 자세한 내용은 아래에서 다룹니다. 첫 배치 제출하기 공식 Python SDK를 설치하고 요청 목록을 만드세요. 각 요청은 직접 지정하는 custom_id와 일반적인 messages.create() 호출과 똑같이 생긴 params 객체를 가집니다. import anthropic from anthropic.types.message_create_params import MessageCreateParamsNonStreaming from anthropic.types.messages.batch_create_params import Request client = anthropic.Anthropic() tickets = [ "Card declined three times, support chat timed out.", "Love the new dashboard, the export button is hidden though.", "Webhook stopped firing after the 2.4 upgrade.", ] batch = client.messages.batches.create( requests=[ Request( custom_id=f"ticket-{i}", params=MessageCreateParamsNonStreaming( model="claude-haiku-5-5", max_tokens=1024, output_config={"effort": "low"}, messages=[{ "role": "user", "content": f"Label this ticket billing, bug, or praise. One word.\n\n{text}", }], ), ) for i, text in enumerate(tickets) ] ) print(batch.id, batch.processing_status) custom_id에 의미를 담으세요. 데이터베이스 기본 키나 파일 경로를 쓰면 나중에 조인할 필요가 없으며, 결과를 입력과 연결하는 유일한 수단입니다. 원시 HTTP를 선호한다면 동일한 페이로드를 x-api-key와 anthropic-version 헤더와 함께 POST https://api.anthropic.com/v1/messages/batches로 보내면 됩니다. 전체 스키마는 메시지 배치 생성 레퍼런스에서 확인할 수 있습니다. 배치를 폴링하고 결과 수집하기 processing_status가 ended가 될 때까지 배치를 조회한 다음 결과를 스트리밍하세요. 각 결과는 설정한 custom_id와 succeeded, errored, canceled, expired 중 하나인 result.type을 가집니다. import time while True: batch = client.messages.batches.retrieve(batch.id) if batch.processing_status == "ended": break print("still working:", batch.request_counts.processing) time.sleep(30) labels, retry = {}, [] for result in client.messages.batches.results(batch.id): if result.result.type == "succeeded": msg = result.result.message labels[result.custom_id] = next(b.text for b in msg.content if b.type == "text") elif result.result.type == "errored": retry.append(result.custom_id) print(f"{len(labels)} labeled, {len(retry)} need another pass") 두 가지 실패 유형은 별도로 처리해야 합니다. invalid_request 오류는 요청 본문이 잘못되었다는 뜻이므로 다시 제출하기 전에 수정하세요. 그 외의 오류는 서버 측 문제이므로 그대로 재시도해도 안전합니다. expired 결과는 해당 요청이 실행되기 전에 24시간 창이 닫혔다는 뜻이며, 이것들도 다시 제출해야 합니다. 30~60초 간격으로 폴링하세요. 매초 조회 엔드포인트를 두드리는 것은 아무 이득도 없고 Claude API 속도 제한에만 영향을 줍니다. 배치 가격에 프롬프트 캐싱 중첩하기 가장 큰 이득은 두 할인을 결합할 때 나옵니다. 배치의 모든 요청이 긴 접두사(스타일 가이드, 분류 체계, 40페이지 계약서)를 공유한다면, 그 접두사를 cache_control로 표시하고 10,000건의 요청 모두에 동일한 표시된 접두사를 보내세요. shared_system = [ {"type": "text", "text": "You are a support triage analyst."}, { "type": "text", "text": taxonomy_document, # thousands of tokens, identical every time "cache_control": {"type": "ephemeral"}, }, ] 배치의 모든 Request에 그 system 블록을 넣으세요. 접두사가 살아 있는 캐시 항목과 바이트 단위로 일치하는 요청은 그 접두사에 대해 캐시 읽기 요율로 청구되며, 50% 배치 할인은 캐시 읽기와 쓰기 모두에 적용됩니다. 완벽한 적중률을 가정하고 예산을 잡지 마세요. 배치는 요청을 순서대로가 아니라 동시에 처리하므로 하나의 배치 안에서의 캐시 적중은 최선 노력 수준입니다. Anthropic의 프롬프트 캐싱 가이드에서 접두사 규칙을 다룹니다. 중단 지점 이전에 바뀌는 바이트는 그 뒤의 모든 것을 무효화하므로, 타임스탬프와 항목별 텍스트는 캐시된 블록 뒤에 두세요. Claude Code가 Apidog CLI로 엔드포인트를 테스트하게 하기 100,000건의 실제 요청에 돈을 쓰기 전에 배치 생명주기(생성, 조회, 결과)에 대한 회귀 테스트를 원할 것입니다. GUI에서 직접 작성하는 것은 느립니다. 대신 코딩 에이전트가 Apidog CLI로 수행하게 하세요. npm install -g apidog-cli@latest apidog auth login --with-token <YOUR_TOKEN> apidog skill install # pick Claude Code when prompted 그런 다음 Claude Code에 한 번의 프롬프트를 입력하세요: In Apidog project 4820193, create a test case for POST https://api.anthropic.com/v1/messages/batches that submits two Haiku 5.5 requests with custom_id ticket-0 and ticket-1, asserts the response has an id and processing_status, then polls GET /v1/messages/batches/{id} until processing_status is ended. Run it against the anthropic-staging environment and summarize failures. 에이전트는 페이로드 스키마를 읽고 자체 JSON을 검증한 다음, 케이스를 생성하고 실행합니다: apidog cli-schema get test-case-create apidog cli-schema validate test-case-create --file batch-case.json apidog test-case create --project 4820193 --file batch-case.json apidog run --test-case 77214 --project 4820193 -e 992301 -r cli,json API 키는 Apidog 환경 변수에 남아 있으므로 프롬프트나 저장소에 절대 들어가지 않습니다. 리포터를 -r junit로 바꾸면 동일한 명령이 모든 병합 시 CI에서 실행되며, 이는 Apidog CLI 파이프라인 가이드에서 소개한 설정입니다. 아직 CLI를 에이전트에 연결하지 않았다면 Claude Code에서 Apidog CLI 사용하기부터 시작하세요. 배치가 잘못된 선택일 때 !When to use the Claude Batch API and when not to | 워크로드 | 배치 사용? | 이유 | | --- | --- | --- | | 매일 밤 어제의 로그 요약 | 예 | 기다리는 사람이 없고 50% 할인됨 | | 코퍼스 전체에 임베딩이나 레이블 백필 | 예 | 100,000건 요청 한도에 부합 | | 프롬프트 스위트 전반에 걸친 평가 실행 | 예 | custom_id를 키로 한 결과가 테스트 ID에 매핑됨 | | 채팅 UI 응답 | 아니요 | 사용자는 한 시간을 기다리지 않음 | | 다음 단계를 고르기 위해 마지막 답변이 필요한 에이전트 루프 | 아니요 | 배치 요청은 서로를 볼 수 없음 | | 5초 SLA를 지켜야 하는 요청 | 아니요 | 24시간 미만의 지연 시간 보장이 없음 | 몇 가지는 아예 넘어오지 않습니다. 빠른 모드(fast mode)는 Batch API에서 사용할 수 없고, 서버 측 거부 폴백도 여기서는 거부되며, Claude Opus 5.5와 Claude Sonnet 5.5에서 any 또는 tool로 강제한 tool_choice는 일반 호출과 마찬가지로 배치 안에서도 400을 반환합니다. 대신 strict: true와 함께 tool_choice: auto를 사용하세요. 멀티 프로바이더 인프라를 운영한다면 다른 곳에도 같은 패턴이 있습니다. OpenAI Batch API와 Gemini API 배치 모드를 참고하세요. 형태는 다르지만 경제성은 같습니다. 자주 묻는 질문 Claude Batch API란 무엇인가요? 표준 Messages API 요청을 정상 토큰 가격의 50%로 대량 실행하는 비동기 엔드포인트입니다. 자체 ID와 함께 요청 목록을 제출하고, 배치가 끝날 때까지 폴링한 뒤, 29일 이내에 결과를 읽으면 됩니다. Claude Batch API 비용은 얼마인가요? 입력과 출력 모두 표준 요율의 절반입니다. Claude Sonnet 5.5의 경우 입력 100만 토큰당 $1.00, 출력 100만 토큰당 $5.00이며, 동기식으로는 각각 $2.00과 $10.00입니다. Claude 배치는 얼마나 걸리나요? 대부분의 배치는 1시간 이내에 완료됩니다. 최대 24시간이며, 그 이후 처리되지 않은 요청은 expired 결과를 반환하므로 다시 제출해야 합니다. 배치 안에서 프롬프트 캐싱을 사용할 수 있나요? 예, 그리고 할인은 중첩됩니다. 공유 접두사를 cache_control로 표시하고 모든 요청에 동일한 접두사를 반복하면, 캐시 읽기는 배치 할인에 더해 입력 가격의 일부만 청구됩니다. 배치의 요청 하나가 실패하면 어떻게 되나요? 그 요청만 실패합니다. 해당 결과는 오류 객체와 함께 type: "errored"를 가지며, 나머지는 모두 성공합니다. 검증 오류는 페이로드를 수정해야 하고, 서버 오류는 그대로 재시도해도 안전합니다. 실행 중인 배치를 취소할 수 있나요? 예. client.messages.batches.cancel(batch_id)는 배치를 canceling으로 전환합니다. 이미 완료된 요청은 결과를 유지하고, 나머지는 canceled로 반환됩니다. Batch API는 도구와 이미지를 지원하나요? 예. 비전, 도구 정의, 시스템 프롬프트를 포함한 모든 Messages API 기능이 배치 안에서 작동합니다. 예외는 빠른 모드, 서버 측 폴백, 그리고 5.5 모델에서의 강제 도구 선택입니다. 마무리 배치 처리는 프롬프트 캐싱 다음으로 Claude API에서 두 번째로 큰 무료 절감 수단이며, 품질에는 아무런 손해가 없습니다. 같은 모델, 같은 기능, 절반의 가격을, 아마 쓰지도 않았을 지연 시간으로 지불하는 것입니다. 결과는 custom_id를 키로 삼고, 공유 접두사는 캐시하고, expired는 실패가 아니라 재시도로 처리하세요. 확장하기 전에 생명주기를 테스트하세요. Apidog CLI를 설치하고 코딩 에이전트를 배치 엔드포인트로 향하게 한 뒤, 생성된 테스트 케이스를 CI에서 계속 실행하여 스키마 변경이 100,000건의 요청에서 당신을 놀라게 하지 않도록 하세요. 무료 플랜은 4명의 사용자를 지원하며, Apidog을 다운로드하면 몇 분 만에 첫 케이스를 실행할 수 있습니다.

  3. Claude Batch API: รันงาน Async ลดต้นทุนครึ่งหนึ่ง Claude Batch API: รันงาน Async ลดต้นทุนครึ่งหนึ่ง คำตอบสั้น: Claude Batch API ประมวลผลคำขอ Messages API แบบอะซิงโครนัสในราคาลด 50% ทั้งโทเคนอินพุตและเอาต์พุต คุณส่งคำขอได้สูงสุด 100,000 รายการ (หรือ 256 MB) ในครั้งเดียว จากนั้น poll จนกว่าแบตช์จะสิ้นสุด แล้วอ่านผลลัพธ์ที่จับคู่ด้วย custom_id ของคุณเอง แบตช์ส่วนใหญ่เสร็จภายในหนึ่งชั่วโมง และเพดานสูงสุดคือ 24 ชั่วโมง {% cta apidog.com %} ลองใช้ Apidog วันนี้ {% endcta %} คุณมีตั๋วสนับสนุน 40,000 ใบที่ต้องจัดหมวดหมู่ หรือแค็ตตาล็อกสินค้าที่ต้องเขียนใหม่ หรือบทถอดเสียงหนึ่งเดือนที่ต้องสรุป ไม่มีอะไรเร่งด่วนเลย ทุกการเรียกเหล่านั้นยังคงคิดราคาเต็มเมื่อคุณยิงทีละครั้ง และคุณต้องเสียเวลาทั้งบ่ายคอยดูแลการ retry กับ rate limit ของคุณ Claude Batch API มีอยู่เพื่อรองรับงานรูปแบบนี้โดยเฉพาะ คุณส่งรายการคำขอให้ Anthropic แล้วเดินจากไป กลับมาแล้วได้ไฟล์ผลลัพธ์ที่ราคาเพียงครึ่งหนึ่งของที่การเรียกแบบซิงโครนัสแบบเดียวกันจะคิด ไม่ต้องรันคิว ไม่ต้องปรับ concurrency ไม่ต้องมี logic สำหรับ backoff คู่มือนี้ครอบคลุมว่า batch endpoint ทำอะไรได้บ้าง ค่าใช้จ่ายเท่าไร วิธีส่งงานและเก็บผลลัพธ์ และวิธีให้ coding agent ของคุณทดสอบทั้งหมดด้วย Apidog CLI ก่อนที่คุณจะชี้มันไปที่ข้อมูลจริง Claude Batch API คืออะไร? Claude Batch API คือ endpoint แบบอะซิงโครนัสที่ /v1/messages/batches ซึ่งรับคำขอ Messages API จำนวนมากในการส่งครั้งเดียว และคืนผลลัพธ์เมื่อการประมวลผลสิ้นสุดลง มันแลกความหน่วง (latency) กับส่วนลด 50% Anthropic เอกสารไว้ที่ batch processing ข้อจำกัดที่คุณต้องออกแบบให้สอดคล้อง: - ขนาด: สูงสุด 100,000 คำขอ หรือ 256 MB ต่อแบตช์ แล้วแต่ว่าจะถึงอันไหนก่อน - จังหวะเวลา: แบตช์ส่วนใหญ่เสร็จภายในหนึ่งชั่วโมง 24 ชั่วโมงคือระยะเวลาสูงสุดก่อนที่คำขอที่ยังไม่เสร็จจะหมดอายุ - การเก็บรักษา: ผลลัพธ์ยังใช้งานได้ 29 วันหลังจากสร้างแบตช์ - ฟีเจอร์เทียบเท่า: vision, การใช้ tools, system prompt และ prompt caching ทั้งหมดใช้งานได้ในแบตช์ - ลำดับ: ผลลัพธ์กลับมาในลำดับใดก็ได้ ดังนั้นคุณต้องจับคู่ด้วย custom_id ไม่ใช่ด้วยตำแหน่ง ประเด็นสุดท้ายคือจุดที่ทำคนเจ็บ แบตช์คือถุง ไม่ใช่คิว Claude Batch API มีค่าใช้จ่ายเท่าไร ส่วนลดคือ 50% แบบคงที่ทั้งโทเคนอินพุตและเอาต์พุต ใช้กับโมเดลใดก็ตามที่แต่ละคำขอระบุ คุณสามารถผสมโมเดลในแบตช์เดียวได้ ดังนั้น classifier ราคาถูกและ summarizer ราคาแพงสามารถไปด้วยกันได้ !Claude Batch API vs standard pricing: output price per million tokens for Opus 5.5, Sonnet 5.5 and Haiku 5.5 | โมเดล | อินพุต / เอาต์พุต มาตรฐาน ต่อ MTok | อินพุต / เอาต์พุต แบบแบตช์ ต่อ MTok | | --- | --- | --- | | Claude Opus 5.5 | $4.00 / $20.00 | $2.00 / $10.00 | | Claude Sonnet 5.5 | $2.00 / $10.00 | $1.00 / $5.00 | | Claude Haiku 5.5 (prompt สูงสุด 100K) | $0.10 / $0.50 | $0.05 / $0.25 | | Claude Haiku 5.5 (prompt เกิน 100K) | $0.50 / $2.50 | $0.25 / $1.25 | อ่านแถวของ Haiku ให้ดี Haiku 5.5 คิดราคาตามขนาด prompt ดังนั้น prompt เดียวที่เกิน 100,000 โทเคนจะคิดราคา 5 เท่าของอัตรา prompt สั้น ไม่ว่าจะมีส่วนลดแบตช์หรือไม่ ประเมินงาน Haiku ที่มี context ยาวที่ $0.25 / $1.25 ไม่ใช่ $0.05 / $0.25 ตรวจสอบที่ หน้าข้อมูลราคาของ Anthropic ก่อนที่คุณจะสร้างการคาดการณ์จากตัวเลขเหล่านี้ และอ่านบทวิเคราะห์ของเราเกี่ยวกับ ค่าใช้จ่าย Claude API ไปที่ไหน ถ้าใบเรียกเก็บเงินคือเหตุผลที่คุณมาที่นี่ ราคาแบบแบตช์ยังใช้ร่วมกับ prompt caching ได้ด้วย ซึ่งเป็นที่ที่เงินออมจริงอยู่ รายละเอียดเพิ่มเติมด้านล่าง ส่งแบตช์แรกของคุณ ติดตั้ง Python SDK อย่างเป็นทางการ แล้วสร้างรายการคำขอ แต่ละรายการมี custom_id ที่คุณเลือก และออบเจ็กต์ params ที่ดูเหมือนการเรียก messages.create() ปกติทุกประการ import anthropic from anthropic.types.message_create_params import MessageCreateParamsNonStreaming from anthropic.types.messages.batch_create_params import Request client = anthropic.Anthropic() tickets = [ "Card declined three times, support chat timed out.", "Love the new dashboard, the export button is hidden though.", "Webhook stopped firing after the 2.4 upgrade.", ] batch = client.messages.batches.create( requests=[ Request( custom_id=f"ticket-{i}", params=MessageCreateParamsNonStreaming( model="claude-haiku-5-5", max_tokens=1024, output_config={"effort": "low"}, messages=[{ "role": "user", "content": f"Label this ticket billing, bug, or praise. One word.\n\n{text}", }], ), ) for i, text in enumerate(tickets) ] ) print(batch.id, batch.processing_status) ให้ custom_id มีความหมาย เช่น primary key ของฐานข้อมูลหรือ path ของไฟล์ จะช่วยให้คุณไม่ต้อง join ทีหลัง และมันคือสิ่งเดียวที่เชื่อมผลลัพธ์กลับไปยังอินพุตของมัน ถ้าคุณชอบ HTTP ดิบ payload เดียวกันก็ส่งไปที่ POST https://api.anthropic.com/v1/messages/batches พร้อมเฮดเดอร์ x-api-key และ anthropic-version ของคุณ เอกสาร create a message batch reference มี schema แบบเต็ม Poll แบตช์และเก็บผลลัพธ์ ดึงข้อมูลแบตช์ซ้ำจนกว่า processing_status จะอ่านว่า ended แล้วสตรีมผลลัพธ์ แต่ละผลลัพธ์มี custom_id ที่คุณตั้งไว้ และ result.type เป็น succeeded, errored, canceled หรือ expired import time while True: batch = client.messages.batches.retrieve(batch.id) if batch.processing_status == "ended": break print("still working:", batch.request_counts.processing) time.sleep(30) labels, retry = {}, [] for result in client.messages.batches.results(batch.id): if result.result.type == "succeeded": msg = result.result.message labels[result.custom_id] = next(b.text for b in msg.content if b.type == "text") elif result.result.type == "errored": retry.append(result.custom_id) print(f"{len(labels)} labeled, {len(retry)} need another pass") โหมดความล้มเหลวสองแบบควรได้รับการจัดการแยกกัน ข้อผิดพลาด invalid_request หมายความว่าเนื้อหาคำขอผิด คุณจึงต้องแก้ไขก่อนส่งใหม่ สิ่งอื่นๆ เป็นฝั่งเซิร์ฟเวอร์และปลอดภัยที่จะ retry ตามเดิม ผลลัพธ์ expired หมายความว่าหน้าต่าง 24 ชั่วโมงปิดลงก่อนที่คำขอนั้นจะได้รัน และคุณก็ส่งคำขอเหล่านั้นใหม่เช่นกัน Poll ด้วยตัวจับเวลา 30 ถึง 60 วินาที การกระหน่ำ retrieve endpoint ทุกวินาทีไม่ได้อะไรเลยและนับรวมกับ rate limit ของ Claude API ของคุณด้วย ใช้ราคาแบบแบตช์ร่วมกับ prompt caching กำไรสูงสุดมาจากการรวมส่วนลดทั้งสองเข้าด้วยกัน ถ้าทุกคำขอในแบตช์ของคุณใช้คำนำหน้า (prefix) ยาวๆ ร่วมกัน เช่น style guide, taxonomy, สัญญา 40 หน้า ให้ทำเครื่องหมาย prefix นั้นด้วย cache_control และส่ง prefix ที่ทำเครื่องหมายไว้เหมือนกันในคำขอทั้ง 10,000 รายการ shared_system = [ {"type": "text", "text": "You are a support triage analyst."}, { "type": "text", "text": taxonomy_document, # thousands of tokens, identical every time "cache_control": {"type": "ephemeral"}, }, ] ใส่บล็อก system นั้นในทุก Request ในแบตช์ คำขอใดก็ตามที่มี prefix ตรงกับรายการ cache ที่ยังมีชีวิตอยู่แบบไบต์ต่อไบต์ จะคิดราคา prefix นั้นในอัตรา cache-read และส่วนลดแบตช์ 50% ก็ใช้กับทั้ง cache read และ write อย่าคาดหวังอัตราการเข้าเป้าแบบสมบูรณ์: แบตช์ประมวลผลคำขอแบบพร้อมกัน (concurrent) ไม่ได้เรียงตามลำดับ ดังนั้น cache hit ภายในแบตช์เดียวจึงเป็นแบบ best-effort คู่มือ prompt caching ของ Anthropic ครอบคลุมกฎเรื่อง prefix: ไบต์ใดก็ตามที่เปลี่ยนไปก่อนจุดตัดของคุณ จะทำให้ทุกอย่างหลังจากนั้นใช้ไม่ได้ ดังนั้นให้วาง timestamp และข้อความเฉพาะรายการไว้หลังบล็อกที่ cache ไว้ ให้ Claude Code ทดสอบ endpoint ด้วย Apidog CLI ก่อนคุณจะใช้เงินกับคำขอจริง 100,000 รายการ คุณอยากมี regression test สำหรับวงจรชีวิตของแบตช์: create, retrieve, results การเขียนมันด้วยมือใน GUI นั้นช้า ให้ coding agent ของคุณทำด้วย Apidog CLI แทน npm install -g apidog-cli@latest apidog auth login --with-token <YOUR_TOKEN> apidog skill install # pick Claude Code when prompted จากนั้นส่ง prompt หนึ่งครั้งไปยัง Claude Code: In Apidog project 4820193, create a test case for POST https://api.anthropic.com/v1/messages/batches that submits two Haiku 5.5 requests with custom_id ticket-0 and ticket-1, asserts the response has an id and processing_status, then polls GET /v1/messages/batches/{id} until processing_status is ended. Run it against the anthropic-staging environment and summarize failures. agent จะอ่าน schema ของ payload ตรวจสอบ JSON ของตัวเอง จากนั้นสร้างและรัน test case: apidog cli-schema get test-case-create apidog cli-schema validate test-case-create --file batch-case.json apidog test-case create --project 4820193 --file batch-case.json apidog run --test-case 77214 --project 4820193 -e 992301 -r cli,json API key ของคุณอยู่ใน environment variable ของ Apidog ดังนั้นมันจะไม่หลุดไปใน prompt หรือ repo เปลี่ยน reporter เป็น -r junit แล้วคำสั่งเดียวกันก็รันใน CI ทุกครั้งที่ merge ซึ่งคือ setup ใน คู่มือ pipeline ของ Apidog CLI ของเรา ถ้าคุณยังไม่ได้เชื่อม CLI เข้ากับ agent ของคุณ เริ่มจาก การใช้ Apidog CLI ใน Claude Code เมื่อใดที่แบตช์เป็นตัวเลือกที่ผิด !When to use the Claude Batch API and when not to | งาน | ใช้แบตช์? | เหตุผล | | --- | --- | --- | | การสรุป log ของเมื่อวานทุกคืน | ใช่ | ไม่มีใครรอ ลด 50% | | การเติม embeddings หรือ labels ย้อนหลังทั้งคลังข้อมูล | ใช่ | อยู่ในเพดาน 100,000 คำขอ | | การรัน evaluation กับชุด prompt ต่างๆ | ใช่ | ผลลัพธ์ที่จับคู่ด้วย custom_id จับคู่กับ ID ของการทดสอบได้ | | การตอบกลับใน UI แชท | ไม่ | ผู้ใช้จะไม่รอหนึ่งชั่วโมง | | ลูปของ agent ที่ต้องการคำตอบล่าสุดเพื่อเลือกขั้นถัดไป | ไม่ | คำขอในแบตช์มองเห็นกันไม่ได้ | | คำขอที่ต้องตอบภายใน SLA 5 วินาที | ไม่ | ไม่มีการรับประกันความหน่วงต่ำกว่า 24 ชั่วโมง | มีบางอย่างที่ไม่สามารถใช้ข้ามได้เช่นกัน Fast mode ไม่พร้อมใช้บน Batch API, server-side refusal fallback ถูกปฏิเสธที่นั่น และบน Claude Opus 5.5 และ Claude Sonnet 5.5 การบังคับ tool_choice เป็น any หรือ tool จะคืนค่า 400 ภายในแบตช์เหมือนกับการเรียกปกติทุกประการ ให้ใช้ tool_choice: auto ร่วมกับ strict: true แทน ถ้าคุณรันโครงสร้างพื้นฐานแบบหลายผู้ให้บริการ รูปแบบเดียวกันก็มีอยู่ที่อื่นด้วย: ดู OpenAI Batch API และ Gemini API batch mode รูปร่างต่างกัน แต่เศรษฐศาสตร์ไม่ต่าง คำถามที่พบบ่อย Claude Batch API คืออะไร? มันคือ endpoint แบบอะซิงโครนัสที่รันคำขอ Messages API มาตรฐานเป็นกลุ่มก้อนในราคา 50% ของราคาโทเคนปกติ คุณส่งรายการคำขอพร้อม ID ของคุณเอง, poll จนกว่าแบตช์จะจบ และอ่านผลลัพธ์ภายใน 29 วัน Claude Batch API มีค่าใช้จ่ายเท่าไร? ครึ่งหนึ่งของอัตรามาตรฐานทั้งอินพุตและเอาต์พุต บน Claude Sonnet 5.5 นั่นคือ $1.00 ต่อโทเคนอินพุตหนึ่งล้าน และ $5.00 ต่อโทเคนเอาต์พุตหนึ่งล้าน เทียบกับ $2.00 และ $10.00 แบบซิงโครนัส แบตช์ของ Claude ใช้เวลานานแค่ไหน? แบตช์ส่วนใหญ่เสร็จภายในหนึ่งชั่วโมง ระยะเวลาสูงสุดคือ 24 ชั่วโมง หลังจากนั้นคำขอที่ยังไม่ถูกประมวลผลจะคืนผลลัพธ์ expired และคุณต้องส่งใหม่ ฉันใช้ prompt caching ภายในแบตช์ได้ไหม? ได้ และส่วนลดใช้ร่วมกันได้ ให้ทำเครื่องหมาย prefix ที่ใช้ร่วมกันด้วย cache_control ส่ง prefix ที่เหมือนกันนั้นซ้ำในทุกคำขอ และ cache read จะคิดราคาเป็นเศษเสี้ยวของราคาอินพุตบนส่วนลดแบตช์อีกชั้น เกิดอะไรขึ้นเมื่อคำขอหนึ่งในแบตช์ล้มเหลว? มีแค่คำขอนั้นที่ล้มเหลว ผลลัพธ์ของมันจะมาพร้อม type: "errored" พร้อมออบเจ็กต์ error ส่วนที่เหลือยังสำเร็จตามปกติ ข้อผิดพลาดจากการตรวจสอบ (validation error) ต้องแก้ payload ส่วนข้อผิดพลาดฝั่งเซิร์ฟเวอร์ปลอดภัยที่จะ retry ตามเดิม ฉันยกเลิกแบตช์ที่กำลังรันอยู่ได้ไหม? ได้ client.messages.batches.cancel(batch_id) จะย้ายแบตช์ไปเป็นสถานะ canceling คำขอที่เสร็จแล้วจะเก็บผลลัพธ์ไว้ ส่วนที่เหลือจะกลับมาเป็น canceled Batch API รองรับ tools และรูปภาพไหม? ได้ ทุกฟีเจอร์ของ Messages API ทำงานได้ในแบตช์ รวมถึง vision, นิยามของ tool และ system prompt ข้อยกเว้นคือ fast mode, server-side fallback และการบังคับ tool choice บนโมเดลตระกูล 5.5 สรุป การประมวลผลแบบแบตช์คือการประหยัดฟรีที่ใหญ่เป็นอันดับสองบน Claude API รองจาก prompt caching และไม่ต้องแลกกับคุณภาพเลย: โมเดลเดียวกัน ฟีเจอร์เดียวกัน ครึ่งราคา โดยแลกกับความหน่วงที่คุณคงไม่ได้ใช้อยู่แล้ว ให้จับคู่ผลลัพธ์ด้วย custom_id cache prefix ที่ใช้ร่วมกัน และจัดการ expired เหมือนการ retry ไม่ใช่ความล้มเหลว ทดสอบวงจรชีวิตก่อนที่คุณจะขยายขนาด ติดตั้ง Apidog CLI ชี้ coding agent ของคุณไปที่ batch endpoint และให้ test case ที่สร้างขึ้นรันใน CI ต่อไป เพื่อที่การเปลี่ยนแปลง schema จะไม่ทำให้คุณประหลาดใจที่คำขา 100,000 รายการ แผนฟรีครอบคลุม 4 ผู้ใช้ และคุณสามารถ ดาวน์โหลด Apidog แล้วมี test case แรกที่รันได้ในไม่กี่นาที

  4. Claude Batch API: تشغيل المهام غير المتزامنة بنصف التكلفة الإجابة السريعة: تعالج واجهة Claude Batch API طلبات Messages API بشكل غير متزامن بخصم 50% على كل من الرموز المُدخَلة والمُخرَجة. يمكنك إرسال ما يصل إلى 100,000 طلب (أو 256 ميجابايت) في استدعاء واحد، ثم الاستعلام بشكل دوري حتى انتهاء الدفعة، ثم قراءة النتائج المرتبطة بـ custom_id الخاص بك. تُكمل معظم الدفعات خلال ساعة، والحد الأقصى الصارم هو 24 ساعة. {% cta apidog.com %} جرّب Apidog اليوم {% endcta %} لديك 40,000 تذكرة دعم لتصنيفها، أو كتالوج منتجات لإعادة كتابته، أو شهر من النصوص المُفرَّغة لتلخيصه. لا شيء من هذا عاجل. ومع ذلك، تُحتسب كل واحدة من هذه الاستدعاءات بالسعر الكامل عندما ترسلها واحدة تلو الأخرى، وتقضي فترة الظهيرة في مراقبة إعادة المحاولات ضد حد المعدل الخاص بك. وُجدت Claude Batch API تحديداً لهذا النوع من العمل. تُسلّم Anthropic قائمة من الطلبات، ثم تبتعد، وتعود إلى ملف من النتائج تكلفته نصف ما كانت ستكلفه نفس الاستدعاءات بشكل متزامن. لا قائمة انتظار لتشغيلها، ولا ضبط للتزامن، ولا منطق للتراجع. يغطي هذا الدليل ما تفعله نقطة نهاية الدفعة، وكم تكلف، وكيفية إرسال مهمة وجمعها، وكيفية ترك وكيل البرمجة الخاص بك يختبر الأمر برمته باستخدام Apidog CLI قبل توجيهه إلى بيانات حقيقية. ما هي Claude Batch API؟ Claude Batch API هي نقطة نهاية غير متزامنة على /v1/messages/batches تقبل العديد من طلبات Messages API في إرسال واحد وتعيد نتائجها بمجرد انتهاء المعالجة. تُقايض زمن الاستجابة مقابل خصم بنسبة 50%. توثّقها Anthropic تحت المعالجة الدفعية. القيود التي تحتاج إلى التصميم حولها: - الحجم: ما يصل إلى 100,000 طلب أو 256 ميجابايت لكل دفعة، أيهما تصل إليه أولاً. - التوقيت: تكتمل معظم الدفعات خلال ساعة؛ و24 ساعة هي الحد الأقصى قبل انتهاء صلاحية الطلبات غير المكتملة. - الاحتفاظ: تبقى النتائج متاحة لمدة 29 يوماً بعد إنشاء الدفعة. - تكافؤ الميزات: تعمل الرؤية واستخدام الأدوات ومطالبات النظام والتخزين المؤقت للمطالبات جميعها داخل الدفعة. - الترتيب: تعود النتائج بأي ترتيب، لذا تربطها بـ custom_id وليس بالموضع أبداً. هذه النقطة الأخيرة هي التي تربك الناس. الدفعة عبارة عن كيس، وليست قائمة انتظار. كم تكلف Claude Batch API الخصم ثابت بنسبة 50% على كل من الرموز المُدخَلة والمُخرَجة، ويُطبَّق على أي نموذج يحدده كل طلب. يمكنك خلط النماذج داخل دفعة واحدة، حتى يتمكن مصنِّف رخيص وملخِّص مكلف من السير معاً. !Claude Batch API vs standard pricing: output price per million tokens for Opus 5.5, Sonnet 5.5 and Haiku 5.5 | النموذج | الإدخال / الإخراج القياسي لكل مليون رمز | الإدخال / الإخراج الدفعي لكل مليون رمز | | --- | --- | --- | | Claude Opus 5.5 | $4.00 / $20.00 | $2.00 / $10.00 | | Claude Sonnet 5.5 | $2.00 / $10.00 | $1.00 / $5.00 | | Claude Haiku 5.5 (مطالبات حتى 100K) | $0.10 / $0.50 | $0.05 / $0.25 | | Claude Haiku 5.5 (مطالبات أكثر من 100K) | $0.50 / $2.50 | $0.25 / $1.25 | اقرأ صفوف Haiku بعناية. يُسعَّر Haiku 5.5 حسب حجم المطالبة، لذا فإن مطالبة واحدة تتجاوز 100,000 رمز تُحتسب بخمسة أضعاف معدل المطالبة القصيرة، سواءً طُبِّق خصم الدفعة أم لا. قدِّر عمل Haiku ذا السياق الطويل بسعر $0.25 / $1.25، وليس $0.05 / $0.25. تحقق من صفحة أسعار Anthropic قبل بناء تقدير على هذه الأرقام، واقرأ تحليلنا حول أين يذهب إنفاق Claude API إذا كانت الفاتورة هي سبب وجودك هنا. تتكدس الأسعار الدفعية أيضاً مع التخزين المؤقت للمطالبات، وهو المكان الذي توجد فيه التوفيرات الحقيقية. المزيد حول ذلك أدناه. أرسل دفعتك الأولى ثبّت Python SDK الرسمي وأنشئ قائمة من الطلبات. يحمل كل واحد منها custom_id تختاره أنت وكائن params يبدو تماماً مثل استدعاء messages.create() العادي. import anthropic from anthropic.types.message_create_params import MessageCreateParamsNonStreaming from anthropic.types.messages.batch_create_params import Request client = anthropic.Anthropic() tickets = [ "Card declined three times, support chat timed out.", "Love the new dashboard, the export button is hidden though.", "Webhook stopped firing after the 2.4 upgrade.", ] batch = client.messages.batches.create( requests=[ Request( custom_id=f"ticket-{i}", params=MessageCreateParamsNonStreaming( model="claude-haiku-5-5", max_tokens=1024, output_config={"effort": "low"}, messages=[{ "role": "user", "content": f"Label this ticket billing, bug, or praise. One word.\n\n{text}", }], ), ) for i, text in enumerate(tickets) ] ) print(batch.id, batch.processing_status) اجعل custom_id يحمل معنى. فمفتاح أساسي لقاعدة بيانات أو مسار ملف يوفر عليك عملية ربط لاحقة، وهو الشيء الوحيد الذي يربط النتيجة بمُدخلها. إذا كنت تفضل HTTP الخام، فإن نفس الحمولة تذهب إلى POST https://api.anthropic.com/v1/messages/batches مع ترويسات x-api-key وanthropic-version الخاصة بك. يحتوي مرجع إنشاء دفعة رسائل على المخطط الكامل. استعلم عن الدفعة واجمع النتائج استرجع الدفعة حتى تقرأ processing_status القيمة ended، ثم بثّ النتائج. تحمل كل نتيجة custom_id الذي حددته وresult.type بقيمة succeeded أو errored أو canceled أو expired. import time while True: batch = client.messages.batches.retrieve(batch.id) if batch.processing_status == "ended": break print("still working:", batch.request_counts.processing) time.sleep(30) labels, retry = {}, [] for result in client.messages.batches.results(batch.id): if result.result.type == "succeeded": msg = result.result.message labels[result.custom_id] = next(b.text for b in msg.content if b.type == "text") elif result.result.type == "errored": retry.append(result.custom_id) print(f"{len(labels)} labeled, {len(retry)} need another pass") تستحق أوضاع الفشل معالجة منفصلة. خطأ invalid_request يعني أن جسم الطلب كان خاطئاً، لذا أصلحه قبل إعادة الإرسال. أي شيء آخر هو من جانب الخادم ومن الآمن إعادة محاولته كما هو. نتيجة expired تعني أن النافذة البالغة 24 ساعة أُغلقت قبل تشغيل ذلك الطلب، فأعد إرساله أيضاً. استعلم بمؤقت من 30 إلى 60 ثانية. فطرق نقطة نهاية الاسترجاع كل ثانية لا يجلب لك شيئاً ويُحتسب ضد حدود معدل Claude API الخاصة بك. كدّس الأسعار الدفعية مع التخزين المؤقت للمطالبات يأتي أكبر مكسب من الجمع بين الخصمين. إذا كانت كل مطالبة في دفعتك تشترك في بادئة طويلة — دليل أسلوب، تصنيف، عقد من 40 صفحة — ضع علامة على تلك البادئة بـ cache_control وأرسل نفس البادئة المعلَّمة على كل الطلبات العشرة آلاف. shared_system = [ {"type": "text", "text": "You are a support triage analyst."}, { "type": "text", "text": taxonomy_document, # thousands of tokens, identical every time "cache_control": {"type": "ephemeral"}, }, ] ضع كتلة system تلك على كل Request في الدفعة. أي طلب تتطابق بادئته مع إدخال ذاكرة تخزين مؤقت حيّة بايتاً ببايت يُحتسب على تلك البادئة بأسعار قراءة الذاكرة المؤقتة، ويُطبَّق خصم الدفعة البالغ 50% على قراءات وكتابات الذاكرة المؤقتة على حد سواء. لا تضع ميزانية لمعدل إصابة مثالي: تعالج الدفعة طلباتها بشكل متزامن وليس بالترتيب، لذا فإن إصابات الذاكرة المؤقتة داخل دفعة واحدة هي بذل أفضل جهد. يغطي دليل التخزين المؤقت للمطالبات الخاص بـ Anthropic قواعد البادئة: أي بايت يتغير قبل نقطة التوقف الخاصة بك يُبطل كل شيء بعده، لذا أبقِ الطوابع الزمنية والنص الخاص بكل عنصر بعد الكتلة المخزنة مؤقتاً. دع Claude Code يختبر نقطة النهاية باستخدام Apidog CLI قبل أن تنفق المال على 100,000 طلب حي، تريد اختبار انحدار على دورة حياة الدفعة: الإنشاء، الاسترجاع، النتائج. كتابة ذلك يدوياً في واجهة رسومية بطيئة. دع وكيل البرمجة الخاص بك يقوم بذلك باستخدام Apidog CLI بدلاً من ذلك. npm install -g apidog-cli@latest apidog auth login --with-token <YOUR_TOKEN> apidog skill install # pick Claude Code when prompted ثم مطالبة واحدة إلى Claude Code: In Apidog project 4820193, create a test case for POST https://api.anthropic.com/v1/messages/batches that submits two Haiku 5.5 requests with custom_id ticket-0 and ticket-1, asserts the response has an id and processing_status, then polls GET /v1/messages/batches/{id} until processing_status is ended. Run it against the anthropic-staging environment and summarize failures. يقرأ الوكيل مخطط الحمولة، ويتحقق من JSON الخاص به، ثم ينشئ الحالة ويشغلها: apidog cli-schema get test-case-create apidog cli-schema validate test-case-create --file batch-case.json apidog test-case create --project 4820193 --file batch-case.json apidog run --test-case 77214 --project 4820193 -e 992301 -r cli,json يبقى مفتاح API الخاص بك في متغير بيئة Apidog، لذا لا يصل أبداً إلى مطالبة أو مستودع. بدّل أداة الإبلاغ إلى -r junit وسيعمل نفس الأمر في CI عند كل دمج، وهو الإعداد الموجود في دليل خط أنابيب Apidog CLI الخاص بنا. إذا لم تكن قد وصّلت CLI بوكيلك بعد، فابدأ بـ استخدام Apidog CLI في Claude Code. متى تكون الدفعة الخيار الخاطئ !When to use the Claude Batch API and when not to | عبء العمل | استخدام الدفعة؟ | السبب | | --- | --- | --- | | تلخيص ليلي لسجلات الأمس | نعم | لا أحد ينتظر؛ خصم 50% | | إعادة تعبئة التضمينات أو التسميات على مجموعة نصوص | نعم | يتناسب مع سقف 100,000 طلب | | تشغيلات التقييم عبر مجموعة مطالبات | نعم | النتائج المرتبطة بـ custom_id تُطابق معرّفات الاختبار | | ردود واجهة الدردشة | لا | لن ينتظر المستخدمون ساعة | | حلقة وكيل تحتاج إلى الإجابة الأخيرة لاختيار الخطوة التالية | لا | لا يمكن لطلبات الدفعة رؤية بعضها البعض | | طلب يجب أن يتغلب على اتفاقية مستوى خدمة مدتها 5 ثوانٍ | لا | لا يوجد ضمان لزمن الاستجابة أقل من 24 ساعة | بعض الأشياء أيضاً لا تنتقل. الوضع السريع غير متاح على Batch API، وتُرفض الاحتياطات من جانب الخادم هناك، وعلى Claude Opus 5.5 وClaude Sonnet 5.5 يُعيد tool_choice المفروض بقيمة any أو tool خطأ 400 داخل الدفعة تماماً كما يفعل في استدعاء عادي. استخدم tool_choice: auto مع strict: true بدلاً من ذلك. إذا كنت تدير بنية تحتية متعددة المزودين، فإن نفس النمط موجود في أماكن أخرى: انظر OpenAI Batch API ووضع الدفعة في Gemini API. تختلف الأشكال، لكن الاقتصاديات لا تختلف. الأسئلة الشائعة ما هي Claude Batch API؟ إنها نقطة نهاية غير متزامنة تشغّل طلبات Messages API القياسية بكميات كبيرة بنسبة 50% من أسعار الرموز العادية. تُرسل قائمة من الطلبات بمعرّفاتك الخاصة، وتستعلم حتى انتهاء الدفعة، وتقرأ النتائج خلال 29 يوماً. كم تكلف Claude Batch API؟ نصف السعر القياسي على كل من الإدخال والإخراج. على Claude Sonnet 5.5 يكون $1.00 لكل مليون رمز مُدخَل و$5.00 لكل مليون رمز مُخرَج، مقابل $2.00 و$10.00 بشكل متزامن. كم تستغرق دفعة Claude؟ تكتمل معظم الدفعات خلال ساعة. الحد الأقصى هو 24 ساعة، وبعدها يُعيد أي طلب غير معالَج نتيجة expired، فأعد إرساله. هل يمكنني استخدام التخزين المؤقت للمطالبات داخل الدفعة؟ نعم، والخصومات تتكدس. ضع علامة على بادئة مشتركة بـ cache_control، وكرر تلك البادئة المتطابقة عبر كل طلب، وتُحتسب القراءات المخزنة مؤقتاً بجزء صغير من سعر الإدخال فوق خصم الدفعة. ماذا يحدث عندما يفشل طلب واحد في دفعة؟ يفشل ذلك الطلب فقط. تحمل نتيجته type: "errored" مع كائن خطأ؛ وكل شيء آخر يظل ناجحاً. تحتاج أخطاء التحقق إلى حمولة مُصلَحة، وأخطاء الخادم آمنة لإعادة المحاولة دون تغيير. هل يمكنني إلغاء دفعة قيد التشغيل؟ نعم. ينقل client.messages.batches.cancel(batch_id) الدفعة إلى canceling. تحتفظ الطلبات المنتهية بالفعل بنتائجها؛ ويعود الباقي بـ canceled. هل تدعم Batch API الأدوات والصور؟ نعم. تعمل كل ميزة في Messages API داخل الدفعة، بما في ذلك الرؤية وتعريفات الأدوات ومطالبات النظام. الاستثناءات هي الوضع السريع والاحتياطات من جانب الخادم واختيار الأدوات المفروض على نماذج 5.5. الختام المعالجة الدفعية هي ثاني أكبر توفير مجاني على Claude API بعد التخزين المؤقت للمطالبات، وهي لا تكلفك شيئاً في الجودة: نفس النماذج، نفس الميزات، نصف السعر، مدفوعة بزمن استجابة لم تكن تستخدمه على الأرجح. اربط نتائجك بـ custom_id، وخزّن البادئة المشتركة مؤقتاً، وتعامل مع expired كإعادة محاولة وليس كفشل. اختبر دورة الحياة قبل توسيع نطاقها. ثبّت Apidog CLI، ووجّه وكيل البرمجة الخاص بك إلى نقاط نهاية الدفعة، وأبقِ حالة الاختبار المُولَّدة قيد التشغيل في CI حتى لا يفاجئك تغيير المخطط عند 100,000 طلب. تغطي الخطة المجانية 4 مستخدمين، ويمكنك تنزيل Apidog وتشغيل أول حالة في غضون دقائق قليلة.

  5. A 200K-Token Claude Session Left Idle Re-Buys Its Cache: $0.04 Becomes $1.00 - Book: Observability for LLM Applications - Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go - My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools - Me: xgabriel.com | GitHub --- Ten minutes at the coffee machine can add $0.96 to the next message in a 200,000-token Claude Code session. The session has been open since the morning and has read half the repo. You step away, come back, and type one line: "thanks, now also rename the test file." If you sign in with an API key and run Opus 5.5, the turn before your break read those 200K tokens from the prompt cache for about $0.04. Your one-line follow-up pays about $1.00 to write the same 200K tokens back into the cache, because the cache expired while you were gone. Claude Code 2.1.314, out October 30, brought idle compaction to VS Code and the Desktop Code tab to dodge exactly this bill. Three prices for the same token Every Claude Code turn is a fresh API request that re-sends the whole conversation; as the prompt caching docs put it, "The model doesn't remember anything between requests." The API skips reprocessing the unchanged start of the request, the prefix, when it matches what it recently cached. So a token in your history is billed at one of three rates, depending on the cache's state when the request arrives. Anthropic's prompt caching page gives the multipliers: - A cache write with the 5-minute TTL costs 1.25x the base input price. - A cache write with the 1-hour TTL costs 2x. - A cache read is 0.1x, with exceptions. The exceptions matter for current models. The pricing page prices cache hits on Opus 5.5 and Sonnet 5.5 at 0.05x, and on Fable 5.1 at 0.025x. On those models the gap between a warm read and a cold write is wider still. Each hit resets the timer, and the lifetime is "measured from the start of the request that writes or reads the cache entry." Work steadily and the cache stays warm all day. Step away past the TTL and the next request finds nothing, so it writes the whole prefix again at the write rate. The math for one line at 200K tokens These are list prices per million tokens from Anthropic's pricing page, multiplied by a 200,000-token prefix. Input side only: your new message and Claude's reply cost the same either way. | Model | Warm read | Cold, 5m write | Cold, 1h write | |---|---|---|---| | Opus 5.5 ($4 base) | $0.04 | $1.00 | $1.60 | | Sonnet 5.5 ($2 base) | $0.02 | $0.50 | $0.80 | | Fable 5.1 ($10 base) | $0.05 | $2.50 | $4.00 | On Opus 5.5 the cold turn costs 25 times the warm one on the 5-minute TTL, and 40 times on the 1-hour TTL. On Fable 5.1 it is 50 and 80 times. There is no long-context surcharge hiding on top: the pricing page says Claude 4.6 and later models, except Haiku 5.5, bill the full 1M window "at standard pricing." Which column applies to you depends on how you pay. Claude Code's docs say it requests the one-hour TTL for the main conversation only on a Claude subscription within your plan's included usage. With an API key, usage credits or a cloud provider, the default is five minutes. That means the coffee break above is enough. On a subscription you don't see dollars. You see plan usage, and a cold 200K rewrite draws on it the same way. Since a fix in 2.1.311, /usage lists large prompt-cache misses under "What's contributing to your limits usage?". If you run on an API key and take breaks, the one-hour TTL can be the cheaper choice. A session that grew to 200K tokens by appending turns wrote roughly 200K tokens to the cache over its life, one exchange at a time. Under that assumption, paying the 1-hour rate instead of the 5-minute rate on those writes costs about 200K × ($8 − $5) per million, or $0.60 on Opus 5.5. One break of between five minutes and an hour then costs a $0.04 read instead of a $1.00 rewrite, which covers that premium. A break longer than an hour is cold on either TTL, and on the hour TTL the rewrite costs $1.60. Claude Code exposes the choice as the promptCacheTtl setting in settings.json (v2.1.242 or later): { "promptCacheTtl": "1h" } !An hourglass whose falling sand is made of small token blocks, next to a coffee cup and a terminal window; below the empty bulb, a stack of burnt-orange coins The cache runs on a timer. When the sand runs out, the next message buys the whole history again. See it in your own numbers You don't have to trust my table. The API reports all three rates on every response. From the caching docs: - cache_creation_input_tokens: tokens written to the cache by this request. - cache_read_input_tokens: tokens read from the cache. - input_tokens: tokens after the last cache breakpoint, neither read nor written. Total input is the sum of the three. A cache_creation object splits the writes into ephemeral_5m_input_tokens and ephemeral_1h_input_tokens. This script uses the Python SDK to send a large system block marked for caching, the way the caching docs show, and prints the counts. Point it at any text file over a few thousand tokens: import anthropic client = anthropic.Anthropic() history = open("session.md").read() resp = client.messages.create( model="claude-opus-5-5", max_tokens=256, system=[{ "type": "text", "text": history, "cache_control": {"type": "ephemeral"}, }], messages=[{"role": "user", "content": "thanks, now also..."}], ) u = resp.usage print("written:", u.cache_creation_input_tokens) print("read: ", u.cache_read_input_tokens) print("fresh: ", u.input_tokens) The block has to be long enough to cache at all: 512 tokens on Opus 5.5, per the same docs, and shorter prompts are silently not cached. Run it twice inside five minutes and the second run should report the block under read. Wait six minutes and run it again: the block moves back to written. Multiply each count by its rate and you have the bill for that request. Claude Code reports the same counts. To check which TTL your main conversation's writes used, the docs suggest running claude -p "hello" --output-format json and reading usage.cache_creation in the result. During a session, /usage (v2.1.251 or later) adds a Prompt cache (main) line. The costs docs show it like this (one line in the terminal, wrapped here): Prompt cache (main): 14 requests · 91% of input tokens from cache · 2 misses (last 6m 10s ago, 310.2k tokens re-cached) · 1 expected rebuild (compaction or tool-result clearing) · warm (1h TTL, last activity 40s ago) The misses part says how many tokens cold turns wrote back, and a cold cache shows how long the session has been idle. If you want to go back further than /usage, each session's full transcript is kept at ~/.claude/projects/<project>/<session>.jsonl (docs). What idle compaction in 2.1.314 trades away Claude Code's answer to the coffee break is idle compaction. 2.1.299 added it to the terminal on October 14 (Classmethod has a write-up). On October 30, 2.1.314 added it "to VS Code and Claude Desktop's Code tab: a 200K+ token conversation left idle is summarized, and the summary is used on your next message if the prompt cache has expired." The idleCompaction entry lists when it runs. All of these must hold: - You're in an interactive terminal session, the VS Code chat panel, or the Desktop Code tab running locally or over SSH. - Auto-compaction is on. - The conversation is on the one-hour TTL. - Claude Code can fetch feature flags from Anthropic. - The context has reached the threshold, 200,000 tokens by default. - About an hour has passed since the last request, and your computer stayed awake. Check the size condition against your model. The same entry says that "at the default, a conversation on a 200K context window auto-compacts before it reaches 200,000 tokens." So out of the box, only sessions on a larger context window ever qualify. On a 200K window you have to lower the threshold first (see below). Compaction sends a separate summarization request that repeats your history, and the docs say that while the cache is warm, it "reads your prefix from the cache." So reading 200K tokens happens at the cheap rate, before the cache expires. When you come back, your next message writes the summary and the files Claude Code re-reads, not 200K tokens. The summary isn't free. The summarization request reads the 200K prefix, about $0.04 on Opus 5.5. The summary itself is generated output, billed at the output rate ($20 per million on Opus 5.5). The request also inherits your extended thinking setting, and the costs docs say you can't turn thinking off on Opus 5.5 and that thinking tokens bill as output. If a summary came out at 10,000 tokens, that would be about $0.04 to read, $0.20 of output plus whatever thinking it spends, and $0.08 to write it to a 1-hour cache, with the re-read files on top. Treat that $0.32 as a floor, against $1.60 for the cold rewrite. Your summary size will differ. On a subscription, all of it is plan usage rather than dollars. What compaction really costs is detail. Per the context window docs, project-root CLAUDE.md, auto memory and your plan are re-injected from disk, and Claude Code re-reads up to five recently modified files (a file over 5,000 tokens comes back as a path only). Path-scoped rules and nested CLAUDE.md files lived in the message history, so compaction "summarizes them away with everything else"; they come back only when Claude next touches a file that triggers them. Exact error messages and the dead ends you already ruled out go the same way, unless the summary happened to keep them. You'll know it happened. VS Code shows "Compacted using a summary written while you were away", and the terminal shows a line starting "Compacted while idle, before the prompt cache expired." To turn it off, set "idleCompaction": false. To change the threshold, set CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS in the env block of settings.json, with 100,000 as the floor. If you'd rather pick what survives, compact yourself before you step away. /compact focus on the failing auth test keeps what you name. /clear costs nothing when the next task is unrelated. And /rewind goes back to a prefix that is already cached instead of building a new one. Spotting the big sessions before you walk away I build Hermes IDE, so weigh this section with that in mind. Hermes runs Claude Code, Codex and other agents side by side, each in a real terminal. With several sessions open, the question before you walk away is which of them are big. Hermes 2.3.4, released October 15, added a context meter to each session that shows how full the conversation is and offers Compact when it gets close to full. The sidebar shows a context gauge for each session, and the status strip shows the session's token total and its cost. That figure is either what the agent itself reports or an estimate from its transcript, labelled as an estimate. !A Claude Code session in Hermes after pressing the Context chip, showing Claude Code's /context breakdown, per-session context gauges in the sidebar, and a status strip with the token total and estimated cost A Claude Code session after pressing the Context chip: Claude Code's /context breakdown (44.4k of 1M tokens, 4%), the per-session context gauges in the sidebar, and the status strip with the token total and estimated cost. That gives you a habit for the break: scan the gauges, and for any session near 200K that sits between tasks, compact it with a focus before you leave. The Commands list above each session includes Compact, and a command only runs when the agent is waiting, so it never lands in the middle of a turn. When you come back, watch how far the session's spend figure jumps after your first message; that jump is roughly what the return cost. What Hermes doesn't do: it doesn't know whether a session's prompt cache is warm or cold, or which TTL it is on. For that, run /usage inside Claude Code and read the Prompt cache (main) line. Hermes also doesn't compact anything on its own. You click Compact, or Claude Code's own idle compaction does it. !The action bar above a Claude Code session in Hermes with the Commands list open, showing pinned Context, Model, Plan and Review, then built-in commands such as Compact, Usage and Diff The action bar above a Claude Code session (Prompts, Context 4%, Model, Plan, Review, / Commands) with the Commands list open: pinned Context, Model, Plan and Review, then built-in commands such as Compact, Usage and Diff. Hermes is free to download, source-available under BSL 1.1, and runs on macOS, Windows and Linux. The code is on GitHub. It isn't affiliated with Anthropic, Nous Research or any agent vendor. Do you let idle compaction summarize your long sessions, or did you turn it off the first time it dropped something you needed? --- If this was useful A cold cache is a cost regression you only see if you trace tokens per request and split reads from writes. Observability for LLM Applications is my book on doing that for LLM features in production: traces, evals, cost and quality, and the dashboards that catch a $0.04 turn quietly becoming a $1.00 one. ![Observability for LLM Applications — the book](amazon.de)

    2 reactions · 1 comment
  6. YouTube · · YouTube description · Hilay Trivedi

    Build your own AI agent harness from scratch in Python What is an AI harness, and how do tools like Claude Code work underneath? I build one from scratch in plain Python, one layer at a time, using a car as the map. For beginners moving into AI engineering. No framework, every part visible. Code for every version (one branch per version, v1 to v6): HILAYTRIVEDI/harness-demo Chapters: 00:00 What is a harness? The car analogy 01:35 V1 The engine: one LLM call 04:14 V2 The chassis: the agent loop 05:57 V3 The wheels: tools 12:58 V4 Steering and GPS: system prompt and streaming 18:55 V5 Brakes and saved places: permissions and memory 27:01 V6 The fuel gauge: context window and auto-compact 29:36 What's next Tools mentioned: • Anthropic Python SDK: anthropics/anthropic-sdk-python • Claude Code: anthropic.com #AI #AIAgents #ClaudeCode Connect with me: • LinkedIn: linkedin.com • GitHub: github.com/HILAYTRIVEDI

    17 likes · 18 comments · 707 views
  7. Anthropic Python v2.2.0 adds usage and cost reports by dimension, marking older reports legacy. Worth reviewing if you track API spend. v2.2.0 新增按维度划分的用量与成本报告,旧报告标为 legacy。维护 API 成本看板的团队可核对变更。 github.com/anthropics/anthropic-sdk-python/releas… t.co

    1 like · 44 views
  8. @GaryMarcus @sama @OpenAI Here’s a concrete example from @AnthropicAI’s own Python SDK, since they both do it. An agent’s file-write tool can hang the entire async event loop when writing to a FIFO. I reproduced it, submitted a fix and regression test in July. PR remains open. anthropic-sdk-python#1752

    6 views
  9. Here’s a concrete example from @AnthropicAI’s own Python SDK. An agent’s file-write tool can hang the entire async event loop when writing to a FIFO. I reproduced it, submitted a fix and regression test in July. PR remains open. anthropic-sdk-python#1752

    5 views
  10. Zenn · · @467

    Airflow × AI Pluginを試す 概要 いつの間にかAirflowでLLM・AI Agent向けのProviderがサポートされていたので、ClaudeCode × Airflowをいくつか試してみる。 事前準備 Airflow3.1をQuick Start通りにインストールし、standaloneで起動できるようにしておく。 standaloneにおいての実行で、forkされた子プロセスからHTTPS(claude)を呼ぶと不安定になるので、DAGの実行にはairflow dags test <dag名>を用いる。 Claude ConsoleでAPIを発行しておく。 試したことないが、ローカルLLMもサポートされている。(link) インストール provideインストール pip install 'apache-airflow-providers-common-ai[anthropic]' airflow connectionの追加 airflow connections add my_claude_conn \ --conn-type pydanticai \ --conn-password 'sk-ant-xxxxxxxx' \ --conn-extra '{"model": "anthropic:claude-haiku-5-5"}' localhost 試してみる @task.llm / LLMOperator airflow.apache.org 無難なプロンプトを投げるようなDecorator / Operator。 pydantic_aiにおいて、prompt返答の型安全性を実現し、pydantic_aiからauthropic-sdkを呼び出しClaudeへ接続している。 各種パラメータについて promptとsystem_promptがある。system_promptがagentに対するpromptであり、promptが具体的なタスクのprompt。 airflow.apache.org agent = self._create_agent(output_type=self.output_type, instructions=self.system_prompt) result = self._run_llm(context, agent, self.prompt, usage_limits=usage_limits) usage_limitsにおいて、tokenのlimitなどを設けることができる。 require_approvalにおいて、人手による承認を設けることができる。 実装例.おすすめの本を紹介してもらう データエンジニアとしてのおすすめの本を紹介してもらう実装を試す。 dag.py from datetime import timedelta from pydantic import BaseModel from airflow.providers.common.compat.sdk import dag, task @dag def my_pipeline(): class Book(BaseModel): title_english: str title_ja: str price: str class Books(BaseModel): books: list[Book] @task.llm( llm_conn_id="my_claude_conn", system_prompt="あなたはデータエンジニアのスペシャリストです", output_type=Books, allow_modifications=True, ) def recommend(topic: str): 以下のreturnがtask.llmに渡すpromptになる return f"{topic}として読むべき本を3冊おすすめしてください。" @task def show(result: dict): print("=== おすすめの本 ===") for i, book in enumerate(result["books"], start=1): print(f"{i}. {book['title_ja']}") print(f" 原題: {book['title_english']}") print(f" 価格: {book['price']}") show(recommend("データエンジニア")) my_pipeline() 実行した結果が以下です。@task.llmのoutput_typeに合った形(Books)でresult["books"]が返ってきていることがわかります。 === おすすめの本 === 1. データ指向アプリケーションデザイン 原題: Designing Data-Intensive Applications 価格: 約5,720円(税込) 2. データエンジニアリングの基礎 原題: Fundamentals of Data Engineering 価格: 約4,400円(税込) 3. データウェアハウス工具箱 原題: The Data Warehouse Toolkit 価格: 約6,600円(税込) 試しにrecommend関数に指定したpromptをoutput_typeに沿っていない形にして実行してみる。 ・・・ def recommend(topic: str): return "今日の天気は?" すると以下のようにエラーになる。あまりエラーが判りやすくはないですね。 2026-10-25T04:20:54.338091Z [error ] [DAG TEST] Error running task <TaskInstance: my_pipeline.recommend manual__2026-10-25T04:20:50.026474+00:00 [queued]> [airflow.sdk.definitions.dag] loc=dag.py:1419 Traceback (most recent call last): ・・・ File "/Users/srn221b/airflow/airflow_venv/lib/python3.12/site-packages/airflow/sdk/api/client.py", line 171, in get_json_error raise err airflow.sdk.api.client.ServerResponseError: Server returned error @task.agent / AgentOperator airflow.apache.org toolやskillなどを用いてLLMに考えてもらいながらtaskを実行するときに使えるDecorator / Operator。 claudeへの接続の仕方などは@task.llmと同様。 各種パラメータについて toolsetsにおいて、Database(SQLToolset)・AgentSkill(AgentSkillsToolset)など、LLMに答えてもらうにあたり利用したいtoolを設定できる。 capabilitiesにおいて、Thinking、WebSerachなどの能力を指定できる。 前回の結果を再利用する手段として3つがサポートされている。 durable cache_prompt message_history 目的 失敗したときのやり直しを安く、確実にする 同じ入力の送り直しを安くする 会話を次の実行に引き継ぐ 再利用する範囲 同じタスクインスタンスのリトライ間 1回の実行の中で繰り返すリクエスト間 別のタスク実行(別の DAG run など)の間 どこに保存されるか Airflow 側のジャーナル(state store か cache path) LLM プロバイダー側のキャッシュ XCom(キーは message_history) 再利用するときの動き 記録済みのステップはLLMもツールも呼ばずに結果を再生する LLMは毎回呼ぶ。入力トークンが割引されるだけ 過去の会話を前提にして、新しくLLMを呼ぶ コストへの効果 再生したステップは0(usage にも数えない) 入力トークン料金の一部が割引 減らない(履歴の分だけ入力が増える) 既定値 False True None(1回で終わる会話) ※表はAIが生成 実装例.サンプルデータの自動作成 今回以下のようなサンプルデータの自動生成と確認をしてくれる実装を試してみる。 seed_orders:ローカルDBに接続するためにSQLToolset、サンプルデータ作成時の注意点を考慮させるためにAgentSkillsToolsetを持たせます。 report:ローカルDBに接続するためにSQLToolset、slackに接続するためにHookToolset(SlackWebhookHook..)を持たせます。 また事前にpostgressへのconnectorをpostgres_default、slackへのconnectorをslack_webhook_defaultとして作成しておきます。 skills/seed-orders/SKILL.md --- name: seed-orders description: ケーキ屋の orders テーブルに初期データ(テスト用の注文)を投入するときの条件と手順。初期データの投入を頼まれたときに使う。 --- 初期データ投入の注意点 ・・・ dag.py from pathlib import Path from airflow.providers.common.ai.toolsets import HookToolset from airflow.providers.common.ai.toolsets.skills import AgentSkillsToolset from airflow.providers.common.ai.toolsets.sql import SQLToolset from airflow.providers.common.compat.sdk import dag, task from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook @dag(tags=["example"]) def example_agent_decorator(): create_orders = SQLExecuteQueryOperator( task_id="create_orders", conn_id="postgres_default", sql=[ "DROP TABLE IF EXISTS orders", """ CREATE TABLE orders ( id serial PRIMARY KEY, customer text, product text, category text, amount numeric(10, 2), created_at date ) """, ], ) @task.agent( llm_conn_id="my_claude_conn", system_prompt="あなたはデータエンジニアです。ツールを使ってデータベースを操作してください。", toolsets=[ SQLToolset( db_conn_id="postgres_default", allowed_tables=["orders"], allow_writes=True, ), AgentSkillsToolset( sources=[str(Path(file).parent / "skills")], exclude_tools={"run_skill_script"}, ), ], ) def seed_orders(): return "seed-orders スキルの手順に従って、orders テーブルに初期データを入れてください。" @task.agent( llm_conn_id="my_claude_conn", system_prompt="あなたはデータアナリストです。ツールを使って質問に答え、回答は日本語で書いてください。", toolsets=[ SQLToolset( db_conn_id="postgres_default", allowed_tables=["orders"], ), HookToolset( SlackWebhookHook(slack_webhook_conn_id="slack_webhook_default"), allowed_methods=["send_text"], tool_prefix="slack", ), ], ) def report(question: str): return ( "orders テーブルは、ケーキ屋の検証用に自動生成した注文データです。\n" "customer は顧客、product と category は買ったもの(ケーキ・焼き菓子・ドリンク)です。\n" f"このデータを使って、次の質問に答えてください: {question}\n" "Slack に1回だけ送ってください。送ったあと、送った内容をそのまま答えてください。" ) create_orders >> seed_orders() >> report("カテゴリ別の売上と、売れ筋の商品、売上が特に多かった月を教えてください。") example_agent_decorator() 実行してみると、途中でLLMがSQLを組み立てて考えてくれているログが見れる。 ・・・ 2026-10-25T05:58:42.234507Z [info ] ::group::Tool call: query [airflow.task.operators.airflow.providers.common.ai.decorators.agent._AgentDecoratedOperator] loc=logging.py:64 2026-10-25T05:58:42.243900Z [info ] Running statement: SELECT count(*) AS n, min(created_at) AS min_date, max(created_at) AS max_date, count(DISTINCT customer) AS customers, min(amount) AS min_amt, max(amount) AS max_amt, sum(CASE WHEN created_at BETWEEN DATE '2025-12-20' AND DATE '2025-12-25' THEN 1 ELSE 0 END) AS dec_rush_rows, sum(CASE WHEN amount % 50 <> 0 THEN 1 ELSE 0 END) AS non50_amounts FROM orders, parameters: None [airflow.task.hooks.airflow.providers.postgres.hooks.postgres.PostgresHook] loc=sql.py:896 ・・・ また完了するとDatabaseへデータの挿入が行われ、SlackへSummary Reportされていることが確認できる。 id | customer | product | category | amount | created_at -----+-------------+--------------------+----------+---------+------------ 1 | customer_3 | チョコレートケーキ | ケーキ | 650.00 | 2026-06-23 2 | customer_3 | マドレーヌ | 焼き菓子 | 150.00 | 2025-11-27 3 | customer_3 | 紅茶 | ドリンク | 550.00 | 2026-09-09 4 | customer_1 | コーヒー | ドリンク | 400.00 | 2026-07-23 5 | customer_7 | チーズケーキ | ケーキ | 500.00 | 2026-07-02 6 | customer_1 | ショートケーキ | ケーキ | 650.00 | 2025-12-21 ・・・ LLM Retry Policy と ClassifierRetryPolicy ! Airflow>=3.3.0が必要 Airflow3.3.0からRetry policiesというのができた。これを用いれば、LLMにタスクの失敗時のリトライ判断を委ねることができる。 種類としては、LLMRetryPolicyとClassifierRetryPolicyがサポートされ、いずれも以下のようにタスクのretry_policyに指定して使用する。 snowflake_policy = ClassifierRetryPolicy(・・・) ・・・ snowflake_policy = LLMRetryPolicy(・・・) ・・・ @task(retries=5, retry_policy=snowflake_policy) def query_snowflake(): ・・・ ではLLMRetryPolicyとClassifierRetryPolicyで何が異なるのかというと以下である。 LLMRetryPolicy 責務:モデルがRetryに関連するエラーの分類・動作をすべて決める。 ClassifierRetryPolicy 責務:モデルは分類だけ、動作はコードで定義した表で決める。 snowflake_policy = ClassifierRetryPolicy( ・・・ min_confidence=0.8, # categoriesの挙動を実行を決めるときの分類のmin確信度 categories={ Warehouseが停止したと分類したときの挙動 "warehouse_suspended": ErrorCategory( "The warehouse is suspended and will auto-resume.", delay=timedelta(seconds=30) ), tokenがexpiredしたと分類したときの挙動 "token_expired": ErrorCategory( "A JWT or session token expired; the token rotates on its own.", delay=timedelta(seconds=30) ) ・・・ またいずれもfallback_rulesでモデルが判断(分類)できなかったときのfallbackを設定できる。 実装例.モデルに再実行を委ねてみる rate limitエラーが出た場合と、bad dataエラーが出た場合に、モデルはどのように再実行を行うのかを試してみる。 from datetime import timedelta from airflow.providers.common.ai.policies.retry import LLMRetryPolicy from airflow.providers.common.compat.sdk import dag, task from airflow.sdk.definitions.retry_policy import RetryAction, RetryRule llm_policy = LLMRetryPolicy( llm_conn_id="my_claude_conn", timeout=30.0, fallback_rules=[ RetryRule(exception=ConnectionError, action=RetryAction.RETRY, retry_delay=timedelta(seconds=10)), RetryRule(exception=PermissionError, action=RetryAction.FAIL), ], ) @dag(catchup=False, tags=["sample", "retry_policy", "llm"]) def llm_retry_policy_sample(): @task(retries=3, retry_delay=timedelta(minutes=1), retry_policy=llm_policy) def rate_limited(): # rate limit エラー raise RuntimeError("429 Too Many Requests: Rate limit exceeded. Retry after 60 seconds.") @task(retries=3, retry_delay=timedelta(minutes=1), retry_policy=llm_policy) def bad_data(): # bad data エラー raise ValueError("Column 'user_id' expected type INT but got STRING in row 42.") rate_limited() bad_data() llm_retry_policy_sample() 実行してみると、rate limitエラーの方だけRetryが4回された。 人間としても、bad dataエラーの場合は再実行しても意味がない・rate limitエラーの場合は再実行したら直るかもと思うので、挙動としては正しいであろう。 ちなみに、LLMRetryPolicyにinstructionsが指定されていない場合、DEFAULT_INSTRUCTIONSが参照されるようだった。 そのほかにも そのほかにも以下がサポートされている。 @task.llm_branchを用いてLLM駆動型タスク分岐。 後続にA or Bのタスクがある場合、どちらを実行するかをLLMが決めてくれる。 @task.llm_sqlを用いて自然言語->sqlをbuildするタスクの作成。 sqlglotのAST解析を使って出力を検証している。 @task.llm_schema_compareを用いてDatabaseを横断したスキーマドリフト検出。 詳細は次のページを参照すれば確認できる。 airflow.apache.org どういった活用の仕方がされているか。 Airflow公式ブログ(link]では次のような活用の仕方が紹介がされている。 問い合わせチケットの振り分け(@task.llm_branch) レポートの要約と人による承認(@task.llm_file_analysis + enable_hitl_review=True) エージェントによるDB分析(@task.agent + SQLToolset)

Latest stargazers

The last 10 distinct accounts we observed this year.

Most active participants

PR, issue, comment & review events in the past year.

Packages

1
PackageVersionDownloads · 30dTrend · 30d
anthropicv2.2.0
v2.2.0
≥128.5M

README badges

Embed a badge in your README or website.

  • anthropics/anthropic-sdk-python reached #10 in daily mentions on gitwal · Nov 3, 2026
Live mentions · last 30 days
anthropics/anthropic-sdk-python mentions in the last 30 days