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.
| Name | Signature |
|---|---|
sse_client | sse_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:
client:connect() — connect, send request, read response headers
client:update() — read data, decode, dispatch SSE events (yields cooperatively)
client:close() — close the connection (idempotent)
client:is_connected() — check connection status
The options table may contain:
method — HTTP method (default: "GET")
body — request body string
headers — additional request headers (override defaults case-insensitively)
connect_timeout — connection + handshake timeout in seconds (default: 10)
send_timeout — send timeout in seconds (default: 30)
recv_timeout — per-update read timeout in seconds (default: 0.5)
tls_certfile, tls_keyfile, tls_cafile, tls_capath, tls_no_verify — TLS options
The callbacks table may contain:
connect() — called on successful connection
open(status, headers) — called when response headers are received
message(event) — default handler for SSE events
error(msg, status) — called on errors
close() — called when the connection closes
done() — called on [DONE] sentinel
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)