In this video, you watched the partner script crash when a stream failed partway through Amara’s reply, and you changed the script so it keeps the words she’d already read and marks a reply that never finished as broken.
Key Points
- A failure can arrive after the first words. The status was 200 before the first word was written, so a failure during generation arrives later, as an error event in the middle of the stream.
- The failing runs used a stand-in server. You can’t make a provider fail on cue, so this video’s failing runs use a small local stand-in server. It passes on the real reply’s first words, then sends an error event. It’s only for the recording, so you don’t need to build it.
- The error comes from inside the loop. With the script as the last lesson left it, Amara saw the first few words of the reply, and then the script crashed with
Error: Stream error: Server error, thrown by your provider file when it read the error event. The stack’s last line pointed to line 17 ofpartner.js, thefor awaitloop, not to thestreamAnswer()call above it. Nothing after the loop ran, so Amara was left with half a sentence. Your run’s words will differ. streamAnswer()doesn’t retry it. An error event from the provider is never retried, even before any text. And once the first words have gone out, even a retryable failure is thrown on to your loop. That second rule is there because a retry would ask the model for a whole new reply, which would appear after the broken words. Words the member has already read can’t be taken back, so handling the error is the script’s job.- Put the whole loop inside the
try. Atryaround thestreamAnswer()call alone catches nothing here, because the request starts, and fails, inside the loop. - Keep what was shown. The
catchblock prints the error’s message. The words Amara saw stay on screen, andreplykeeps them on purpose. - A
nullstop reason means the reply is broken. Only the closing event setsanswer.stopReason, so after thetry, the script setsbrokentoanswer.stopReason === null, and a marker tells Amara that the reply broke off. cutOffcan’t tell you how a broken reply ended. The stop reason and usage staynull, because the closing event never came. So the script can’t count this call’s tokens, though the provider still processed them.cutOffstaysfalseonly because that’s its starting value.- A cut-off reply ends with no error. At the output limit, the closing event does come, so the stop reason is set and
cutOffturnstrue, the same flagask()sets. Oneifstatement after the loop adds a second marker.
Remember that a stream can break after the member has read part of it. Put the whole loop inside the try, and in the catch, keep what was shown. After it, a null stop reason means broken, and cutOff means cut off.