http.sse — Lilush API

←index

← http

Overview

Server-Sent Events (SSE) streaming client using the LEV event loop.

Must be used within a lev.run() context. All I/O yields cooperatively so the event loop remains responsive.

Functions

NameSignature
sse_clientsse_client(uri, options, callbacks) -> client

sse_client(uri, options, callbacks) -> client

Create a Server-Sent Events (SSE) streaming client

Returns an SSE client object. Must be used within lev.run().

Methods:

The options table may contain:

The callbacks table may contain:

Named event callbacks (e.g., callbacks.delta) are dispatched by SSE event type. JSON data payloads are automatically decoded.

local http = require("http")
local json = require("cjson.safe")
local lev = require("lev")

lev.run(function()
    local client = http.sse_client(
        "https://api.example.com/v1/chat/completions",
        {
            method  = "POST",
            body    = json.encode({ model = "gpt-4o", stream = true, messages = { ... } }),
            headers = { ["Authorization"] = "Bearer " .. api_key },
        },
        {
            message = function(data)
                if type(data) == "table" then
                    local delta = data.choices and data.choices[1]
                        and data.choices[1].delta
                    if delta and delta.content then
                        io.write(delta.content)
                    end
                end
            end,
            done  = function() print("\n[stream complete]") end,
            error = function(msg, status) print("SSE error", status, msg) end,
        }
    )
    local ok, err = client:connect()
    if not ok then print("failed:", err); return end
    while client:update() and client:is_connected() do end
end)