Claude API RAG with Pinecone Vector Database
What this guide actually covers
If you're searching for "Claude API RAG with Pinecone," you're trying to answer one question: how do I let Claude answer questions using my own documents instead of just its training data? The short answer is retrieval-augmented generation (RAG) — you store your documents as vectors in Pinecone, retrieve the most relevant chunks at query time, and pass them to Claude as context alongside the user's question.
Claude itself has no built-in vector database or retrieval mechanism. It's a text-in, text-out model (plus tool calling). Pinecone fills the gap by handling similarity search over embeddings, and your application glues the two together: embed → store → retrieve → generate. This article walks through that pipeline end to end, with code you can adapt directly.
The architecture in four steps
A RAG system built on Claude and Pinecone has four moving parts:
- Chunking — split source documents into retrievable pieces (usually 200–800 tokens each).
- Embedding — convert chunks into vectors using an embedding model (Claude doesn't generate embeddings, so you need a separate model like Voyage AI or OpenAI's embedding endpoints).
- Storage and retrieval — store vectors in Pinecone with metadata, and query the index for the top-k most relevant chunks at runtime.
- Generation — send the retrieved chunks plus the user's question to Claude, which produces the final answer grounded in your data.
Steps 1–3 are Pinecone's job. Step 4 is where Claude comes in.
Step 1: Chunk and embed your documents
Keep chunks semantically coherent — split on headings or paragraphs rather than fixed character counts when possible. Overlapping chunks by 10–15% helps avoid losing context at boundaries.
import { Pinecone } from "@pinecone-database/pinecone";
import { VoyageAIClient } from "voyageai";
const pc = new Pinecone({ apiKey: process.env.PINECONE_API_KEY });
const voyage = new VoyageAIClient({ apiKey: process.env.VOYAGE_API_KEY });
async function embedChunks(chunks) {
const result = await voyage.embed({
input: chunks,
model: "voyage-3",
});
return result.data.map((d) => d.embedding);
}
Anthropic doesn't ship its own embedding API, so you pick one separately. Voyage AI is commonly recommended alongside Claude because it was tuned with Anthropic's retrieval use cases in mind, but any decent embedding model works.
Step 2: Store vectors in Pinecone
Create an index matching your embedding model's dimension (1024 for voyage-3), then upsert vectors with metadata so you can trace answers back to source documents.
const index = pc.index("docs-index");
async function upsertChunks(chunks, embeddings, sourceId) {
const vectors = chunks.map((text, i) => ({
id: `${sourceId}-${i}`,
values: embeddings[i],
metadata: { text, sourceId, chunkIndex: i },
}));
await index.upsert(vectors);
}
Attach whatever metadata you'll need for filtering later — document type, date, customer ID, access level. This matters a lot once you have more than one tenant or document category, since you'll want Pinecone's metadata filters to scope retrieval before it ever reaches Claude.
Step 3: Retrieve relevant chunks at query time
At query time, embed the user's question with the same model, query Pinecone for the top-k matches, and extract the text from the metadata.
async function retrieveContext(question, k = 5) {
const [queryEmbedding] = await embedChunks([question]);
const results = await index.query({
vector: queryEmbedding,
topK: k,
includeMetadata: true,
});
return results.matches.map((m) => m.metadata.text).join("\n\n---\n\n");
}
Five to eight chunks is a reasonable starting point. Too few and Claude lacks context; too many and you waste tokens on irrelevant text, which also increases latency and cost.
Step 4: Send context and question to Claude
Once you have retrieved context, build a prompt that clearly separates reference material from the question, and instruct Claude to answer only from what's provided (or explicitly say when it can't).
async function askClaude(question, context) {
const response = 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,
system:
"Answer the user's question using only the provided context. If the context doesn't contain the answer, say so explicitly.",
messages: [
{
role: "user",
content: `Context:\n${context}\n\nQuestion: ${question}`,
},
],
}),
});
const data = await response.json();
return data.content[0].text;
}
This is the full loop: retrieveContext() pulls relevant chunks from Pinecone, then askClaude() sends them to the model. Wiring the generation step through SubToAPI gives you a standard application API key, request logging, and usage metadata on top of your existing Claude access, which is useful once you're running retrieval queries at any real volume and need to track cost per request or per team.
Handling context window and token budgets
Even with retrieval narrowing things down, you still need to budget tokens carefully:
- Cap total context size — sum the token length of retrieved chunks before sending; truncate or re-rank if you're over budget.
- Rerank when precision matters — Pinecone's top-k by cosine similarity is a good first pass, but a lightweight reranker (or asking Claude to score relevance) improves answer quality when chunks are noisy.
- Stream for long answers — if your RAG answers tend to be long, streaming responses improves perceived latency; see streaming docs if you're building this through SubToAPI.
- Use tool calling for dynamic retrieval — instead of always retrieving upfront, you can let Claude decide when to query Pinecone mid-conversation using tool use, which is useful for multi-turn RAG where the first retrieval isn't always enough.
Production considerations
A few things that matter once this moves past a prototype:
- Metadata filtering is cheaper than semantic filtering — use Pinecone namespaces or filters to scope retrieval by tenant, document type, or permission level before similarity search runs.
- Re-embed on document updates, not just on creation — stale vectors are a common source of RAG answering from outdated content.
- Log retrieved chunks alongside Claude's answer so you can debug bad responses by checking whether retrieval or generation failed.
- Set a confidence fallback — if similarity scores for all top-k matches are low, it's often better to tell the user no relevant document was found than to let Claude guess.
If you're just getting the generation half of this working, the quickstart covers setting up a key and making your first request; pricing has details on the Solo, Team, and Scale plans if you're deciding how to structure API access across a team building this.
FAQ
Does Claude have a built-in vector database? No. Claude handles text generation and reasoning; vector storage and similarity search require a separate system like Pinecone, Weaviate, or pgvector.
What embedding model should I use with Claude and Pinecone? Anthropic doesn't provide an embeddings API, so pick one separately — Voyage AI is commonly used alongside Claude, and OpenAI's embedding models also work fine with Pinecone.
How many chunks should I retrieve per query? Five to eight chunks is a reasonable default. Tune based on your chunk size and Claude's context window — more isn't always better if it dilutes relevance.