Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | 4x 4x 4x 4x 4x 4x 4x 10x 10x 10x 5x 5x 10x 1x 1x 10x 1x 1x 10x 3x 3x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 4x 4x 2x 1x 1x 1x 1x 4x 2x 2x 4x 1x 1x 2x 2x 2x 2x 2x 4x 3x 3x 2x 2x 2x 1x 1x 1x 1x 2x 2x 1x 1x 1x | /**
* AgentKits — Streaming Utilities
*
* Unified streaming interface across providers.
* Stream transformers, collectors, and abort support.
*
* Usage:
* import { collectStream, transformStream } from 'agentkits/streaming';
*/
// ── Types ──────────────────────────────────────────────────────────
export interface StreamEvent {
type: 'content' | 'tool_call' | 'usage' | 'done' | 'error';
content?: string;
toolCall?: { id: string; name: string; arguments: string };
usage?: { promptTokens: number; completionTokens: number; totalTokens: number };
error?: string;
}
export interface StreamOptions {
/** AbortSignal for cancellation */
signal?: AbortSignal;
/** Callback for each chunk */
onChunk?: (event: StreamEvent) => void;
}
export type StreamTransformer = (events: AsyncIterable<StreamEvent>) => AsyncIterable<StreamEvent>;
// ── SSE Parser ─────────────────────────────────────────────────────
/** Parse Server-Sent Events from a ReadableStream or Response */
export async function* parseSSE(
input: ReadableStream<Uint8Array> | Response,
signal?: AbortSignal,
): AsyncIterable<StreamEvent> {
const stream = input instanceof Response ? input.body! : input;
const reader = stream.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
if (signal?.aborted) break;
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: ')) {
const data = line.slice(6).trim();
if (data === '[DONE]') {
yield { type: 'done' };
return;
}
try {
const parsed = JSON.parse(data);
const delta = parsed.choices?.[0]?.delta;
if (delta?.content) {
yield { type: 'content', content: delta.content };
}
if (delta?.tool_calls?.[0]) {
const tc = delta.tool_calls[0];
yield {
type: 'tool_call',
toolCall: { id: tc.id ?? '', name: tc.function?.name ?? '', arguments: tc.function?.arguments ?? '' },
};
}
if (parsed.usage) {
yield {
type: 'usage',
usage: {
promptTokens: parsed.usage.prompt_tokens,
completionTokens: parsed.usage.completion_tokens,
totalTokens: parsed.usage.total_tokens,
},
};
}
if (parsed.choices?.[0]?.finish_reason) {
yield { type: 'done' };
}
} catch {
// Skip unparseable lines
}
}
}
}
} finally {
reader.releaseLock();
}
}
// ── Collectors ──────────────────────────────────────────────────────
/** Collect an async stream of events into a single string */
export async function collectStream(
stream: AsyncIterable<StreamEvent>,
options?: StreamOptions,
): Promise<{ content: string; usage?: StreamEvent['usage'] }> {
const parts: string[] = [];
let usage: StreamEvent['usage'];
for await (const event of stream) {
if (options?.signal?.aborted) break;
if (options?.onChunk) options.onChunk(event);
if (event.type === 'content' && event.content) {
parts.push(event.content);
}
if (event.type === 'usage' && event.usage) {
usage = event.usage;
}
if (event.type === 'error') {
throw new Error(event.error ?? 'Stream error');
}
}
return { content: parts.join(''), usage };
}
/** Count tokens in a stream (passes through) */
export async function* countStreamTokens(
stream: AsyncIterable<StreamEvent>,
countFn?: (text: string) => number,
): AsyncIterable<StreamEvent & { tokenCount?: number }> {
const counter = countFn ?? ((t: string) => Math.ceil(t.length / 4));
let totalTokens = 0;
for await (const event of stream) {
if (event.type === 'content' && event.content) {
totalTokens += counter(event.content);
yield { ...event, tokenCount: totalTokens };
} else {
yield event;
}
}
}
/** Extract only content strings from a stream */
export async function* extractContent(
stream: AsyncIterable<StreamEvent>,
): AsyncIterable<string> {
for await (const event of stream) {
if (event.type === 'content' && event.content) {
yield event.content;
}
}
}
/** Create an abortable wrapper around a stream */
export function createAbortableStream(
stream: AsyncIterable<StreamEvent>,
): { stream: AsyncIterable<StreamEvent>; abort: () => void } {
const controller = new AbortController();
async function* abortable(): AsyncIterable<StreamEvent> {
for await (const event of stream) {
if (controller.signal.aborted) return;
yield event;
}
}
return { stream: abortable(), abort: () => controller.abort() };
}
/** Compose multiple stream transformers */
export function composeTransformers(...transformers: StreamTransformer[]): StreamTransformer {
return (stream) => {
let current = stream;
for (const t of transformers) {
current = t(current);
}
return current;
};
}
|