Reference

Code snippet library

Copy-paste starters for chat, streaming, embeddings, RAG, and tools. Filter by tag or search below.

31 snippets

Minimal RAG loop

python · rag, python, embeddings

# Pseudocode — swap embed/search for your stack
chunks = ["Annual refunds within 14 days.", "Monthly plans auto-renew."]
index = [(embed(c), c) for c in chunks]

Chunk text by words

python · rag, python, chunking

def chunk_words(text: str, size: int = 120, overlap: int = 20) -> list[str]:
    words = text.split()
    chunks = []

Summarize chat history

python · python, memory, chat

def compress_history(messages: list[dict], keep_last: int = 4) -> list[dict]:
    if len(messages) <= keep_last + 1:
        return messages

RAG prompt with citations

text · rag, prompt, citations

You answer using ONLY the notes below.
After each factual sentence, cite the chunk ID in square brackets, e.g. [faq#2].
If the notes do not support an answer, reply: "Not in the notes."

Synthetic media disclosure label

text · synthetic-media, disclosure, literacy

Disclosure: This [video/audio/image] was created or edited with AI.
[Real person's name] [did / did not] consent to the use of their likeness.
Do not treat this as official communication from [organization] without verification.

Merge keyword + vector hits

typescript · rag, search

function mergeHits(keyword: ChunkHit[], vector: ChunkHit[], limit = 20) {
  const byId = new Map<string, ChunkHit>();
  for (const hit of [...keyword, ...vector]) {

Pass request ID through LLM calls

typescript · tracing, nextjs, observability

export async function POST(req: Request) {
  const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
  const span = tracer.startSpan("chat", { attributes: { requestId } });

Tool allowlist check

typescript · tools, security, agents

const ALLOWED = new Set(["search_docs", "create_ticket"]);

function handleToolCall(name: string, args: unknown) {
← Reference hub