Skip to content

Streaming ​

With stream: true, POST /v1/agents/{slug}/runs and POST /v1/conversations/{id}/messages answer with Server-Sent Events while the run executes, so you can show text as it is generated and tool activity as it happens.

Request ​

bash
curl -N "$HEVKAR_BASE_URL/v1/agents/writer/runs" \
  -H "Authorization: Bearer $HEVKAR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"input": {"topic": "solar panels"}, "stream": true}'
ts
const stream = hevkar.agents.stream('writer', { input: { topic: 'solar panels' } });

for await (const event of stream) {
  if (event.event === 'text.delta') process.stdout.write(event.data.text);
  if (event.event === 'tool.call') console.log('\n[calling', event.data.name, ']');
}
const result = await stream.finalResult(); // RunResult
ts
const res = await fetch(`${baseUrl}/v1/agents/writer/runs`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ input: { topic: 'solar panels' }, stream: true }),
});
if (!res.ok) throw new Error(JSON.stringify(await res.json())); // errors before the run are JSON

const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;
  let end;
  while ((end = buffer.indexOf('\n\n')) !== -1) {
    const frame = buffer.slice(0, end);
    buffer = buffer.slice(end + 2);
    const event = /^event: (.*)$/m.exec(frame)?.[1];
    const data = JSON.parse(/^data: (.*)$/m.exec(frame)?.[1] ?? 'null');
    if (event === 'text.delta') process.stdout.write(data.text);
    if (event === 'run.completed' || event === 'run.failed') console.log('\n', event, data);
  }
}

The response has status 200 and Content-Type: text/event-stream. Each event is an event: line with the name and a data: line with JSON:

text
event: run.started
data: {"runId":"4f0f7c1e-…"}

event: text.delta
data: {"text":"Solar panels convert"}

event: text.delta
data: {"text":" sunlight into electricity"}

event: run.completed
data: {"runId":"4f0f7c1e-…","status":"succeeded","output":{"text":"Solar panels convert sunlight into electricity…"},"usage":{"inputTokens":40,"outputTokens":210,"priceMicros":150},"latencyMs":3120}

Errors detected before the run starts (validation, auth, rate limit, spend cap) are normal JSON error responses with a 4xx status, not streams.

Event reference ​

EventDataNotes
run.started{runId}first event
text.delta{text, nodeId?}a piece of the answer; nodeId in workflows
tool.call{name, args}the model calls a tool
tool.result{name, ok}the tool finished
node.started{nodeId, nodeType, iteration}workflows
node.completed{nodeId, nodeType, iteration, status, handle, error?}workflows
run.waiting{runId, nodeId, kind: "approval" | "event", eventName?}workflows; the stream ends here
run.completedRunResultlast event
run.failed{runId, error: {code, message}}last event
  • With an outputSchema, text.delta carries the raw JSON text as it is generated; the parsed object is in run.completed.
  • In workflows, iteration is 0 for a node and 1, 2, … for map items and loop iterations; text.delta events come from agent nodes and carry the node id.
  • When a workflow pauses (run.waiting), resume it with an approval or event and follow it with GET /v1/runs/{id} or webhooks.

Disconnects ​

Closing the connection of a streamed run cancels it (status cancelled, error RUN_CANCELLED), except for workflow runs, which keep going on the engine. Use async: true for work that must finish even if your client goes away.

The SDK rejects iteration and finalResult() with code STREAM_INTERRUPTED when the connection drops before the run ends; look the run up with hevkar.runs.get(stream.runId).

Streams cannot be combined with async (400 ASYNC_STREAM_CONFLICT). A streamed request with a repeated Idempotency-Key whose run finished gets a short replay stream: run.started, one text.delta with the whole text (when the output is { text }), then run.completed or run.failed. While that run is still going the answer is 409 IDEMPOTENCY_IN_PROGRESS.

Proxies in front of your backend must not buffer text/event-stream responses (the API sends X-Accel-Buffering: no and Cache-Control: no-cache).

Hevkar public API v1