streaming-rag
БесплатноБез исполняемых скриптовНе проверенStreaming LLM responses with inline citations. Token-level source attribution, SSE vs WebSocket, TTFT optimization, progressive disclosure (retrieval status…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
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)
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.
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.
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+)
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["t
Установить streaming-rag в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл 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`
Как установить скилл streaming-rag?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл streaming-rag запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic