Streaming Support¶
Type: Implementation guide. Normative spec: PROTOCOL_SPEC §5 Module Specification (streaming hooks).
Overview¶
A streaming module produces its output as a sequence of chunks instead of one response — useful for modules that wrap LLM APIs, process large datasets, or transform data in real time. The executor's stream() runs a three-phase pipeline that delivers chunks to the caller as they are produced, while still running output validation and after-middleware on the combined result.
Streaming Module Interface¶
Each SDK exposes a language-idiomatic StreamingModule interface so that adapter and bridge code (e.g. apcore-mcp, apcore-a2a) can detect streaming support without guessing from method names.
apcore.StreamingModule is a @runtime_checkable Protocol: an async-generator stream(inputs, context) yielding dict chunks.
from collections.abc import AsyncIterator
from pydantic import BaseModel
from apcore import Context, ModuleAnnotations, StreamingModule
class ChatInput(BaseModel):
prompt: str
class ChatChunk(BaseModel):
content: str
done: bool
class ChatModule:
input_schema = ChatInput
output_schema = ChatChunk
description = "Stream chat completions"
annotations = ModuleAnnotations(streaming=True)
async def execute(self, inputs: dict, context: Context) -> dict:
# Used when a caller does not stream.
return {"content": f"echo:{inputs['prompt']}", "done": True}
async def stream(self, inputs: dict, context: Context) -> AsyncIterator[dict]:
for token in ("echo:", inputs["prompt"]):
yield {"content": token, "done": False}
yield {"content": "", "done": True}
assert isinstance(ChatModule(), StreamingModule)
isinstance checks only that stream exists. When a module declares annotations.streaming = True, registration also checks the signature (arity, async generator) and raises StreamingInterfaceError (STREAMING_INTERFACE_MISMATCH) if it does not match. The @module decorator wraps plain functions only; a streaming module is a class.
TypeScript interfaces are structural, so a streaming module carries the STREAMING_MARKER symbol property; isStreamingModule() narrows the type.
import { Type } from "@sinclair/typebox";
import { STREAMING_MARKER, isStreamingModule } from "apcore-js";
import type { Context, Module, StreamingModule } from "apcore-js";
class ChatModule implements StreamingModule {
readonly [STREAMING_MARKER] = true as const;
inputSchema = Type.Object({ prompt: Type.String() });
outputSchema = Type.Object({ content: Type.String(), done: Type.Boolean() });
description = "Stream chat completions";
annotations = { streaming: true };
async execute(inputs: Record<string, unknown>, _context: Context): Promise<Record<string, unknown>> {
// Used when a caller does not stream.
return { content: `echo:${String(inputs.prompt)}`, done: true };
}
async *stream(inputs: Record<string, unknown>, _context: Context): AsyncGenerator<Record<string, unknown>> {
for (const token of ["echo:", String(inputs.prompt)]) {
yield { content: token, done: false };
}
yield { content: "", done: true };
}
}
const mod: Module = new ChatModule();
console.log(isStreamingModule(mod)); // true
A module that has a stream() method but no marker is still detected, with a one-time deprecation warning per module; add the marker to silence it.
Implement the StreamingModule trait and return Some(self) from Module::as_streaming(). The executor and adapters use the same typed handle. For legacy modules with no typed handle, the executor calls Module::stream(). A None result selects unary execution.
use apcore::{ChunkStream, Context, Module, ModuleAnnotations, ModuleError, StreamingModule};
use async_trait::async_trait;
use serde_json::{json, Value};
struct ChatModule;
#[async_trait]
impl Module for ChatModule {
fn description(&self) -> &str { "Stream chat completions" }
fn input_schema(&self) -> Value {
json!({ "type": "object", "properties": { "prompt": { "type": "string" } }, "required": ["prompt"] })
}
fn output_schema(&self) -> Value {
json!({ "type": "object", "properties": { "content": { "type": "string" }, "done": { "type": "boolean" } } })
}
fn annotations(&self) -> ModuleAnnotations {
ModuleAnnotations { streaming: true, ..ModuleAnnotations::default() }
}
async fn execute(&self, inputs: Value, _ctx: &Context<Value>) -> Result<Value, ModuleError> {
// Used when a caller does not stream.
Ok(json!({ "content": format!("echo:{}", inputs["prompt"].as_str().unwrap_or("")), "done": true }))
}
fn as_streaming(&self) -> Option<&dyn StreamingModule> {
Some(self)
}
}
impl StreamingModule for ChatModule {
fn stream_typed(&self, inputs: Value, _context: &Context<Value>) -> ChunkStream {
let prompt = inputs["prompt"].as_str().unwrap_or("").to_string();
Box::pin(async_stream::stream! {
for token in ["echo:".to_string(), prompt] {
yield Ok(json!({ "content": token, "done": false }));
}
yield Ok(json!({ "content": "", "done": true }));
})
}
}
Registering a module whose annotations.streaming is true while as_streaming() returns None fails with STREAMING_INTERFACE_MISMATCH.
Rules¶
- SDKs export the streaming interface (
StreamingModule/STREAMING_MARKER+isStreamingModule/Module::as_streaming) so adapter code can rely on it. - Adapter and bridge code detects streaming through that interface (
isinstance,isStreamingModule,as_streaming), not throughhasattr/typeofchecks on a method namedstream. - A module that declares
annotations.streaming = truebut whosestream()does not satisfy the interface is rejected at registration withStreamingInterfaceError/STREAMING_INTERFACE_MISMATCH(fields:module_id,expected_signature,actual_signature,mismatch_reason), not at the first call. - A non-streaming module may have an unrelated method named
stream; it is treated as streaming only if it satisfies the interface.
Requirements¶
- Streaming modules satisfy the Streaming Module Interface for their language.
- The executor's
stream()returns an async iterator that yields chunks as the module produces them. - Every chunk is an object; chunks are combined with a depth-capped deep merge into the output that is validated.
- Output validation and after-middleware run on the combined output after the last chunk, not on individual chunks.
- A module without streaming support is called through
execute()and its result is yielded as a single chunk. - Streaming modules should set the
streamingannotation so agents can discover them.
Three-phase streaming pipeline¶
Phase 1 — pipeline setup. Steps 1–7 of the standard pipeline run as for call(), from context creation through input validation. The built-in execute step opens the native producer when available. The configured step's scope and hooks apply to this invocation.
Phase 2 — chunk emission. The executor iterates the module's stream and yields each chunk to the caller immediately, while deep-merging it into the accumulated output. A chunk that is not an object is rejected before delivery (see Contract: Module.stream). The execution deadline covers opening the producer, waiting for chunks, and processing the end of the stream. If it expires, the executor cancels the execution token and reports MODULE_TIMEOUT.
Phase 3 — post-processing. After the last chunk, output validation (step 9) and middleware after (step 10) run on the accumulated output within the same execution deadline. An ordinary failure is logged and reported as apcore.stream.post_validation_failed when an event emitter is configured. Cancellation reaches the consumer as EXECUTION_CANCELLED and bypasses on_error (D-20).
TypeScript resumes the same configured pipeline after the last chunk. Custom steps after the producer retain access to prior step outputs. The result step runs once after the stream drains.
Consuming streams¶
use apcore::{APCore, ModuleError};
use futures::StreamExt;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), ModuleError> {
let client = APCore::new();
client.register("llm.chat", Box::new(ChatModule))?; // ChatModule from the example above
// stream() returns a Stream of Result<Value, ModuleError>; it is not awaited.
let mut chunks = client.stream("llm.chat", json!({ "prompt": "Hello" }), None, None);
while let Some(chunk) = chunks.next().await {
let chunk = chunk?;
print!("{}", chunk["content"].as_str().unwrap_or(""));
}
Ok(())
}
Observe completion¶
Use the opt-in stream completion API when the caller needs the canonical merged output and the post-processing result. The handle drives one invocation. Read the chunks to exhaustion or close the stream before awaiting completion. The legacy stream() entry retains its existing chunk and diagnostic behavior.
The completion has a reason of completed, failed, cancelled, timed_out, or consumer_closed. A canonical error code is present when execution ended with an error. The output is a detached snapshot at the output-validation boundary. The snapshot is absent when execution ends before reaching that boundary. For native streams, it uses the same merge depth and array replacement as the executor. For unary fallback, the call still runs once. After-middleware can change the unary chunk without altering the snapshot.
The completion reports separate outcomes for output_validation and middleware_after. Each outcome has a status of passed, failed, or skipped. A skipped outcome distinguishes a step that is absent, never reached, outside its match scope, or skipped by the strategy. A failure describes whether the pipeline ignored it, recovered it, or left it unhandled. A native stream can have a completed reason with an ordinary post-processing failure. A deadline or cancellation during post-processing yields timed_out or cancelled, respectively. Callers that require validated success check both the reason and the step outcomes.
The consumer can close before the first chunk or during iteration. The first terminal outcome is retained and cleanup can finish separately. In Rust, dropping the owned chunk stream closes it. A loop that borrows the stream leaves ownership with the caller.
import asyncio
from apcore import APCore
async def main() -> None:
client = APCore()
client.register("llm.chat", ChatModule()) # ChatModule from the example above
execution = client.stream_with_completion("llm.chat", {"prompt": "Hello"})
try:
async for chunk in execution.chunks:
print(chunk)
finally:
await execution.aclose()
result = await execution.completion()
print(result.reason, result.output_validation.status, result.output)
asyncio.run(main())
import { APCore } from "apcore-js";
const client = new APCore();
await client.register("llm.chat", new ChatModule()); // ChatModule from the example above
const execution = client.streamWithCompletion("llm.chat", { prompt: "Hello" });
try {
for await (const chunk of execution.chunks) {
console.log(chunk);
}
} finally {
await execution.close();
const result = await execution.completion;
console.log(result.reason, result.outputValidation.status, result.output);
}
use apcore::{APCore, ModuleError};
use futures::StreamExt;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), ModuleError> {
let client = APCore::new();
client.register("llm.chat", Box::new(ChatModule))?; // ChatModule from the example above
let (mut chunks, completion) =
client.stream_with_completion("llm.chat", json!({ "prompt": "Hello" }), None, None);
while let Some(item) = chunks.next().await {
match item {
Ok(chunk) => println!("{chunk}"),
Err(error) => {
eprintln!("{error}");
break;
}
}
}
drop(chunks);
let result = completion.await;
println!("{:?}: {:?}", result.reason, result.output_validation);
Ok(())
}
Completion carries execution data for the trusted caller. Apply the surface's output projection and redaction before returning it through an external protocol.
Run a governed stream from configuration¶
Use the SDK setup from Getting Started. In Rust, also run cargo add futures-util. Save the two files below in the directory from which you run the program. The SDK loads the ACL from acl.root. The rule allows an external caller to invoke api.echo and requires approval. The local example handler approves the expected input. The program checks that the ACL denies another registered module and that the stream's completion contains the merged output.
# acl/global_acl.yaml
version: "1.0"
default_effect: deny
audit:
enabled: true
include_denied: true
log_level: info
rules:
- callers: ["@external"]
targets: ["api.echo"]
effect: allow
approval: required
import asyncio
from collections.abc import AsyncIterator
from apcore import APCore, Config, Context, ModuleAnnotations, ModuleError
from apcore.approval import ApprovalRequest, ApprovalResult, CallbackApprovalHandler
from pydantic import BaseModel
class EchoInput(BaseModel):
text: str
class EchoOutput(BaseModel):
text: str
done: bool
class Echo:
description = "Stream the supplied text"
input_schema = EchoInput
output_schema = EchoOutput
annotations = ModuleAnnotations(streaming=True)
async def execute(self, inputs: dict, context: Context) -> dict:
return {"text": inputs["text"], "done": True}
async def stream(self, inputs: dict, context: Context) -> AsyncIterator[dict]:
yield {"text": inputs["text"], "done": False}
yield {"done": True}
async def main() -> None:
config = Config.load("apcore.yaml")
assert config.get("project.name") == "stream-demo"
client = APCore(config=config)
client.register("api.echo", Echo())
client.register("api.denied", Echo())
approved = []
async def approve(request: ApprovalRequest) -> ApprovalResult:
if request.module_id == "api.echo" and request.arguments == {"text": "hello"}:
approved.append(request.module_id)
return ApprovalResult(status="approved", approved_by="demo-policy")
return ApprovalResult(status="rejected", reason="Unexpected invocation")
client.executor.set_approval_handler(CallbackApprovalHandler(approve))
try:
await client.call_async("api.denied", {"text": "hello"})
except ModuleError as error:
assert error.code == "ACL_DENIED", error
else:
raise AssertionError("Expected the ACL to deny api.denied")
execution = client.stream_with_completion("api.echo", {"text": "hello"})
chunks = [chunk async for chunk in execution.chunks]
result = await execution.completion()
assert approved == ["api.echo"]
assert chunks == [{"text": "hello", "done": False}, {"done": True}]
assert result.reason == "completed"
assert result.output_validation.status == "passed"
assert result.output == {"text": "hello", "done": True}
asyncio.run(main())
import { deepStrictEqual, equal, rejects } from "node:assert/strict";
import { Type } from "@sinclair/typebox";
import {
ACLDeniedError,
APCore,
CallbackApprovalHandler,
Config,
STREAMING_MARKER,
createApprovalResult,
} from "apcore-js/full";
import type { StreamingModule } from "apcore-js";
class EchoModule implements StreamingModule {
readonly [STREAMING_MARKER] = true as const;
inputSchema = Type.Object({ text: Type.String() });
outputSchema = Type.Object({ text: Type.String(), done: Type.Boolean() });
description = "Stream one text value and a completion flag";
annotations = { streaming: true };
async execute(inputs: Record<string, unknown>): Promise<Record<string, unknown>> {
return { text: inputs.text, done: true };
}
async *stream(inputs: Record<string, unknown>): AsyncGenerator<Record<string, unknown>> {
yield { text: inputs.text, done: false };
yield { done: true };
}
}
const config = Config.load("apcore.yaml");
equal(config.get("project.name"), "stream-demo");
const client = new APCore({ config });
let approvalCalls = 0;
client.executor.setApprovalHandler(new CallbackApprovalHandler(async (request) => {
approvalCalls += 1;
equal(request.moduleId, "api.echo");
deepStrictEqual(request.arguments, { text: "hello" });
return createApprovalResult({ status: "approved", approvedBy: "demo-reviewer" });
}));
await client.register("api.echo", new EchoModule());
await client.register("api.denied", new EchoModule());
await rejects(() => client.call("api.denied", { text: "hello" }), ACLDeniedError);
const execution = client.streamWithCompletion("api.echo", { text: "hello" });
const chunks: Record<string, unknown>[] = [];
try {
for await (const chunk of execution.chunks) {
chunks.push(chunk);
}
} finally {
await execution.close();
}
const completion = await execution.completion;
equal(approvalCalls, 1);
deepStrictEqual(chunks, [{ text: "hello", done: false }, { done: true }]);
equal(completion.reason, "completed");
equal(completion.outputValidation.status, "passed");
deepStrictEqual(completion.output, { text: "hello", done: true });
use std::path::Path;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use apcore::{
APCore, APCoreOptions, ApprovalResult, CallbackApprovalHandler, ChunkStream, Config, Context,
ErrorCode, Module, ModuleAnnotations, ModuleError, StreamEndReason, StreamStepOutcome,
StreamingModule,
};
use async_trait::async_trait;
use futures_util::{stream, StreamExt};
use serde_json::{json, Value};
struct Echo;
#[async_trait]
impl Module for Echo {
fn description(&self) -> &str {
"Echo the approved text"
}
fn input_schema(&self) -> Value {
json!({
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"]
})
}
fn output_schema(&self) -> Value {
json!({
"type": "object",
"properties": {"text": {"type": "string"}, "done": {"type": "boolean"}},
"required": ["text", "done"]
})
}
fn annotations(&self) -> ModuleAnnotations {
ModuleAnnotations {
streaming: true,
..ModuleAnnotations::default()
}
}
async fn execute(
&self,
inputs: Value,
_context: &Context<Value>,
) -> Result<Value, ModuleError> {
Ok(json!({"text": inputs["text"], "done": true}))
}
fn as_streaming(&self) -> Option<&dyn StreamingModule> {
Some(self)
}
}
impl StreamingModule for Echo {
fn stream_typed(&self, inputs: Value, _context: &Context<Value>) -> ChunkStream {
Box::pin(stream::iter([
Ok(json!({"text": inputs["text"], "done": false})),
Ok(json!({"done": true})),
]))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load(Path::new("apcore.yaml"))?;
assert_eq!(config.get("project.name"), Some(json!("stream-demo")));
let approvals = Arc::new(AtomicUsize::new(0));
let decisions = Arc::clone(&approvals);
let handler = CallbackApprovalHandler::new(move |request| {
decisions.fetch_add(1, Ordering::Relaxed);
async move {
if request.module_id == "api.echo" && request.arguments["text"] == "hello" {
Ok(ApprovalResult::approved("local-policy"))
} else {
Ok(ApprovalResult::rejected("Only hello is allowed"))
}
}
});
let client = APCore::try_start(APCoreOptions {
config: Some(config),
approval_handler: Some(Box::new(handler)),
..APCoreOptions::default()
})?;
client.register("api.echo", Box::new(Echo))?;
client.register("api.denied", Box::new(Echo))?;
let denied = client
.call("api.denied", json!({"text": "hello"}), None, None)
.await
.expect_err("An unlisted module is denied by the ACL");
assert_eq!(denied.code, ErrorCode::ACLDenied);
assert_eq!(approvals.load(Ordering::Relaxed), 0);
let (mut chunks, completion) =
client.stream_with_completion("api.echo", json!({"text": "hello"}), None, None);
assert_eq!(
chunks.next().await.transpose()?,
Some(json!({"text": "hello", "done": false}))
);
assert_eq!(
chunks.next().await.transpose()?,
Some(json!({"done": true}))
);
assert!(chunks.next().await.is_none());
let result = completion.await;
assert_eq!(result.reason, StreamEndReason::Completed);
assert_eq!(result.output_validation, StreamStepOutcome::Passed);
assert_eq!(result.output, Some(json!({"text": "hello", "done": true})));
assert_eq!(approvals.load(Ordering::Relaxed), 1);
Ok(())
}
Deep merge¶
Chunks are combined with a recursive deep merge (Algorithm A24):
| Left value | Right value | Result |
|---|---|---|
| object | object | merged recursively |
| anything else | anything else | right value wins — arrays are replaced, not concatenated |
Recursion stops at stream.max_merge_depth levels (default 32). At the cap, an object is merged by assigning its keys at that level. For other values, the right side replaces the left. The accumulator is updated as each chunk arrives, so its retained data follows the size of the merged result.
Chunk 1: {"content": "Hello", "metadata": {"tokens": 1}}
Chunk 2: {"content": " world", "metadata": {"tokens": 1, "model": "gpt-4"}}
Merged: {"content": " world", "metadata": {"tokens": 1, "model": "gpt-4"}}
Note
Strings are not concatenated. A module that wants the validated output to contain the full text should yield the growing string, or put the complete text in its final chunk.
Fallback behaviour¶
When the executor's stream() is called for a module without streaming support, it runs execute() and yields the result as a single chunk; no merge is needed.
Streaming annotation¶
The annotation lets AI agents discover streamable modules and lets schema export advertise the capability. It also opts the module into the registration-time interface check above.
Dependencies¶
- Core Executor — runs the three-phase pipeline.
- Middleware System — before-middleware runs in phase 1, after-middleware in phase 3.
- Schema System — output validation runs on the accumulated output in phase 3.
- Cancellation — a module can check its cancel token between chunks for cooperative cancellation.
Python SDK reference
Not a protocol requirement — the relevant apcore-python source files.
| File | Purpose |
|---|---|
src/apcore/streaming.py |
StreamingModule Protocol |
src/apcore/executor.py |
Executor.stream() three-phase pipeline and the depth-capped deep merge |
Testing strategy¶
- Basic streaming — chunks arrive in order; the accumulated output is correct.
- Deep merge — recursive object merge, array replacement, scalar replacement, depth cap (
conformance/fixtures/stream_aggregation.json). - Fallback — a non-streaming module produces a single-chunk stream.
- Pipeline integration — before-middleware runs before the first chunk; after-middleware runs after the last.
- Validation — output validation runs on the accumulated output; a phase-3 failure does not affect chunks already delivered.
- Non-object chunk — rejected with
STREAM_CHUNK_NOT_OBJECTand never delivered. - Cancellation — cancelling mid-stream stops emission and raises
ExecutionCancelledError.
Contract: Module.stream¶
Inputs¶
inputs(dict/object/Value, required) — already validated against the module'sinput_schemacontext(Context, required) — execution context
Errors¶
- An error raised by the module mid-stream ends the stream and is propagated to the consumer.
- Native stream chunks use the same JSON object representation as module return values. The executor projects each chunk before merging or delivering it. A non-object chunk (array, string, number, boolean, null) raises
InvalidInputError(GENERAL_INVALID_INPUT) withdetails.codeset toSTREAM_CHUNK_NOT_OBJECT, plusdetails.chunk_indexanddetails.actual_type(the JSON type name) (D-58).
Returns¶
AsyncIterator[dict]/AsyncGenerator<Record<string, unknown>>/ChunkStream(aStreamofResult<Value, ModuleError>) — a lazy sequence of partial output objects.
Properties¶
- async: true
- thread_safe: false (a stream instance is not shared across concurrent consumers)
- pure: false (may hold open connections or file handles)
- idempotent: false