HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 42“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
AI SDKs and Streaming UI Integration
TechLearningPro's lesson panel, the staff refund desk, and a spike in the marketing site each streamed model output differently.
Course progress0%
Focus
23 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 42 · AI Agents, Workflow Automation and Integrations
Lesson Overview
TechLearningPro's lesson panel, the staff refund desk, and a spike in the marketing site each streamed model output differently. One page imported a vendor UI SDK in the browser and followed that package's message list. Another used the Server-Sent Events contract from Lesson 16. A third pasted a helper that streamed tool-call fragments into the same bubble as the answer. Learners saw half a JSON tool payload, a "credit posted" sentence that was only a draft, and, on one spike, a request path that only worked if a key lived in the client bundle. The key never shipped — a reviewer caught it — but the three protocols remained.
The fix is a UI event port the panel already understands, with any vendor AI SDK behind a server adapter. The browser speaks the Lesson 16 events, plus two agent statuses this lesson adds: status and proposal. Tokens append to a draft. A proposal is data for a later approval. It is not an effect, and it is not rendered as the assistant's answer. SDKs that offer chat hooks, stream writers, or data-stream protocols can be useful on the server. Their function names change. Verify them in the current docs for the version you pin. This lesson does not call those functions. It implements the port.
Familiarity with fetch and AbortController in the browser. No provider account.
What is AI SDKs and Streaming UI Integration?
AI SDKs, in this lesson, means libraries that wrap a model provider and often a chat UI: hooks that post a message, parsers for a vendor's stream, and helpers that write a response body. Streaming UI integration means connecting that stream to TechLearningPro's panel so the learner sees tokens promptly and never sees a tool side effect happen inside the bubble.
Vendors ship these SDKs because streaming HTTP is fussy and because each lab uses a different chunk format. Teams adopt them to save a week, then discover the hook's message shape in the React tree and a secret in a client example. The durable design is the one Lesson 16 started: your server owns the model call, the response is SSE, and the panel reduces a closed event union. An SDK can produce those events. It is not the union.
You will see documentation for chat hooks, text streams, and "data stream" protocols. Names and event discriminators move between major versions. Treat every snippet in a vendor doc as versioned. The code in this lesson is the contract the panel tests. When an adapter imports an SDK, the module comment records the package version and the doc URL you verified.
Term
Meaning in this lesson
UI event
TutorEvent, the only type the reducer accepts
Token
A text fragment of the draft
Status
streaming, paused, or awaiting_approval
Proposal
A named action with arguments, not executed
SSE
The wire format from Lesson 16
Reducer
Pure function from state and event to state
Adapter
Server module that maps an SDK or ModelPort into events
Turn id
clientTurnId, idempotency key for one send
Why Do We Need It?
text
Three stream protocols in the UI
|
v
Tool JSON renders as the answer, drafts look final,
a sample puts a key near the client
|
v
One TutorEvent union over SSE
|
v
Tokens fill a draft, proposals stay beside it,
secrets stay on the server
Benefits:
The panel tests do not import a vendor package.
Stop and abort use one signal.
A refund workflow can say paused without pretending the credit moved.
Swapping a provider changes the adapter, not the reducer.
Lesson 43 can accept a proposal only after an allow-list check that this UI does not skip.
Real World Example
The lesson player loads the lesson document immediately. The learner presses Explain. The client sends clientTurnId and the question to your API with the session cookie. The server authenticates, checks the lesson scope, and opens ModelPort through a stream adapter. SSE sends meta, then token events, then done. The reducer appends tokens under the label "Draft." If the model output includes a tool-shaped proposal the server is willing to surface, the adapter emits proposal after it has parsed a complete object. The panel lists "Suggested action: open glossary" as a row that does nothing until a later, explicit command.
Staff refund UI uses the same reducer. When Lesson 41 pauses, the server sends status with paused and the finding text as tokens that already finished, or as a single token if you buffer staff findings. The button label is "Review finding." It is not "Credit posted."
Banks stream fraud-review notes to an analyst with the same split: narrative tokens versus a recommended hold that is not yet a hold. Amazon's customer chat and Microsoft's copilot side panels stream prose while keeping order-cancel buttons on a separate confirmation. Google's model APIs and the various UI SDKs differ in chunk shape. Netflix-style device UIs keep a thin event protocol so a player can ship even when the recommendation service changes. TechLearningPro's thin protocol is TutorEvent.
Internal Working
The panel sets status to streaming only after an explicit send, and it stores clientTurnId.
fetch posts to your route with AbortSignal. The route rejects a second in-flight turn id.
The route writes Content-Type: text/event-stream and the anti-buffering headers you already used in Lesson 16.
The first block is meta with requestId and promptVersion. The reducer stores the id and still shows a draft label.
Each text fragment is token. The reducer appends it. It does not run Markdown that could include raw HTML from the model. Render text, or sanitize with the lesson player's existing sanitizer.
A complete, schema-valid suggestion becomes proposal. The reducer pushes it onto proposals. It does not concatenate the JSON into text.
A workflow pause becomes statuspaused or awaiting_approval. The reducer sets that status and stops expecting tokens unless another token arrives before done.
done freezes the draft as a finished turn and records finish as stop or length.
error freezes whatever draft exists and records timeout, aborted, or unavailable. aborted is what the panel's Stop button produces.
The server does not emit a proposal it has not parsed. Partial tool JSON is buffered in the adapter until it is valid or until the stream ends, in which case it is dropped, not shown.
Architecture
flowchart LR
subgraph client [Browser]
Panel[Lesson or staff panel]
Reducer[Event reducer]
end
subgraph server [Application server]
Route[Session route]
Encoder[SSE encoder]
Adapter[Stream adapter]
end
subgraph edge [Edges]
Model[ModelPort or workflow runtime]
Sdk[Optional SDK adapter]
end
Panel --> Route
Route --> Adapter
Adapter --> Model
Sdk --> Adapter
Adapter --> Encoder
Encoder --> Panel
Panel --> Reducer
text
Explicit send + clientTurnId + AbortSignal
|
v
POST /api/assistant/stream (cookie session, no provider key)
|
v
Stream adapter
|
+--> ModelPort stream or buffered complete
+--> optional SDK, pinned, server-only
|
v
TutorEvent: meta | token | status | proposal | done | error
|
v
SSE blocks
|
v
Reducer -> draft text, proposals[], status
|
x proposal does not call a tool
x vendor chunk types do not reach the reducer
Deep Dive
What the panel is allowed to believe
Until done, the string on screen is a draft. Lesson 22's copy applies: "Draft" rather than "Saved" or "Posted." length means the token cap cut the draft. Show that it is incomplete. paused means a human is required. Show the finding and the review action. Do not show a success state for a credit.
Proposals are not tokens
Tool-calling models often stream an argument object in pieces. If you append those pieces to the answer, the learner reads syntax, and a later parser may disagree with what was displayed. Buffer in the adapter. Emit proposal once, with name and arguments that match a small checked shape. Unknown names can still be displayed as disabled rows, or dropped. This lesson drops unknown names so the UI cannot advertise a tool the product has not listed. Execution waits for Lesson 43's allow-list and Lesson 37's executor.
Idempotent turns
clientTurnId is a UUID the panel creates for one send. The server stores the event list or the final text for that id and tenant. A retry after a dropped connection replays stored events or the final result. It does not open a second model stream. This matches the capstone replay rule from the knowledge assistant: one turn, one bill.
SDK adapter shape
text
SDK or provider stream (private to the adapter file)
|
v
map to TutorEvent
|
v
encode SSE
The adapter may buffer, drop unknown chunks, and convert provider errors into timeout, aborted, or unavailable. It logs the provider id and the turn id. It does not log the key or the full prompt. If the SDK's docs show a client component that takes an API key prop, do not use that component. Call your route from the panel.
Resume and event ids
SSE id fields let a reconnecting client send Last-Event-ID. The lab reducer also ignores an event whose id was already applied, so a replay cannot double-append tokens. Ids are decimal strings that increase inside one turn. They are not tenant data.
Staff versus learner copy
The same reducer can drive both panels. The surrounding chrome differs. The learner panel never receives awaiting_approval for a refund. The route that serves learners does not subscribe to refund runs. Sharing a reducer is not sharing an authorization path.
Code Examples
Place the contract in packages/stream-ui/src/. The panel imports the reducer and the types. The server imports the encoder.
Arguments are a string map in the lab so the reducer stays free of a schema library. A production adapter may allow a richer JSON value only after validation, and it still must not execute it.
Unknown proposal names are skipped. lookup_ticket is the only name this adapter will emit, and emitting it does not call executeSupportTool. refund_course is dropped.
The tests never open a socket and never read an environment variable.
Client send sketch
The panel creates one AbortController per turn, passes signal to fetch("/api/assistant/stream"), and on Stop calls abort(). Parse SSE blocks with the Lesson 16 parser and call reducePanel. Credentials are the session cookie (credentials: "include" if you cross origins you already trust). There is no provider header in the browser.
Architecture Diagram
text
Panel (explicit send, Stop)
|
v
fetch your API with session cookie and AbortSignal
|
v
Route checks session, lesson scope, clientTurnId
|
v
toTutorEvents
|
+--> TokenSource (ModelPort stream adapter or buffered complete)
+--> ProposalSource filtered by allow-list
|
v
encodeTutorEvent -> text/event-stream
|
v
reducePanel
|
+--> text draft
+--> proposals rendered outside the draft
+--> status paused / awaiting_approval / complete / incomplete
Optional SDK path:
text
Pinned SDK, server package only
|
v
private mapper function in the adapter file
|
v
TutorEvent
Write the package name, version, and doc URL in that file after you read the docs. If the docs disagree with TutorEvent, change the mapper, not the reducer.
Real-Time Enterprise Example
The lesson route and the staff route share encodeTutorEvent and reducePanel. They do not share a data source. Learners stream from the tutor TokenSource. Staff stream status from the refund runtime: when a checkpoint is paused, the staff route sends statusawaiting_approval and the finding as tokens that were already stored, then done. Replaying that turn does not call FindingModel.
A provider outage becomes errorunavailable after any tokens already flushed. The panel stays on the lesson. The learner may retry with a new clientTurnId. The old id remains incomplete so support can see the attempt.
Multi-tenant challenge: the route takes tenant from the session before it reads a turn. A replay looks up (tenant_id, user_id, client_turn_id). A stolen turn id from another tenant returns 404 and emits nothing. High-traffic challenge: cap concurrent streams per user. A second stream while one is streaming is rejected with your usual 429 JSON, not with a second SSE body. Limited token budget: the adapter stops reading the source at the Lesson 19 cap and emits done with finish: "length".
Privacy challenge: do not forward the raw provider stream to the browser. The adapter is the filter that drops unknown chunks, usage frames that contain account identifiers, and tool-call deltas.
Performance Optimization
Flush SSE blocks as they are encoded. Proxy buffering belongs off for this response, as Lesson 16 configured. The reducer is a pure function. It should not copy the whole lesson document. Append text. If a transcript grows past a product cap, stop the source and finish with length.
Do not animate per character if tokens already arrive in small pieces. Extra timers jank the main thread. Rendering plain text is cheaper and safer than parsing Markdown on every token. If you render Markdown, do it on a throttled snapshot, still through the sanitizer, and keep proposals out of that snapshot.
Server CPU is dominated by the model wait. Avoid JSON-parsing the draft on every token. Parse a proposal only in the adapter when the source says the tool object is complete. A buffered non-stream complete that you then slice into fake tokens is acceptable for a staff finding that is already done. Label it a replay, and do not pretend it is live generation.
Leave the UI SDK out of the client bundle unless you have measured a need and proven it does not pull in a key. The reducer and a small SSE parser are enough.
Security
Authentication. The stream route requires a session. EventSource without cookies is the wrong client if your auth is cookie-based. Use fetch and a readable body, or a session design you have already reviewed.
Authorization. Lesson scope and staff role are checked before the first meta event. A failed check is a normal HTTP error, not a stream of someone else's text.
Least privilege. The token source can call ModelPort. It cannot call the ledger. The proposal allow-list is a constant in the adapter.
Validation. Proposal arguments in the lab are strings. Reject non-objects before emit. Ignore names outside ALLOWED.
Secrets. No provider key in the client, in SSE, or in reducer tests. The adapter logs turn id and status.
Tenant isolation. Turn replay is keyed by tenant and user.
Injection. Token text is untrusted. Render as text or sanitized Markdown. Do not eval it. Do not interpret it as a proposal. Proposals come from the adapter's structured channel.
CSRF. The stream POST uses the same CSRF control as your other cookie-authenticated posts.
OWASP themes: security misconfiguration (key in the client), injection (HTML in tokens), and broken access control (replay across tenants). The controls are the server route, the text render, and the turn key.
Common Mistakes
Importing a chat hook that wants a provider key. Symptom: a key in the bundle or a broken client. Cause: a quickstart was written for a local demo. Fix: the panel calls your API. The SDK, if any, stays on the server. Verify the current server-side example, not the browser-key example.
Teaching the reducer a vendor chunk name. Symptom: a provider switch deletes tokens. Cause: the UI branched on a vendor type. Fix: map to TutorEvent in the adapter.
Appending tool-call deltas to the answer. Symptom: the bubble fills with braces. Cause: one channel for text and tools. Fix: buffer, then emit proposal, and keep it out of text.
Executing a proposal when it arrives. Symptom: a glossary or a credit runs because the stream included it. Cause: the client treated the event as a command. Fix: render a disabled or explicit row. Execution is another route with authorization.
Marking the turn complete on the first token. Symptom: Stop no longer makes sense and a partial draft is saved as final. Cause: status flipped too early. Fix: complete only on done.
Opening two streams for one click. Symptom: double bills and interleaved tokens. Cause: no clientTurnId gate. Fix: one active turn, replay on retry.
Ignoring abort. Symptom: Stop spins and the model keeps running. Cause: signal stopped at the browser. Fix: pass it to TokenSource and emit aborted.
Logging the SSE body. Symptom: lesson questions in access logs. Cause: a debug middleware dumped the response. Fix: log status, turn id, duration, and byte count.
Using EventSource on a cookie route that needs a POST body. Symptom: the question is stuffed into a query string and then into logs. Cause: EventSource cannot send a JSON body. Fix: fetch with a stream reader.
Rendering unsanitized Markdown per token. Symptom: a model string injects markup. Cause: innerHTML. Fix: text nodes or the existing sanitizer.
Showing "Credit posted" on paused. Symptom: staff trust a toast. Cause: copy was generic. Fix: "Waiting for approval" and a review button.
Copying an SDK method from a previous major. Symptom: the build fails or, worse, silently uses a compatibility shim that streams a different protocol. Fix: open the docs for the pinned version, write the mapper, and keep the panel tests on TutorEvent.
Best Practices
Keep TutorEvent closed and versioned with the app, not with a vendor.
Encode SSE the way Lesson 16 specifies.
Reduce with a pure function and test it.
Append tokens only while the turn is open.
Store proposals in their own list.
Allow-list proposal names before emit.
Drop partial tool JSON that never becomes valid.
Finish with done or error, not with a closed socket alone.
Map abort to aborted.
Idempotency-key the turn and do not double-spend.
Authenticate before the first event.
Take tenant from the session.
Keep provider credentials in the server adapter.
Render untrusted text safely.
Use draft copy until done.
Use approval copy for paused.
Separate learner and staff routes even if they share a reducer.
Cap concurrency and token length.
Log metadata, not bodies.
If you pin a UI SDK, confine it to the server mapper and record the doc URL.
Do not let the client choose promptVersion.
Leave execution to the tool port in the next lesson.
Interview Questions & Answers
Beginner
Why stream tokens instead of waiting for the full answer?
A lesson explanation can take seconds. Streaming shows progress and lets Stop abort the spend. The panel still labels the text as a draft until done, because a partial sentence is not a saved answer.
Where does an AI UI SDK belong?
On the server, inside an adapter that emits TutorEvent, and only after you pin a version and read its docs. The browser talks to your route with the session cookie. It does not hold a provider key.
What is the difference between a token and a proposal?
A token is draft text. A proposal is a named suggestion with arguments. The reducer stores them separately so braces never become the answer and a suggestion never runs by itself.
Intermediate
How should Stop work?
The panel aborts the fetch signal. The server stops reading the token source and writes an error event with reason aborted, or closes after that event. The reducer keeps the partial text and sets incomplete. No proposal is executed on the way out.
Why not connect EventSource to the provider?
The provider would see the browser, the key would have to live there or in a proxy you do not control, and the chunk format would become your UI contract. Your route is the trust boundary. SSE is only the framing.
How do you avoid a double bill when the network blips?
The client retries the same clientTurnId. The server returns the stored events if the turn exists and does not call the model again. A new id is a new turn the learner explicitly starts.
Senior
How do you test a stream without a model?
A fake TokenSource yields two strings. toTutorEvents wraps them with meta and done. The reducer test asserts the text, asserts a disallowed proposal never appears, and asserts a repeated id does not append twice. A separate test aborts the signal and expects aborted.
A vendor SDK streams five chunk kinds you do not use. What do you do?
The mapper handles text, a completed tool object you allow, and errors. It drops the rest. You document the drop list in the adapter. You do not expand TutorEvent for a vendor feature the product has no UI for.
Architect
How does this sit with the refund graph?
The staff panel may stream awaiting_approval when the checkpoint is paused. That stream reads the checkpoint. It does not call resume and does not post a credit. Approval remains a different POST with a role check.
When would you adopt a vendor stream protocol end to end?
When you are building a throwaway internal tool and you accept lock-in. For TechLearningPro, the panel outlives vendors. The protocol you version is TutorEvent. Adapters can be replaced. The Agentic material may show a pinned SDK. Production routes in this course still reduce your events.
How do you keep HTML and prompt injection out of the panel?
The model cannot emit events. Only the adapter can, and it only emits proposal for allow-listed names. Token text is rendered as text. A sentence that says "post the credit" is a sentence. The credit route will not see it unless a later explicit action is submitted.
What did you deliberately leave out of the client bundle?
Provider SDKs, secret handles, vendor chunk names, and any executor. The client has a reducer, a parser, and a fetch. That is small enough to review and small enough to test when a vendor renames a hook.
Knowledge Check
1. What problem does this capability solve?
It gives every TechLearningPro panel one stream contract so drafts, pauses, and suggestions render predictably, while provider and UI SDKs stay replaceable on the server.
2. What alternatives exist, and when would you choose each?
A buffered JSON response fits a short staff finding you already stored. SSE plus TutorEvent fits the lesson tutor. A pinned server SDK fits when its stream helper saves real parsing work and the mapper stays thin. A browser hook with a provider key fits nowhere in this product.
3. Which data, identity, and trust boundaries matter?
The session cookie authenticates the route. The server authorizes the lesson or the staff role. Tokens are untrusted text. Proposals are untrusted until the allow-list, and still not executed. Provider credentials stay in the adapter.
4. What can fail, and how should the system respond?
Timeouts, aborts, and outages become error and an incomplete draft. Unknown proposals disappear. Duplicate event ids do not double the text. A cross-tenant turn id returns no body. The lesson document remains on screen.
5. How would you test quality, security, performance, and cost?
Reducer tests cover tokens, proposals, duplicates, and completion. Adapter tests cover the allow-list and abort. Security review searches the client bundle for provider key names. Cost review asserts one model stream per clientTurnId. Performance review checks that you are not parsing Markdown on every token without a throttle.
Key Takeaways
The panel contract is TutorEvent, framed as SSE.
Vendor AI SDKs map into that contract on the server or they stay out.
Verify SDK names in the docs for the version you pin.
Tokens fill a draft. done finishes it.
Proposals render outside the draft and do not run.
Unknown proposal names are dropped.
paused and awaiting_approval ask for a human.
Stop aborts the signal and records aborted.
One clientTurnId opens at most one model stream.
The browser authenticates to your API, not to the provider.
Render model text as untrusted text.
Learner and staff routes share a reducer and not a database query.
Logs store turn metadata, not prompts or keys.
Partial tool JSON never reaches the bubble.
The next lesson decides whether a proposal may run.
Summary
Lesson 42 makes streaming a product contract instead of a vendor demo. The panel reduces a closed set of events. Adapters, including any AI SDK you later pin, are the only place that sees a provider chunk. Drafts stay drafts until done. Suggestions stay suggestions. Refund pauses stay pauses. That discipline is what lets Lesson 43 attach a real tool ecosystem without teaching the browser to call tools by itself.
Next Lesson Preview
MCP Fundamentals and Tool Ecosystem Integration takes a proposal like lookup_ticket and asks what a tool server is allowed to offer. You will separate host, client, and server, allow-list tools and resources, and keep write effects behind approval. Protocol method names will be whatever the spec revision you pin says they are. The port in the lesson is the one the route will call.
Deliverable and Rubric
Submit the event list, reducer tests, a sequence diagram from send to done, and a sentence on where an SDK would sit if you added one. Include the abort path and one disallowed proposal.
Agentic systems for agent UIs that should still reduce a closed event set.
The current docs of any UI or provider SDK you pin. Record the URL and version beside the mapper. Do not import a hook whose example asks the browser for a provider key.
Ready to mark this lesson complete?Track your journey across the entire course.