|
| 1 | +// BIG FAT WARNING: to avoid the complexity of npm, this typescript is compiled in the browser |
| 2 | +// there's currently no static type checking |
| 3 | + |
| 4 | +import { marked } from 'https://cdnjs.cloudflare.com/ajax/libs/marked/15.0.0/lib/marked.esm.js' |
| 5 | +const convElement = document.getElementById('conversation') |
| 6 | + |
| 7 | +const promptInput = document.getElementById('prompt-input') as HTMLInputElement |
| 8 | +const spinner = document.getElementById('spinner') |
| 9 | + |
| 10 | +// stream the response and render messages as each chunk is received |
| 11 | +// data is sent as newline-delimited JSON |
| 12 | +async function onFetchResponse(response: Response): Promise<void> { |
| 13 | + let text = '' |
| 14 | + let decoder = new TextDecoder() |
| 15 | + if (response.ok) { |
| 16 | + const reader = response.body.getReader() |
| 17 | + while (true) { |
| 18 | + const {done, value} = await reader.read() |
| 19 | + if (done) { |
| 20 | + break |
| 21 | + } |
| 22 | + text += decoder.decode(value) |
| 23 | + addMessages(text) |
| 24 | + spinner.classList.remove('active') |
| 25 | + } |
| 26 | + addMessages(text) |
| 27 | + promptInput.disabled = false |
| 28 | + promptInput.focus() |
| 29 | + } else { |
| 30 | + const text = await response.text() |
| 31 | + console.error(`Unexpected response: ${response.status}`, {response, text}) |
| 32 | + throw new Error(`Unexpected response: ${response.status}`) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +// The format of messages, this matches pydantic-ai both for brevity and understanding |
| 37 | +// in production, you might not want to keep this format all the way to the frontend |
| 38 | +interface Message { |
| 39 | + role: string |
| 40 | + content: string |
| 41 | + timestamp: string |
| 42 | +} |
| 43 | + |
| 44 | +// take raw response text and render messages into the `#conversation` element |
| 45 | +// Message timestamp is assumed to be a unique identifier of a message, and is used to deduplicate |
| 46 | +// hence you can send data about the same message multiple times, and it will be updated |
| 47 | +// instead of creating a new message elements |
| 48 | +function addMessages(responseText: string) { |
| 49 | + const lines = responseText.split('\n') |
| 50 | + const messages: Message[] = lines.filter(line => line.length > 1).map(j => JSON.parse(j)) |
| 51 | + for (const message of messages) { |
| 52 | + // we use the timestamp as a crude element id |
| 53 | + const {timestamp, role, content} = message |
| 54 | + const id = `msg-${timestamp}` |
| 55 | + let msgDiv = document.getElementById(id) |
| 56 | + if (!msgDiv) { |
| 57 | + msgDiv = document.createElement('div') |
| 58 | + msgDiv.id = id |
| 59 | + msgDiv.title = `${role} at ${timestamp}` |
| 60 | + msgDiv.classList.add('border-top', 'pt-2', role) |
| 61 | + convElement.appendChild(msgDiv) |
| 62 | + } |
| 63 | + msgDiv.innerHTML = marked.parse(content) |
| 64 | + } |
| 65 | + window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }) |
| 66 | +} |
| 67 | + |
| 68 | +function onError(error: any) { |
| 69 | + console.error(error) |
| 70 | + document.getElementById('error').classList.remove('d-none') |
| 71 | + document.getElementById('spinner').classList.remove('active') |
| 72 | +} |
| 73 | + |
| 74 | +async function onSubmit(e: SubmitEvent): Promise<void> { |
| 75 | + e.preventDefault() |
| 76 | + spinner.classList.add('active') |
| 77 | + const body = new FormData(e.target as HTMLFormElement) |
| 78 | + |
| 79 | + promptInput.value = '' |
| 80 | + promptInput.disabled = true |
| 81 | + |
| 82 | + const response = await fetch('/chat/', {method: 'POST', body}) |
| 83 | + await onFetchResponse(response) |
| 84 | +} |
| 85 | + |
| 86 | +// call onSubmit when the form is submitted (e.g. user clicks the send button or hits Enter) |
| 87 | +document.querySelector('form').addEventListener('submit', (e) => onSubmit(e).catch(onError)) |
| 88 | + |
| 89 | +// load messages on page load |
| 90 | +fetch('/chat/').then(onFetchResponse).catch(onError) |
0 commit comments