File size: 4,513 Bytes
4e039c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* ------------------------------------------------------------------ *
 * 串流呼叫 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
}