async function testMinimaxStream() {
  const url = 'https://api.minimax.io/v1/chat/completions';
  const apiKey = 'sk-cp-siEwoNh9WA3Prxe6frpJ2HsXPje-gjt5jObhHloqqoO0FX0i9yP54N3zhY492GKu18l9XiANDiCoECU3t0uMtRODvkzzi93A2Rmtco6MjATrKNOEDR_bxa4';
  const body = {
    model: 'MiniMax-M3',
    messages: [
      { role: 'system', content: 'You are a test agent. Output JSON format.' },
      { role: 'user', content: 'Ping' },
    ],
    temperature: 0,
    stream: true,
    response_format: { type: 'json_object' },
  };

  try {
    const res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`,
      },
      body: JSON.stringify(body),
    });

    if (!res.ok) {
      console.error('HTTP Error:', res.status, await res.text());
      return;
    }

    const reader = res.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let fullText = '';
    let buffer = '';
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';
      for (const rawLine of lines) {
        const line = rawLine.trim();
        if (!line.startsWith('data: ')) continue;
        const jsonStr = line.replace(/^data: /, '').trim();
        if (jsonStr === '[DONE]') continue;
        try {
          const parsed = JSON.parse(jsonStr);
          const content = parsed.choices?.[0]?.delta?.content || '';
          fullText += content;
        } catch (e) {
          console.error('Failed to parse:', jsonStr);
        }
      }
    }
    console.log('\n--- FINAL FULL TEXT ---');
    console.log(fullText);
  } catch (err) {
    console.error('Fetch error:', err);
  }
}
testMinimaxStream();
