Kiwi

Streaming

Set stream to true and the answer arrives as server-sent events while it is written.

Events

The events are those of the Anthropic Messages stream, in this order:

EventWhen
message_startFirst. Carries the message id and an empty content.
content_block_startA text block begins (content_block of type text).
content_block_deltaA piece of the text: delta of type text_delta with text.
content_block_stopThe text block is complete.
content_block_start, input_json_delta, content_block_stopFor each of your tools Kiwi calls, a tool_use block whose input arrives as one JSON piece.
message_deltaThe stop_reason and the output token count.
message_stopLast.

Kiwi's own work (searching, running code) is not shown in the stream: the text starts when it has something to say, so the first event after message_start can come after a wait.

If nothing comes from the model for 180 seconds, the stream is closed in the normal way (a message_stop after a message_delta with end_turn) instead of being left open.

Example

import json, os
import requests

with requests.post(
    "https://api.sed1t.com/v1/messages",
    headers={"x-api-key": os.environ["KIWI_API_KEY"]},
    json={"max_tokens": 1024, "stream": True,
          "messages": [{"role": "user", "content": "Write a haiku about kiwis."}]},
    stream=True, timeout=600,
) as r:
    r.raise_for_status()
    r.encoding = "utf-8"
    for line in r.iter_lines(decode_unicode=True):
        if not line.startswith("data: "):
            continue
        event = json.loads(line[6:])
        if event["type"] == "content_block_delta" and event["delta"]["type"] == "text_delta":
            print(event["delta"]["text"], end="", flush=True)
const res = await fetch("https://api.sed1t.com/v1/messages", {
  method: "POST",
  headers: { "x-api-key": process.env.KIWI_API_KEY, "content-type": "application/json" },
  body: JSON.stringify({
    max_tokens: 1024,
    stream: true,
    messages: [{ role: "user", content: "Write a haiku about kiwis." }],
  }),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
for (;;) {
  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 line of lines) {
    if (!line.startsWith("data: ")) continue;
    const event = JSON.parse(line.slice(6));
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") process.stdout.write(event.delta.text);
  }
}