2026-02-12 18:52:16 +08:00
|
|
|
export async function fetchSuggestion(prefix, suffix, apiUrl = 'http://localhost:8000/v1/completions') {
|
|
|
|
|
const res = await fetch(apiUrl, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: { 'Content-Type': 'application/json' },
|
|
|
|
|
body: JSON.stringify({ prefix, suffix, languageId: 'markdown' }),
|
|
|
|
|
})
|
2026-02-07 08:53:37 +08:00
|
|
|
|
2026-02-12 18:52:16 +08:00
|
|
|
if (!res.ok) {
|
|
|
|
|
throw new Error(`HTTP ${res.status}`)
|
|
|
|
|
}
|
2026-02-07 08:53:37 +08:00
|
|
|
|
2026-02-12 18:52:16 +08:00
|
|
|
const reader = res.body?.getReader()
|
|
|
|
|
if (!reader) throw new Error('No reader available')
|
2026-02-07 08:53:37 +08:00
|
|
|
|
2026-02-12 18:52:16 +08:00
|
|
|
let text = ''
|
|
|
|
|
while (true) {
|
|
|
|
|
const { done, value } = await reader.read()
|
|
|
|
|
if (done) break
|
|
|
|
|
const chunk = new TextDecoder().decode(value)
|
|
|
|
|
const lines = chunk.split('\n').filter(l => l.startsWith('data: '))
|
|
|
|
|
for (const line of lines) {
|
|
|
|
|
try {
|
|
|
|
|
const data = JSON.parse(line.slice(6))
|
|
|
|
|
if (data.content) text += data.content
|
|
|
|
|
if (data.done || data.error) break
|
|
|
|
|
} catch (e) {}
|
2026-02-07 08:53:37 +08:00
|
|
|
}
|
2026-02-12 18:52:16 +08:00
|
|
|
}
|
|
|
|
|
return text
|
2026-02-07 08:53:37 +08:00
|
|
|
}
|