streaming-rag
Streaming LLM responses with inline citations. Token-level source attribution, SSE vs WebSocket, TTFT optimization, progressive disclosure (retrieval status then tokens), Python async generators, Vercel AI SDK streaming with sources, LangChain streaming callbacks, client-side citation rendering. USE WHEN: user mentions "streaming RAG", "streaming citations", "SSE RAG", "TTFT", "progressive disclosure", "AI SDK streaming", "token streaming", "inline citations" DO NOT USE FOR: generic RAG pipelines - use `rag-architecture`; citation correctness evaluation - use `rag-evaluation`; conversational memory - use `conversational-rag`
What this skill does
# Streaming RAG
## Why Streaming Matters for RAG
RAG end-to-end latency is typically 1.5-4s. Non-streaming feels broken; streaming cuts perceived latency by 5-10x because users start reading within ~200ms of generation start.
Budget target:
- First retrieval status: < 100ms (from request)
- Retrieval done: < 800ms
- First token: < 1000ms (TTFT)
- Full answer: < 3500ms
## Three Streaming Phases
```
[request] --100ms--> status: "retrieving..."
--800ms--> status: "reading 5 sources"
--1000ms--> first answer token
--3500ms--> done + citations
```
Keep the user informed in phase 1-2 so they do not bail on the request.
## Server-Side: Python Async Generator (FastAPI + SSE)
```python
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from anthropic import AsyncAnthropic
import asyncio
import json
app = FastAPI()
client = AsyncAnthropic()
async def rag_stream(question: str):
yield sse({"type": "status", "message": "retrieving"})
docs = await retriever.ainvoke(question)
yield sse({"type": "status", "message": f"reading {len(docs)} sources"})
yield sse({"type": "sources", "sources": [
{"id": d.metadata["id"], "title": d.metadata["title"], "url": d.metadata["url"]}
for d in docs
]})
context = "\n\n".join(
f"[{d.metadata['id']}] {d.page_content}" for d in docs
)
prompt = (
f"Answer using context. Cite sources inline as [id]. If unknown, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
async with client.messages.stream(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
) as stream:
async for text in stream.text_stream:
yield sse({"type": "token", "text": text})
final = await stream.get_final_message()
yield sse({"type": "done",
"usage": {"input": final.usage.input_tokens,
"output": final.usage.output_tokens}})
def sse(payload: dict) -> str:
return f"data: {json.dumps(payload)}\n\n"
@app.post("/rag/stream")
async def rag_endpoint(body: dict):
return StreamingResponse(rag_stream(body["question"]), media_type="text/event-stream")
```
Six event types over the wire: `status`, `sources`, `token`, `done`, `error`, `heartbeat`.
## Heartbeats (required for long retrievals behind proxies)
Nginx/Cloudflare terminate idle connections at 30-60s. Emit a heartbeat every 15s during retrieval.
```python
async def with_heartbeat(gen, interval: float = 15.0):
q: asyncio.Queue = asyncio.Queue()
async def pump():
async for item in gen:
await q.put(("item", item))
await q.put(("end", None))
task = asyncio.create_task(pump())
while True:
try:
kind, item = await asyncio.wait_for(q.get(), timeout=interval)
if kind == "end": break
yield item
except asyncio.TimeoutError:
yield sse({"type": "heartbeat"})
await task
```
## Inline Citations via Anthropic Citations API
Claude supports native citations that bind token spans to source documents. Cleaner than manual [id] instructions.
```python
async def rag_with_native_citations(question: str, docs):
blocks = [
{
"type": "document",
"source": {"type": "text", "media_type": "text/plain", "data": d.page_content},
"title": d.metadata.get("title", "source"),
"citations": {"enabled": True},
}
for d in docs
]
async with client.messages.stream(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": [*blocks, {"type": "text", "text": question}],
}],
) as stream:
async for event in stream:
if event.type == "content_block_delta":
delta = event.delta
if delta.type == "text_delta":
yield sse({"type": "token", "text": delta.text})
elif delta.type == "citations_delta":
yield sse({"type": "citation",
"citation": delta.citation.model_dump()})
```
Client renders the citation as a hoverable footnote anchored to the adjacent token.
## LangChain Streaming with Callbacks (LCEL 0.3+)
```python
from langchain.chains import create_retrieval_chain
from langchain_core.runnables import RunnableConfig
async def stream(question: str):
yield sse({"type": "status", "message": "retrieving"})
async for event in rag_chain.astream_events(
{"input": question},
version="v2",
config=RunnableConfig(tags=["rag"]),
):
kind = event["event"]
if kind == "on_retriever_end":
docs = event["data"]["output"]
yield sse({"type": "sources", "sources": [
{"id": d.metadata["id"], "title": d.metadata["title"]} for d in docs
]})
elif kind == "on_chat_model_stream":
chunk = event["data"]["chunk"]
if chunk.content:
yield sse({"type": "token", "text": chunk.content})
elif kind == "on_chain_end" and event["name"] == "retrieval_chain":
yield sse({"type": "done"})
```
`astream_events` gives a single unified stream of retrieval + generation events — avoids threading two streams manually.
## TypeScript: Vercel AI SDK with Sources
The AI SDK's `streamText` natively supports `sources` stream parts and client hooks.
```ts
import { streamText, convertToCoreMessages, tool } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod';
export async function POST(req: Request) {
const { messages } = await req.json();
const q = messages[messages.length - 1].content;
const docs = await retriever.search(q, 5);
const result = streamText({
model: anthropic('claude-sonnet-4-5-20250929'),
messages: convertToCoreMessages(messages),
system: `Answer using the provided sources. Cite inline as [id].`,
experimental_providerMetadata: {
anthropic: {
cacheControl: { type: 'ephemeral' },
},
},
experimental_attachments: docs.map((d) => ({
name: d.title,
contentType: 'text/plain',
url: `data:text/plain;base64,${Buffer.from(d.text).toString('base64')}`,
})),
onFinish: async ({ usage, text }) => {
await logUsage(usage, text);
},
});
return result.toDataStreamResponse({
sendSources: true,
getErrorMessage: (err) => 'Stream error; please retry.',
});
}
```
Client with `useChat`:
```tsx
'use client';
import { useChat } from 'ai/react';
export function Chat() {
const { messages, input, handleInputChange, handleSubmit, data } = useChat();
return (
<>
{messages.map((m) => (
<div key={m.id}>
<p>{m.content}</p>
{m.experimental_attachments?.map((a, i) => (
<a key={i} href={a.url}>{a.name}</a>
))}
</div>
))}
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleInputChange} />
</form>
</>
);
}
```
## Client-Side Citation Rendering
Regex `\[(\w+)\]` tokens and replace at stream-end (not per-token — regex on a partial token can mis-match).
```tsx
import { useMemo } from 'react';
function CitedAnswer({ text, sources }: { text: string; sources: Source[] }) {
const rendered = useMemo(() => {
const parts = text.split(/(\[[\w-]+\])/g);
return parts.map((p, i) => {
const m = p.match(/^\[([\w-]+)\]$/);
if (!m) return <span key={i}>{p}</span>;
const s = sources.find((x) => x.id === m[1]);
if (!s) return <span key={i}>{p}</span>;
return (
<a key={i} href={s.url} title={s.title} className="citation">
[{sources.indexOf(s) + 1}]
</a>
);
});
}, [text, sources]);
return <p>{rendered}</p>;
}
```
DoRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.