File size: 2,674 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Reading /api/ask's server-sent events from a fetch() body. EventSource can't POST,
// so the stream is read by hand: bytes -> text -> blocks separated by a blank line ->
// the JSON after "data: ". Comment lines (": ping", the keep-alive) are skipped.

import type { AskEvent, SystemId } from './types'

/** Complete events in `buffer`, and the unfinished tail to keep for the next chunk. */
export function parseEvents(buffer: string): { events: AskEvent[]; rest: string } {
  const blocks = buffer.replace(/\r\n/g, '\n').split('\n\n')
  const rest = blocks.pop() ?? '' // after the last blank line: not complete yet
  const events: AskEvent[] = []
  for (const block of blocks) {
    const data = block
      .split('\n')
      .filter((line) => line.startsWith('data:'))
      .map((line) => line.slice(5).replace(/^ /, ''))
      .join('\n')
    if (data) events.push(JSON.parse(data) as AskEvent)
  }
  return { events, rest }
}

export type HistoryTurn = { question: string; answer: string }

export type AskRequest = { question: string; system: SystemId; day?: string; history?: HistoryTurn[] }

/** Why /api/ask refused before streaming (429 busy/limit, 422 bad input). */
export class AskRefused extends Error {}

/** POST a question and call onEvent for each event as it arrives. Resolves when the
 * stream ends; rejects with AskRefused on an HTTP refusal; abort with `signal`. */
export async function ask(
  body: AskRequest,
  onEvent: (event: AskEvent) => void,
  signal?: AbortSignal,
): Promise<void> {
  const response = await fetch('/api/ask', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
    signal,
  })
  if (!response.ok || !response.body) throw new AskRefused(await refusal(response))
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
  let buffer = ''
  for (;;) {
    const { value, done } = await reader.read()
    if (done) break
    const parsed = parseEvents(buffer + value)
    buffer = parsed.rest
    parsed.events.forEach(onEvent)
  }
  parseEvents(buffer + '\n\n').events.forEach(onEvent) // a last event without its blank line
}

/** The server's reason, readable: FastAPI sends {"detail": "..."} (a string for 429,
 * a list of field errors for 422). */
async function refusal(response: Response): Promise<string> {
  try {
    const body = await response.json()
    if (typeof body.detail === 'string') return body.detail
    if (Array.isArray(body.detail)) return body.detail.map((d: { msg: string }) => d.msg).join('; ')
  } catch {
    // not JSON: fall through
  }
  return `The server refused the question (HTTP ${response.status}).`
}