Dev tools
How to Build a Chatbot With Your Own Data
Learn how to build a chatbot that answers from your own documents: no-code options, a step-by-step Python guide, and tips for testing and safety.
Want an AI assistant that knows your products, policies, or notes, instead of giving generic answers? You can build a chatbot that answers from your own documents in an afternoon, with or without code.
This guide covers the three main ways to do it, how to prepare your data, a complete step-by-step Python example, and how to test and launch it safely.
Can You Really Train ChatGPT on Your Own Data?
Many people search for how to train ChatGPT on your own data. In practice, most "chatbots trained on your data" don't involve training at all.
Instead, they use a technique called retrieval-augmented generation (RAG). When someone asks a question, the system searches your documents for the most relevant passages and hands them to the AI along with the question. The AI then writes an answer based on those passages.
This approach has big advantages over actually retraining a model:
- It's fast and cheap. No training runs, no special hardware.
- It stays up to date. Change a document, and the chatbot's answers change too.
- It can show sources. Answers can point to the exact document they came from.
- It reduces made-up answers, because the AI works from real text rather than memory.
Real training, called fine-tuning, is better for changing a model's style or behavior than for teaching it facts. For a chatbot that knows your content, RAG is almost always the right starting point. Our guide to what RAG is explains the idea in depth.
Three Ways to Build a Chatbot With Your Own Data
There are three main routes, from easiest to most flexible.
Option 1: Use features inside AI apps (no code, for yourself or your team)
The major AI apps let you upload files and chat with them:
- ChatGPT lets you create custom GPTs with your own instructions and uploaded files.
- Claude offers Projects, where you add documents to a project's knowledge and chat with them.
- Google NotebookLM is built around asking questions about sources you upload.
This is the fastest way to get started, and great for personal use or a small team. The limits: it lives inside that app, you have less control over behavior, and it's not something you can embed on your own website.
Option 2: Use a no-code chatbot builder (for customers)
A no-code chatbot builder is a service where you upload documents or point it at your website, adjust a few settings, and get a chat widget to embed. Many customer-support platforms now include this as a feature.
This suits businesses that want a chatbot for your website without hiring developers. When comparing tools, check how they handle data privacy, whether answers show sources, how easily you can update content, and whether a human can take over.
Option 3: Build a custom AI chatbot (with code)
Building your own custom AI chatbot gives you full control: which AI model to use, where your data lives, how answers look, and how it connects to your other systems. It takes some programming, but the core is surprisingly small, as the example below shows.
Choose this route if you need tight privacy control, custom behavior, integration with your own app, or you simply want to understand how it works.
Before You Start: Prepare Your Data
Whichever route you choose, the quality of your chatbot depends on the quality of your documents.
Pick the right sources
Start with the content people actually ask about: FAQs, help articles, product guides, policies, and price lists. A focused set of good documents beats a huge pile of everything.
Clean it up
- Remove outdated versions, so the bot doesn't quote old policies.
- Fix contradictions between documents.
- Convert messy files, like scanned PDFs or slides, into clean text where you can.
- Use clear headings, so the text splits into meaningful chunks.
Remove sensitive information
Don't include passwords, personal data, internal-only notes, or anything you wouldn't want a user to see. Assume anything in the documents could appear in an answer.
Plan for updates
Decide who keeps the content current, and how often. A chatbot with stale information is worse than no chatbot.
How a Custom AI Chatbot Works Under the Hood
A RAG chatbot has two phases.
Preparation (done once, then whenever documents change):
- Split your documents into small chunks of a few paragraphs.
- Turn each chunk into an embedding, a list of numbers that captures its meaning.
- Store the chunks and embeddings in a vector database.
Answering (every time someone asks):
- Turn the question into an embedding.
- Find the chunks closest in meaning to the question.
- Send those chunks and the question to an AI model, with instructions to answer only from them.
- Return the answer to the user, ideally with its sources.
Why not just paste all your documents into the AI every time? Models can only read a limited amount of text per request, and sending more costs more and can make answers less focused. Our guide to what a context window is explains that limit, and why answers can get worse even before you reach it.
How to Build a Chatbot in Python, Step by Step
Here's a complete, minimal chatbot that answers questions from your own text files. It uses Chroma, a free open-source vector database, and Claude through Anthropic's API. The same structure works with other AI providers.
Step 1: Set up
You'll need Python 3.10 or newer and an Anthropic API key. Install the two libraries:
pip install chromadb anthropicThen set your API key as an environment variable named ANTHROPIC_API_KEY, so it never appears in your code.
Step 2: Add your documents
Create a folder called docs next to your script and put your content in it as .txt files, for example refunds.txt, shipping.txt, and faq.txt.
Step 3: Write the chatbot
Save this as chatbot.py:
from pathlib import Path
import chromadb
from anthropic import Anthropic
# --- Preparation: load, chunk, and store your documents ---
def chunk_text(text, size=800, overlap=100):
"""Split text into overlapping chunks of about `size` characters."""
chunks = []
start = 0
while start < len(text):
chunks.append(text[start:start + size])
start += size - overlap
return chunks
db = chromadb.PersistentClient(path="chatbot_db")
collection = db.get_or_create_collection("my_docs")
for file in Path("docs").glob("*.txt"):
chunks = chunk_text(file.read_text(encoding="utf-8"))
if chunks:
collection.upsert(
documents=chunks,
ids=[f"{file.stem}-{i}" for i in range(len(chunks))],
metadatas=[{"source": file.name} for _ in chunks],
)
# --- Answering: retrieve relevant chunks and ask the AI ---
client = Anthropic() # reads ANTHROPIC_API_KEY from the environment
SYSTEM_PROMPT = """You are a friendly support assistant for our company.
Answer only using the sources provided in the user's message.
If the answer is not in the sources, say you don't know and suggest
contacting support. Keep answers short and mention which source file
you used."""
def answer(question):
results = collection.query(query_texts=[question], n_results=4)
chunks = results["documents"][0]
sources = results["metadatas"][0]
context = "\n\n".join(
f"<source file=\"{meta['source']}\">\n{chunk}\n</source>"
for chunk, meta in zip(chunks, sources)
)
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system=SYSTEM_PROMPT,
messages=[{
"role": "user",
"content": f"Sources:\n{context}\n\nQuestion: {question}",
}],
)
return message.content[0].text
# --- A simple chat loop ---
while True:
question = input("\nYou: ")
if question.strip().lower() in {"quit", "exit"}:
break
print("\nBot:", answer(question))Step 4: Run it
python chatbot.pyAsk a question about your documents, and type quit to stop. On the first run, Chroma downloads a small embedding model and indexes your files. After that, the index is saved in the chatbot_db folder.
What each part does
- `chunk_text` splits each document into overlapping pieces, so ideas aren't cut off at chunk edges.
- Chroma turns each chunk into an embedding automatically and stores it with the file name as metadata.
- `collection.query` finds the four chunks most similar in meaning to the question.
- The system prompt tells the AI to stick to those sources and admit when it doesn't know.
- The source tags let the AI tell users which document an answer came from.
Model names change as new versions are released, so check your AI provider's documentation for the latest model to use.
Write a Good System Prompt
The system prompt shapes how your chatbot behaves. A few rules make a big difference:
- Stay grounded. "Answer only from the provided sources."
- Allow "I don't know." "If the answer isn't in the sources, say so." This is your best defense against made-up answers.
- Set the scope. "Only answer questions about our products and policies. Politely decline anything else."
- Define the tone. Friendly, formal, brief, or detailed, whatever fits your brand.
- Offer a next step. Tell it how to direct people to a human, like a support email or contact page.
Test Before You Launch
Never put a chatbot in front of customers without testing it. Write a list of test questions, including:
- Common questions you know the answers to.
- Questions phrased differently, with slang, typos, or different wording.
- Questions with no answer in your documents. The bot should say it doesn't know.
- False premises, like asking about a product you don't sell.
- Off-topic requests, like asking it to write a poem or give legal advice.
- Attempts to break the rules, like "ignore your instructions."
When an answer is wrong, find the cause. Usually the right document chunk wasn't retrieved, the document itself is unclear, or the system prompt needs a stronger rule. Fix the source, not just the symptom, and re-run your test list after every change.
Adding a Chatbot to Your Website
To turn the script into a chatbot for your website, you typically:
- Wrap the `answer` function in a small web API using a framework like Flask or FastAPI.
- Add a chat widget to your site that sends questions to that API and shows the replies.
- Keep your API key on the server. Never put it in your website's JavaScript, where anyone could copy it.
- Add basic protections, like rate limits to prevent abuse and logging to review conversations.
If that sounds like more work than you want, a no-code chatbot builder handles all of this for you.
Keep It Private and Safe
- Know where your data goes. With a cloud AI provider, your documents and questions are sent to their servers. Check their data-use and retention policies.
- Go fully local if needed. For highly sensitive data, you can run the AI model on your own hardware so nothing leaves your machine. Our guide to running an LLM locally shows how to set one up with Ollama, step by step.
- Separate users' data. If different customers should see different documents, filter by metadata so one user's content never appears in another's answers.
- Be clear it's a bot. Tell users they're talking to an AI, and give them a way to reach a person.
- Remember you're responsible. Businesses have been held accountable for what their chatbots tell customers, so review answers regularly.
FAQ
Can I build a chatbot for free?
You can build and test one for very little. Chroma and other open-source tools are free, and you can run open AI models locally at no cost. Cloud AI APIs charge based on usage, though light testing is usually inexpensive. Many no-code builders also offer free plans with limits.
Do I need to know how to code to build a chatbot?
No. AI apps like ChatGPT, Claude, and NotebookLM let you chat with your files without code. A no-code chatbot builder can put a chatbot on your website. Coding is only needed if you want full control or a custom integration.
How much data do I need to build a chatbot?
Less than you might think. Even a handful of well-written documents, like an FAQ and a few policy pages, can power a useful chatbot. Quality and clarity matter more than volume.
Is it safe to give my data to an AI chatbot?
It depends on the provider and your settings. Read the provider's data policies, avoid uploading sensitive personal information, and consider running a model locally for confidential material.
What's the difference between RAG and fine-tuning for chatbots?
RAG looks up relevant passages from your documents each time someone asks a question, so it's best for factual knowledge that changes. Fine-tuning retrains the model on examples, so it's better for changing style or behavior. Most chatbots built on your own data use RAG.