studio / src /lib /llm.js
cheumk's picture
Upload 32 files
4e039c5 verified
Raw History Blame Contribute Delete
4.51 kB
/* ------------------------------------------------------------------ *
* 串流呼叫 OpenAI 相容 /chat/completions
*
* - 一律 stream: true,邊收邊回呼 onDelta(文字、推理內容、工具呼叫)
* - 工具呼叫的 delta 依 index 累積成完整 tool_calls
* - 不設逾時:只有使用者按「停止」(signal abort)才會中斷
* ------------------------------------------------------------------ */
async function readErrorMessage(res) {
const text = await res.text().catch(() => '')
try {
const data = JSON.parse(text)
const e = Array.isArray(data) ? data[0]?.error : data?.error
return e?.message || e?.metadata?.raw || data?.message || text.slice(0, 300) || '無錯誤訊息'
} catch {
return text.slice(0, 300) || '無錯誤訊息'
}
}
/**
* @returns {Promise<{content:string, reasoning:string, tool_calls:Array, finish_reason:string|null}>}
*/
export async function streamChat({ provider, model, messages, tools, temperature, signal, onDelta }) {
const base = String(provider.baseUrl || '').replace(/\/+$/, '')
const headers = { 'Content-Type': 'application/json' }
if (provider.apiKey?.trim()) headers.Authorization = `Bearer ${provider.apiKey.trim()}`
if (/openrouter\.ai/.test(base)) {
headers['HTTP-Referer'] = window.location.origin
headers['X-Title'] = 'Agent Studio'
}
const body = { model, messages, stream: true }
if (tools?.length) body.tools = tools
if (typeof temperature === 'number') body.temperature = temperature
const res = await fetch(`${base}/chat/completions`, {
method: 'POST',
signal,
headers,
body: JSON.stringify(body),
})
if (!res.ok) throw new Error(`API 錯誤 ${res.status}:${await readErrorMessage(res)}`)
if (!res.body) throw new Error('回應不含可讀取的串流')
const out = { content: '', reasoning: '', tool_calls: [], finish_reason: null }
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
let sawSse = false
const handle = (data) => {
if (data.error) throw new Error(data.error.message || 'API 串流回傳錯誤')
const choice = data.choices?.[0]
if (!choice) return
const d = choice.delta || choice.message || {}
if (choice.finish_reason) out.finish_reason = choice.finish_reason
const reasoning = d.reasoning_content ?? d.reasoning
if (typeof reasoning === 'string' && reasoning) {
out.reasoning += reasoning
onDelta?.({ reasoning: out.reasoning })
}
if (typeof d.content === 'string' && d.content) {
out.content += d.content
onDelta?.({ content: out.content })
}
if (Array.isArray(d.tool_calls)) {
d.tool_calls.forEach((tc, pos) => {
// 有些供應商(如 Gemini)不給 index,就用陣列位置;給了新的 id 就視為新呼叫
let idx = typeof tc.index === 'number' ? tc.index : pos
if (tc.id && out.tool_calls[idx]?.id && out.tool_calls[idx].id !== tc.id && typeof tc.index !== 'number') {
idx = out.tool_calls.length
}
const cur = out.tool_calls[idx] || { id: '', type: 'function', function: { name: '', arguments: '' } }
if (tc.id) cur.id = tc.id
if (tc.function?.name) cur.function.name += tc.function.name
if (tc.function?.arguments) {
cur.function.arguments += typeof tc.function.arguments === 'string'
? tc.function.arguments
: JSON.stringify(tc.function.arguments)
}
out.tool_calls[idx] = cur
})
onDelta?.({ tool_calls: out.tool_calls })
}
}
for (;;) {
const { value, done } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop()
for (const raw of lines) {
const line = raw.trim()
if (!line.startsWith('data:')) continue
sawSse = true
const payload = line.slice(5).trim()
if (!payload || payload === '[DONE]') continue
let data
try { data = JSON.parse(payload) } catch { continue }
handle(data)
}
}
// 少數端點忽略 stream:true 直接回整包 JSON
if (!sawSse && buffer.trim().startsWith('{')) {
let data = null
try { data = JSON.parse(buffer) } catch { /* 不是 JSON 就忽略 */ }
if (data) handle(data)
}
out.tool_calls = out.tool_calls.filter(Boolean).map((tc, i) => ({
...tc,
id: tc.id || `call_${Date.now().toString(36)}_${i}`,
}))
return out
}