Streaming

Định dạng SSE kiểu OpenAI

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://gateway.vibecc.viettk.com/v1",
  apiKey: process.env.OPENAI_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Hello" }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

Định dạng SSE thô

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{"content":"Hello"}}]}

data: [DONE]

Streaming kiểu Anthropic

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  baseURL: "https://gateway.vibecc.viettk.com",
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const stream = await client.messages.stream({
  model: "gpt-4o",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Hello" }],
});

for await (const chunk of stream) {
  if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
    process.stdout.write(chunk.delta.text);
  }
}

Cách kết nối hoạt động

  • Gửi tín hiệu giữ kết nối (heartbeat) mỗi 15 giây khi stream đang rảnh
  • Client ngắt kết nối thì request tới provider cũng bị hủy ngay lập tức
  • Thời gian tối đa cho một stream: 60 giây (có thể chỉnh theo từng service class)