File size: 4,177 Bytes
212c959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
const TOKEN_KEY = 'owngpt_v2_token'

export function getToken() {
  if (typeof window === 'undefined') return null
  return window.localStorage.getItem(TOKEN_KEY)
}

export function saveToken(token) {
  if (typeof window === 'undefined') return
  if (token) {
    window.localStorage.setItem(TOKEN_KEY, token)
  } else {
    window.localStorage.removeItem(TOKEN_KEY)
  }
}

async function parseErrorResponse(response) {
  const text = await response.text().catch(() => '')
  try {
    const payload = JSON.parse(text)
    if (Array.isArray(payload.detail)) {
      return payload.detail.map((item) => item.msg || JSON.stringify(item)).join('; ')
    }
    if (typeof payload.detail === 'string') {
      return payload.detail
    }
    if (payload.detail) {
      return JSON.stringify(payload.detail)
    }
  } catch {
    return text || `HTTP ${response.status}`
  }
  return text || `HTTP ${response.status}`
}

async function request(url, options = {}) {
  const {
    token = getToken(),
    headers: customHeaders,
    body,
    ...rest
  } = options

  const headers = { ...(customHeaders || {}) }
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }

  const response = await fetch(url, {
    ...rest,
    headers,
    body,
  })

  if (!response.ok) {
    const detail = await parseErrorResponse(response)
    const error = new Error(detail || `HTTP ${response.status}`)
    error.status = response.status
    throw error
  }

  const contentType = response.headers.get('content-type') || ''
  if (contentType.includes('application/json')) {
    return response.json()
  }
  return response.text()
}

export const api = {
  get: (url, options = {}) => request(url, { ...options, method: 'GET' }),
  delete: (url, options = {}) => request(url, { ...options, method: 'DELETE' }),
  post: (url, data, options = {}) =>
    request(url, {
      ...options,
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
      body: JSON.stringify(data),
    }),
  patch: (url, data, options = {}) =>
    request(url, {
      ...options,
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
      body: JSON.stringify(data),
    }),
  postForm: (url, formData, options = {}) =>
    request(url, {
      ...options,
      method: 'POST',
      body: formData,
    }),
}

function handleSseBlock(block, { onChunk, onDone, onError }) {
  const lines = block.split(/\r?\n/)
  let eventName = 'message'
  let dataString = ''

  for (const line of lines) {
    if (line.startsWith('event: ')) {
      eventName = line.slice(7)
    }
    if (line.startsWith('data: ')) {
      dataString += line.slice(6)
    }
  }

  if (!dataString) return

  let data
  try {
    data = JSON.parse(dataString)
  } catch {
    return
  }

  if (eventName === 'chunk' && data.text) {
    onChunk?.(data.text)
  } else if (eventName === 'done') {
    onDone?.(data)
  } else if (eventName === 'error') {
    onError?.(data.detail || 'Streaming failed')
  }
}

export async function streamChat({
  payload,
  token = getToken(),
  signal,
  onChunk,
  onDone,
  onError,
}) {
  const response = await fetch('/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: JSON.stringify(payload),
    signal,
  })

  if (!response.ok) {
    const detail = await parseErrorResponse(response)
    throw new Error(detail || `HTTP ${response.status}`)
  }

  const reader = response.body?.getReader()
  if (!reader) {
    throw new Error('Streaming is not supported by this browser.')
  }

  const decoder = new TextDecoder()
  let buffer = ''
  let done = false

  while (!done) {
    const result = await reader.read()
    done = result.done
    buffer += decoder.decode(result.value || new Uint8Array(), { stream: !done })
    const blocks = buffer.split(/\r?\n\r?\n/)
    buffer = blocks.pop() || ''

    for (const block of blocks) {
      handleSseBlock(block, { onChunk, onDone, onError })
    }
  }

  if (buffer.trim()) {
    handleSseBlock(buffer, { onChunk, onDone, onError })
  }
}