LlamaIndex Free code examples in Python and JavaScript
Built specifically around ingestion, indexing and retrieval.
Try it without writing code: Document Summarizer — free in the browser.
WHAT THIS PAGE COVERS
An ingestion pipeline that does not re-embed unchanged documents.
text-embedding-3-small
llama-index-core
Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.
llama-index-core plus whichever integrations you need. The umbrella `llama-index` package pulls in a lot you will not use; core plus two integrations is the leaner start.
pip install llama-index-core llama-index-embeddings-openai
pip install llama-index-vector-stores-qdrant
export OPENAI_API_KEY="sk-your-key" # macOS / Linux
setx OPENAI_API_KEY "sk-your-key" # Windows, then open a new shell
THE DOCSTORE IS THE POINT. It stores doc_id to content hash, so the second run skips every unchanged document before the embedding step — the difference between paying for the delta and paying for the archive.
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.storage.docstore import SimpleDocumentStore
from llama_index.embeddings.openai import OpenAIEmbedding
pipeline = IngestionPipeline(
transformations=[
SentenceSplitter(chunk_size=512, chunk_overlap=64),
OpenAIEmbedding(model="text-embedding-3-small"),
],
docstore=SimpleDocumentStore(),
)
nodes = pipeline.run(documents=documents)
print(f"{len(nodes)} nodes embedded")
DEDUPLICATION IS KEYED ON doc_id. A uuid4 per run means nothing ever matches and the docstore quietly does nothing — the pipeline still works, it just costs full price forever.
from llama_index.core import Document
from llama_index.core import SimpleDirectoryReader
# filename_as_id gives every file a stable id across runs.
documents = SimpleDirectoryReader(
"./handbook", filename_as_id=True).load_data()
# Building them by hand: the id must come from the SOURCE, never
# from uuid4() or datetime.now().
documents = [
Document(
text=row["body"],
doc_id=f"ticket-{row['id']}", # stable, from the database
metadata={"source": row["source"], "page": row["page"]},
)
for row in rows
]
SimpleDocumentStore lives in memory. A process that exits without persisting starts the next run with an empty map and re-embeds everything — which is the failure this whole recipe exists to avoid.
import os
PIPELINE_DIR = "./pipeline-storage"
if os.path.exists(PIPELINE_DIR):
pipeline.load(PIPELINE_DIR) # restore the hashes
nodes = pipeline.run(documents=documents)
pipeline.persist(PIPELINE_DIR) # save them again
# Run it twice with no source changes: the second run should report
# zero nodes. If it does not, the ids are not stable.
The index is built from the nodes the pipeline produced. similarity_top_k is the retrieval budget — more context is not free, and past about five chunks most models get worse rather than better.
from llama_index.core import VectorStoreIndex
index = VectorStoreIndex(nodes)
engine = index.as_query_engine(similarity_top_k=5)
response = engine.query("What does error code E-4471 mean?")
print(response)
# The sources are on the response. Show them — a RAG answer without
# citations is indistinguishable from a guess.
for node in response.source_nodes:
print(round(node.score, 4), node.metadata.get("source"))
The TypeScript port is `llamaindex` plus provider packages. It tracks the Python library rather than leading it, so a feature that is new in Python may not be here yet.
npm install llamaindex @llamaindex/openai
export OPENAI_API_KEY="sk-your-key"
Same idea as Python: a docstore holding content hashes, checked before the expensive step. Everything is async here.
import { IngestionPipeline, SentenceSplitter } from "llamaindex";
import { SimpleDocumentStore } from "@llamaindex/core/storage";
import { OpenAIEmbedding } from "@llamaindex/openai";
const pipeline = new IngestionPipeline({
transformations: [
new SentenceSplitter({ chunkSize: 512, chunkOverlap: 64 }),
new OpenAIEmbedding({ model: "text-embedding-3-small" }),
],
docStore: new SimpleDocumentStore(),
});
const nodes = await pipeline.run({ documents });
console.log(`${nodes.length} nodes embedded`);
The hash map is keyed on the document id. Generate it per run and nothing ever matches — the pipeline works and the saving never arrives.
import { Document } from "llamaindex";
const documents = rows.map(
(row) =>
new Document({
text: row.body,
// Stable, from the source. NOT crypto.randomUUID().
id_: `ticket-${row.id}`,
metadata: { source: row.source, page: row.page },
}),
);
// Run the pipeline twice with no changes: the second run should
// produce zero nodes. If it does not, these ids are not stable.
retrieve() returns scored nodes with their metadata. Surfacing those is what separates a RAG answer from a confident guess.
import { VectorStoreIndex } from "llamaindex";
const index = await VectorStoreIndex.init({ nodes });
const engine = index.asQueryEngine({ similarityTopK: 5 });
const response = await engine.query({
query: "What does error code E-4471 mean?",
});
console.log(response.message.content);
for (const node of response.sourceNodes ?? []) {
console.log(node.score?.toFixed(4), node.node.metadata.source);
}
QUESTIONS
Which languages are the LlamaIndex examples in?
Python and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.
Which package do I install for LlamaIndex?
The samples use llama-index-core. The install step on each language tab gives the exact command.
Which LlamaIndex model do these examples use?
text-embedding-3-small, checked against the official documentation on 26 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.
Where is the official LlamaIndex documentation?
https://docs.llamaindex.ai/ — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.
ALSO IN FRAMEWORKS & SDKS
The authority
Official LlamaIndex documentation
Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.
https://docs.llamaindex.ai/