Skip to content

Commit bf941b4

Browse files
committed
minor #248 [Demo] Render markdown in the stream example (valtzu)
This PR was merged into the main branch. Discussion ---------- [Demo] Render markdown in the stream example | Q | A | ------------- | --- | Bug fix? | no | New feature? | no | Docs? | no | Issues | Fix #201 | License | MIT Previously markdown was only converted to HTML on full page reload, now we render the whole partial message server side while streaming. This is a lot less efficient than only sending the new parts of the stream, but much easier to implement _(still no custom JS needed)_ – and I don't think we should make the demos too complex. Commits ------- ec30b7b [Demo] Render markdown in the stream example
2 parents 5297ee6 + ec30b7b commit bf941b4

File tree

3 files changed

+5
-17
lines changed

3 files changed

+5
-17
lines changed

demo/src/Stream/Chat.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@ public function getAssistantResponse(MessageBag $messages): \Generator
5757

5858
$response = '';
5959
foreach ($stream as $chunk) {
60-
yield $chunk;
61-
$response .= $chunk;
60+
yield $response .= $chunk;
6261
}
6362

6463
$assistantMessage = Message::ofAssistant($response);

demo/src/Stream/TwigComponent.php

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -77,15 +77,8 @@ public function streamContent(Request $request): EventStreamResponse
7777
$request->setSession($actualSession);
7878
$response = $this->chat->getAssistantResponse($messages);
7979

80-
$thinking = true;
81-
foreach ($response as $chunk) {
82-
// Remove "Thinking..." when we receive something
83-
if ($thinking && trim($chunk)) {
84-
$thinking = false;
85-
yield new ServerEvent(explode("\n", $this->renderBlockView('_stream.html.twig', 'start')));
86-
}
87-
88-
yield new ServerEvent(explode("\n", $this->renderBlockView('_stream.html.twig', 'partial', ['part' => $chunk])));
80+
foreach ($response as $partialMessage) {
81+
yield new ServerEvent(explode("\n", $this->renderBlockView('_stream.html.twig', 'update', ['message' => $partialMessage])));
8982
}
9083

9184
yield new ServerEvent(explode("\n", $this->renderBlockView('_stream.html.twig', 'end', ['message' => $response->getReturn()])));

demo/templates/_stream.html.twig

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
{% block start %}
2-
<twig:Turbo:Stream:Update target="#bot-message-streamed"/>
3-
{% endblock %}
4-
5-
{% block partial %}
6-
<twig:Turbo:Stream:Append target="#bot-message-streamed">{{ part }}</twig:Turbo:Stream:Append>
1+
{% block update %}
2+
<twig:Turbo:Stream:Update target="#bot-message-streamed">{{ message|markdown_to_html }}</twig:Turbo:Stream:Update>
73
{% endblock %}
84

95
{% block end %}

0 commit comments

Comments
 (0)