Build a chatbot with GPT API using retrieval-augmented generation. Chunk a large text file into 500-token segments with overlap, generate embeddings, store in a local FAISS index, and retrieve top-3 chunks to inject into the system prompt as context.
Assistant
Finalizing retrieval-augmented chatbot plan
The design chooses "text-embedding-3-small" with 1536 embedding dimension, chunking text into 500-token segments with 50-token overlap, storing embeddings in a FAISS index in memory, and retrieving top-3 chunks to inject as context in the system prompt for chat completions via the new OpenAI client. The planned script balances clear modular functions and concise, policy-compliant usage without exposing keys or disclaimers.
Below is a minimal end-to-end example (Python) that:
Reads a large text file.
Splits it into 500-token chunks with overlap.
Embeds each chunk with the OpenAI embeddings API.
Builds a local FAISS index.
Retrieves the top-3 most relevant chunks for a user query.
Injects those chunks into the system prompt and calls GPT for the final answer.
You’ll need:
pip install openai faiss-cpu tiktoken
export OPENAI_API_KEY="your_api_key_here"
python
import os
import faiss
import tiktoken
from openai import OpenAI
# --------------------------
# Configuration
# --------------------------
EMBEDDING_MODEL = "text-embedding-3-small" # 1536 dimensions as of writing
CHUNK_SIZE = 500
CHUNK_OVERLAP = 50
TOP_K = 3
client = OpenAI()
# --------------------------
# Helpers for tokenization and chunking
# --------------------------
def chunk_text_by_tokens(text, chunk_size=500, overlap=50, model="gpt-4o-mini"):
"""
Splits text into chunks of length `chunk_size` tokens with `overlap` tokens.
Returns list of chunk strings.
"""
enc = tiktoken.encoding_for_model(model)
tokens = enc.encode(text)
chunks = []
start = 0
while start < len(tokens):
end = start + chunk_size
chunk_tokens = tokens[start:end]
chunk_text = enc.decode(chunk_tokens)
chunks.append(chunk_text)
if end >= len(tokens):
break
start += chunk_size - overlap
return chunks
def load_text(path):
with open(path, "r", encoding="utf-8") as f:
return f.read()
# --------------------------
# Embeddings and FAISS index
# --------------------------
def embed_texts(text_list, model=EMBEDDING_MODEL):
"""
Returns list of embedding vectors for each text in `text_list`.
"""
embeddings = []
for text in text_list:
emb = client.embeddings.create(
model=model,
input=text
).data[0].embedding
embeddings.append(emb)
return embeddings
def build_faiss_index(embeddings):
"""
Builds a FAISS index for L2 similarity. Returns the index.
"""
dim = len(embeddings[0])
index = faiss.IndexFlatL2(dim)
index.add(np.array(embeddings).astype("float32"))
return index
# --------------------------
# Retrieval
# --------------------------
def retrieve_top_chunks(query, index, chunks, k=TOP_K, model=EMBEDDING_MODEL):
"""
Embeds the query, searches FAISS, returns top-k chunk texts.
"""
query_emb = client.embeddings.create(
model=model,
input=query
).data[0].embedding
# Search
D, I = index.search(np.array([query_emb]).astype("float32"), k)
results = [chunks[i] for i in I[0]]
return results
# --------------------------
# Build prompt and ask GPT
# --------------------------
def build_system_prompt(context_chunks):
"""
Combine retrieved chunks into a system message for GPT.
"""
joined = "\n\n".join(context_chunks)
system_prompt = (
"You are a helpful assistant. Use the following context "
"to answer the user's question. If the answer isn't in the context, "
"just say you don't know.\n\n"
f"CONTEXT:\n{joined}"
)
return system_prompt
def ask(question, index, chunks, model="gpt-4o-mini"):
top_chunks = retrieve_top_chunks(question, index, chunks, k=TOP_K)
system_prompt = build_system_prompt(top_chunks)
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": question},
]
completion = client.chat.completions.create(
model=model,
messages=messages,
temperature=0
)
return completion.choices[0].message["content"]
# --------------------------
# Main flow
# --------------------------
if __name__ == "__main__":
import numpy as np
# 1) Load your large text file
# Replace "large_file.txt" with your file path
text = load_text("large_file.txt")
# 2) Chunk the text
chunks = chunk_text_by_tokens(text, CHUNK_SIZE, CHUNK_OVERLAP)
# 3) Embed all chunks
embeddings = embed_texts(chunks)
# 4) Build FAISS index
index = build_faiss_index(embeddings)
# 5) Simple REPL to ask questions
while True:
user_q = input("Ask a question (or 'quit'): ").strip()
if user_q.lower() in {"quit", "exit"}:
break
answer = ask(user_q, index, chunks)
print("\nAnswer:", answer, "\n")
How it works:
The script splits your file into overlapping ~500-token blocks.
Each block is embedded and stored in a FAISS index.
When you query, it embeds your question, retrieves the top 3 most similar blocks, injects them into the system prompt, and calls GPT to generate the final answer.