Claude API Semantic Search: Implementation Tutorial
What "Claude API semantic search" actually means
Claude doesn't generate embeddings itself — there's no embeddings endpoint in the Messages API. Semantic search with Claude is a two-system pattern: an embedding model turns text into vectors so you can find similar meaning instead of matching keywords, and Claude handles the reasoning on top — reranking candidates, synthesizing an answer, or deciding which result actually answers the user's question. If you landed here expecting a single API call that does semantic search end-to-end, that call doesn't exist, but the full pipeline is straightforward to build and this tutorial walks through it.
The practical architecture is: embed → store → retrieve → rank/answer with Claude. You generate embeddings with a dedicated embeddings model (Voyage AI is Anthropic's recommended partner, but OpenAI's or any other embedding model works the same way), store vectors in a vector database or even a Postgres table with pgvector, retrieve the top-N nearest matches for a query, and hand those matches to Claude to produce the final, grounded answer.
Step 1: Generate embeddings for your documents
Chunk your source documents (500–1000 tokens per chunk is a reasonable default), then embed each chunk:
async function embed(text) {
const res = await fetch("https://api.voyageai.com/v1/embeddings", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.VOYAGE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
input: [text],
model: "voyage-3",
}),
});
const data = await res.json();
return data.data[0].embedding;
}
Store the vector alongside the chunk text and a reference to the source document (file name, page number, URL — whatever you'll need to cite later).
Step 2: Store vectors and query by similarity
Any vector store works here — Pinecone, Qdrant, Weaviate, or pgvector in Postgres. The query flow is the same regardless of backend:
SELECT content, source, 1 - (embedding <=> $1) AS similarity
FROM document_chunks
ORDER BY embedding <=> $1
LIMIT 10;
Embed the user's query with the same embedding model you used for the documents, pass that vector as $1, and you get back the 10 chunks closest in meaning to the question — not just chunks sharing keywords.
Step 3: Let Claude rerank and answer
Raw vector similarity is a decent first pass but it's noisy — the top-10 nearest neighbors often include tangential matches. This is where Claude earns its place in the pipeline: feed it the retrieved chunks and the original question, and ask it to either rerank them by actual relevance or go straight to answering using only the relevant ones.
async function answerWithContext(question, chunks) {
const context = chunks
.map((c, i) => `[${i}] (source: ${c.source})\n${c.content}`)
.join("\n\n");
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: `Using only the context below, answer the question. Cite the source index for each claim. If the context doesn't contain the answer, say so.
Context:
${context}
Question: ${question}`,
},
],
}),
});
return res.json();
}
This gets you grounded, cited answers instead of raw search results, and it filters out the chunks that matched on vector similarity but aren't actually useful. For a simple reranking-only step (no final answer, just a reordered list), you can ask Claude to return the chunk indices ranked by relevance as structured output — see /docs/messages for request formatting and /docs/tools if you want it to return a strict JSON array instead of prose.
Putting the full pipeline together
async function semanticSearch(question) {
const queryVector = await embed(question);
const candidates = await vectorStore.query(queryVector, { topK: 10 });
const answer = await answerWithContext(question, candidates);
return answer;
}
Three external calls per query: one embedding call, one vector store lookup (usually local/fast), and one Claude call. The Claude call is the most expensive step latency-wise, so for high-traffic search it's worth caching answers for repeated or near-duplicate questions.
Where SubToAPI fits
The embedding and vector-store pieces of this pipeline are infrastructure you manage yourself regardless of which LLM provider you use. SubToAPI's job is the Claude call at the end: it wraps your Claude access in a standard HTTPS API with its own sub_live_... keys, so your retrieval service authenticates with a scoped key instead of a raw provider credential, you get usage metadata per request to track cost by search query type, and streaming works out of the box if you want to stream the synthesized answer back to users (see /docs/streaming). Sign up at /signup, check /pricing for the Solo, Team, and Scale tiers, and /docs/quickstart to get a key running in a few minutes.
Common mistakes to avoid
- Embedding the whole document instead of chunks. Large embeddings average out meaning and retrieval gets vague. Chunk first.
- Using different embedding models for queries and documents. Vectors from different models aren't comparable — always embed with the same model on both sides.
- Skipping the Claude rerank/answer step. Raw top-K vector results are a starting point, not a finished search experience, especially for multi-part or ambiguous questions.
- No source tracking. Store the origin of every chunk so Claude (and your UI) can cite it. Ungrounded answers erode trust fast.
- Ignoring chunk overlap. A hard cutoff mid-sentence or mid-table loses meaning; a 10–20% overlap between adjacent chunks improves retrieval quality.
questions
Does the Claude API have a built-in embeddings or search endpoint? No. Claude's API handles chat/completion (Messages, streaming, tool use) but not embeddings. Pair it with a dedicated embeddings provider and a vector store for the retrieval half of semantic search.
Which embedding model should I use with Claude? Voyage AI is Anthropic's recommended embeddings partner and tends to work well for retrieval-augmented pipelines feeding Claude, but any embedding model (OpenAI's, open-source alternatives) works — just stay consistent between document and query embeddings.
How do I keep Claude's answers grounded in the retrieved chunks instead of hallucinating? Instruct it explicitly to answer only from the provided context, require source citations per claim, and tell it to say "not found in context" when the retrieved chunks don't cover the question — this single instruction change noticeably reduces fabricated answers.