Stream an answer
Task: a model can take seconds to answer; show the page at once and the answer as it arrives.
# Recipe: the page renders at once and the answer appears as it is written.
paths:
components: ./components
llm:
model: phi3With stream="true", q:llm does not wait: the retrieval is done, so the sources are on the page, and <ui:stream for="answer"> fills in the answer as the model writes it — through the framework's own script, with no JavaScript to write. Without JavaScript it is a link, and quantum console shows the answer arriving too.
<q:component name="Ask">
<q:knowledge name="docs" persist="false" chunkSize="300" chunkOverlap="30">
<q:source type="directory" path="knowledge" pattern="*.md" />
</q:knowledge>
<q:set name="question" value="{query.q}" default="" />
<q:if condition="question">
<!-- stream="true": the page does not wait for the model. The sources are
known at once; the answer is read from /_stream/… as it is written. -->
<q:llm name="answer" knowledge="docs" top="2" stream="true">
<q:message role="user">{question}</q:message>
</q:llm>
</q:if>
<ui:window title="Ask the store">
<ui:form>
<ui:input bind="q" value="{question}" placeholder="Your question" />
<ui:button variant="primary">Ask</ui:button>
</ui:form>
<q:if condition="question">
<!-- The framework's own script fills it in; without JavaScript, a link
opens the answer. -->
<ui:stream for="answer" />
<q:loop items="{answer_result.sources}" var="s">
<ui:text>[{s.n}] {s.name}</ui:text>
</q:loop>
</q:if>
</ui:window>
</q:component><!-- Structural checks, never the model's exact words: the same tests run
against a real model before every release. -->
<q:test name="the page renders with its sources before the answer" page="/">
<test:visit q="How many days do I have to return an order?" />
<test:expect text="[1] returns.md" />
<test:expect text="Read the answer" />
</q:test>tests/stream.test.q
PASS the page renders with its sources before the answer
1 passed, 0 failedThe stream belongs to the visitor who asked, is read once and expires in ten minutes.
Tested: in CI these tests run against a stand-in model server, which answers from the first source it is given; before every release they run against a real model (tests/live_ai/test_cookbook_ai.py). That is why they check structure — which source, which tool, what the page shows on failure — and never the model's words.
See IA-7.