بث استجابات الذكاء الاصطناعي
تعلّم كيفية بث الرموز من نموذج ذكاء اصطناعي في الوقت الفعلي، ليشاهد المستخدمون الإجابات تظهر تدريجيًا بدلًا من انتظار الاستجابة الكاملة.
بث استجابات الذكاء الاصطناعي درس مجاني في AI Powered SaaS: Stripe + Auth + Billing + Deploy على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في AI Powered SaaS: Stripe + Auth + Billing + Deploy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة AI Powered SaaS: Stripe + Auth + Billing + Deploy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Stream Responses?
Large language models can take several seconds to produce a full answer. Streaming sends tokens to the client as they are generated, so the user sees text appear word by word.
- Lower perceived latency
- Users can start reading immediately
- Feels conversational, like a chat
How Streaming Works
Streaming relies on a long-lived HTTP connection. The server keeps the response open and pushes chunks as they arrive from the model provider.
Two common transports are Server-Sent Events and chunked HTTP responses. Most AI SDKs default to SSE.
Enabling Stream Mode
Most AI APIs accept a stream: true flag. Instead of a single JSON object you receive a sequence of small JSON events, each containing a piece of the answer.
const response = await client.chat.completions.create({
model: "gpt-4o-mini",
stream: true,
messages: [{ role: "user", content: "Explain streaming." }],
});Reading the Stream on the Server
The SDK returns an async iterable. You loop over it and forward each delta to your client.
for await (const chunk of response) {
const token = chunk.choices[0].delta.content || "";
process.stdout.write(token);
}Forwarding to the Browser with SSE
Wrap each token in an SSE data: frame. Set the right headers so the browser keeps the connection open.
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
for await (const chunk of aiStream) {
const t = chunk.choices[0].delta.content || "";
res.write("data: " + JSON.stringify({ t }) + "\n\n");
}
res.end();Consuming the Stream in the UI
On the client, use the EventSource API or fetch with a reader. Append each token to your displayed message state.
const es = new EventSource("/api/chat");
es.onmessage = (e) => {
const { t } = JSON.parse(e.data);
setMessage((prev) => prev + t);
};Showing a Typing Indicator
While tokens stream in, show a blinking cursor or animated dots. Remove it once the stream closes. This reinforces the feeling that the AI is actively responding.
Handling Stream Errors
Connections can drop mid-stream. Always handle the error event and close the source. Offer a retry button and keep whatever partial text was already received.
es.onerror = () => {
es.close();
showRetry();
};Cancelling a Stream
Let users stop a long answer. With fetch you abort via an AbortController; with EventSource you call close(). Cancelling also saves token cost.
const controller = new AbortController();
fetch("/api/chat", { signal: controller.signal });
// later:
controller.abort();Cost and Token Accounting
Streaming does not change billing: you still pay for total tokens generated. Count tokens as they arrive, or read the final usage event some providers send when the stream ends.
Backpressure and Buffering
If the client reads slower than the model produces, tokens queue up. Most runtimes handle this automatically, but for very high throughput consider buffering small batches of tokens before flushing to reduce write overhead.
Quick Check
Test your understanding of streaming AI responses.
Recap
You learned to stream AI responses end to end:
- Enable
stream: trueon the API call - Iterate over chunks server-side and forward via SSE
- Append tokens in the UI with a typing indicator
- Handle errors, cancellation, and token accounting
Streaming makes AI features feel fast and conversational.
تعلم AI Powered SaaS: Stripe + Auth + Billing + Deploy مع معلم ذكاء اصطناعي — مجانًا
اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.
- الدورات
- 12
- الدروس
- 48
الأسئلة الشائعة
هل درس «بث استجابات الذكاء الاصطناعي» مجاني؟
نعم — نص درس «بث استجابات الذكاء الاصطناعي» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Powered SaaS: Stripe + Auth + Billing + Deploy، انتقل إلى CoddyKit PRO. تتضمن دورة AI Powered SaaS: Stripe + Auth + Billing + Deploy 4 دروس في المجموع.
ماذا ستتعلم في «بث استجابات الذكاء الاصطناعي»؟
تعلّم كيفية بث الرموز من نموذج ذكاء اصطناعي في الوقت الفعلي، ليشاهد المستخدمون الإجابات تظهر تدريجيًا بدلًا من انتظار الاستجابة الكاملة. تتمرن على AI Powered SaaS: Stripe + Auth + Billing + Deploy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ AI Powered SaaS: Stripe + Auth + Billing + Deploy؟
لا تُشترط خبرة سابقة. AI Powered SaaS: Stripe + Auth + Billing + Deploy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «بث استجابات الذكاء الاصطناعي»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس AI Powered SaaS: Stripe + Auth + Billing + Deploy هذا؟
نعم. كل درس في AI Powered SaaS: Stripe + Auth + Billing + Deploy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تكامل API لخدمات الذكاء الاصطناعي
- أساسيات هندسة الأوامر
- دمج الذكاء الاصطناعي في واجهة المستخدم
- بث استجابات الذكاء الاصطناعي