
ليه الـ Streaming مش مجرد شكل؟ الـ requests الطويلة في Claude API محتاجاه
- كاتب موثّق
- Claude API
محتويات المقال
stop_reason: "max_tokens"، فحد علّى الـ max_tokens من 16000 لـ 64000. التشغيل اللي بعده وقع قبل ما يبعت ولا request: الـ Python SDK طلّع ValueError ورفض request بالحجم ده من غير streaming. والحل السريع، timeout=1800، خلّى الـ error يختفي. ودلوقتي في ليالي التقرير بياخد ساعة، وليالي تانية بيفشل من غير أي رد من Anthropic، ومحدش عارف يكرر المشكلة على اللابتوب بتاعه.
الفكرة الغلط الشائعة
كل demo للـ streaming عبارة عن chat box والكلام بيظهر كلمة كلمة، فشكله feature خاصة بالـ front-end. الاتنين في الآخر بيدّوك نفس الـ Messageobject، فالفرق باين إنه بس امتى تشوف النص.وإنت بتطوّر، الـ prompts قصيرة والإجابات بترجع في ثواني، فالـ connection عمره ما بيقعد ساكت كتير. والتعامل مع الـ events شكله شغل زيادة لـ background job محدش بيتفرج عليه.
اللي بيحصل فعلًا
الـ call العادي سكوت طويل
messages.create()، الـ API بيبعت الـ response لما آخر token يتولّد، ولحد ساعتها الـ HTTP connection مفيهوش أي حاجة. والـ output الطويل بياخد وقت: Claude Opus 5.5 بيقبل max_tokens لحد 128K، والـ adaptive thinking عنده شغال دايمًا، فممكن يصرف جزء من الوقت ده بيفكر قبل أول كلمة. والـ docs بتقول السكوت ده بيعمل إيه في الشبكات الحقيقية: "Some networks might drop idle connections after a variable period of time, which can cause the request to fail or time out without receiving a response from Anthropic".
ValueError "if a non-streaming request is expected to take longer than approximately 10 minutes"، والـ thinking docs بتحط الخط ده عند max_tokens أكبر من 21,333 وبتسميه "a client-side validation, not an API restriction". ولما request يعدّي الـ timeout بتاعه، الـ client بيقفل الـ connection ويعمل retry "without receiving a response". والـ retry ده request جديد، يعني الـ generation بيبدأ من الأول خالص.
الـ streaming بيخلّي الـ connection شغال
stream=True، أو messages.stream() بتاعة الـ SDK، الـ API بيبدأ يرد على طول بـ . والـ stream ليه ترتيب ثابت: message_start، وبعدين لكل content block فيه content_block_start والـ deltas بتاعته وcontent_block_stop، وبعدين message_delta وفي الآخر message_stop، وممكن events من نوع ping تيجي في النص. وبكلام الـ docs، الـ .stream() "keeps the HTTP connection alive with server-sent events". والـ SDK كمان بيفعّل TCP keep-alive على الـ sockets بتاعته، وصفحة الـ errors بتنصح بالـ streaming أو الـ Message Batches API "for long-running requests, especially those over 10 minutes".
مش محتاج UI عشان تعمل streaming
stream.get_final_message() بترجّع "the complete Message object, identical to what client.messages.create() returns". والـ docs بتقول إنها "especially useful for requests with large max_tokens values". والكود اللي بعد الـ call مبيتغيرش: تقرا الـ ، وبعدين الـ content blocks.
الـ errors ممكن تيجي بعد الـ 200
error جوه الـ stream، ومثال الـ docs هو overloaded_error "which would normally correspond to an HTTP 529 in a non-streaming context". ولو بتعمل parse للـ events بنفسك، فيه تفصيلتين كمان: أرقام الـ usage في message_delta تراكمية، فمتجمعهاش على بعض، وممكن events بأنواع جديدة تظهر، فتجاهل اللي متعرفوش.
نصلّح job التقارير
Message واحد:
import anthropicclient = anthropic.Anthropic()def write_report(diff: str) -> str: # The SDK raised ValueError at 64000 tokens, so: "give it 30 minutes" reply = client.with_options(timeout=1800).messages.create( model="claude-opus-5-5", max_tokens=64000, messages=[{"role": "user", "content": f"Report for:\n{diff}"}], ) # nothing arrives on this connection until the last token return next(b.text for b in reply.content if b.type == "text")print(write_report(DIFF)[:40])import anthropicclient = anthropic.Anthropic()def write_report(diff: str) -> str: with client.messages.stream( model="claude-opus-5-5", max_tokens=64000, messages=[{"role": "user", "content": f"Report for:\n{diff}"}], ) as stream: # events keep the connection busy message = stream.get_final_message() # same Message as create() if message.stop_reason == "max_tokens": raise ReportTruncated(message.usage.output_tokens) return next(b.text for b in message.content if b.type == "text")print(write_report(DIFF)[:40])text، مش من content[0]: لما الـ thinking يبقى شغال ممكن block من نوع thinking ييجي الأول، وفي Claude Opus 5.5 النص بتاعه فاضي افتراضيًا.
لما الـ stream يتقطع في النص
create() من غير streaming | stream() بالـ streaming | ||
|---|---|---|---|
max_tokens | |||
error بعد الـ 200 | |||
Message إزاي | get_final_message() | ||
تطبقها إزاي في مشروعك
دوّر على الـ calls الساكتة دوّر على messages.createاللي فيهاmax_tokensكبير، وعلى أيtimeout=اتضاف بس عشان يسكّت الـValueErrorبتاع الـ SDK.اعملها streaming، حتى من غير UI بدّل create()بـmessages.stream()وget_final_message(). والكود اللي بيقرا الـ response يفضل زي ما هو.فضل اقرا الـ stop reason الـ stream اللي خلص من غير مشاكل ممكن برضه يقف بـ max_tokens. شوفstop_reasonقبل ما تحفظ النتيجة.جهّز نفسك لـ stream يتقطع احفظ النص اللي وصلك. ومع Claude 4.6 واللي بعده، كمّل بـ user message فيها النص ده، مش بـ assistant prefill، واعمل الـ tool calls والـ thinking من الأول. انقل الشغل اللي محدش مستنيه للـ Batches لو محدش هيقرا الـ output على طول، ابعته من خلال الـ Message Batches API واعمل poll على النتايج.
الخلاصة
الـ call العادي بيسيب الـ connection ساكت لحد آخر token، والـ connections الساكتة بتتقطع. الـ Python SDK بيطلّع ValueErrorلما request من غير streaming متوقع ياخد أكتر من 10 دقايق تقريبًا؛ اعتبره نصيحة، مش عقبة تتخطاها بـ timeout أكبر.messages.stream()معget_final_message()بيديك نفس الـMessageمن غير UI ولا تعامل مع events.في الـ stream، الـ errors ممكن تيجي بعد الـ 200 كـ events من نوع error.عشان تكمّل stream اتقطع مع Claude 4.6 واللي بعده، ابعت النص الناقص في user message، مش كـ prefill.
التعليقات (0)