To automate customer support with AI, you build a support agent that answers customers from your own help articles. For each question, a RAG pipeline finds the right part of your help center, and a language model writes the answer from it in your company's voice.
Below I go through that plan step by step, then build a small working version in Python that runs free on your own machine with a local open-source model, plus a ticket triage script for the extras. The video above covers the same plan.
What a support agent does that a help center doesn't
Salesforce has a good example of this on its site. You ask its agent "How do I reset my password?" in plain English, and it gives you the steps to reset your password, pulled from Salesforce's own help article, so you never have to open the article yourself.
Compare that to a normal help center like Mailchimp's. Say I'm a new user and I want to import contacts. I open the article, read through the whole thing, maybe watch the videos in it, and then I know how to do it. Most of these help centers are good, to be fair. But it's a lot of work for the customer, when they could ask a question and get the three steps they need.
The agent is what replaces most of the time your team (or you, if it's just you) spends answering the same support questions.
Step 1: build a knowledge base
The agent can only answer from what you give it, so you need a knowledge base first: a set of articles that explain your product's common problems and how to solve them.
You most likely have this already. Most companies have docs or a support center. If you don't, write it now. You can use AI to help write the articles, as long as everything in them is accurate, because the agent will repeat whatever they say to your customers.
Keep each article focused on one problem, with a heading per situation. That makes the next steps easier, because the agent searches the knowledge base section by section.
Step 2: make the agent sound like your company
This one isn't technical. It comes down to the system prompt. You want the agent to sound like someone on your support team, because people don't like talking to robotic chatbots.
The details depend on your company, but a few rules apply to everyone:
- No emojis. ChatGPT especially loves them.
- No em dashes. Every LLM sprays them everywhere by default, and they've become a giveaway that you're reading AI text.
- No common LLM phrases like "You're absolutely right" or "It's not X, it's Y". Everyone has seen so much LLM writing that these read as low quality now.
- No closing pleasantries like "Let me know if there's anything else I can help with." The customer will ask if they need more.
I wrote a long, detailed prompt for building a whole support agent with an LLM's help, aimed at non-technical people. It's on GitHub as a gist. Paste it into Claude or ChatGPT and it walks you through the setup. The demo below has a much shorter system prompt with the voice rules built in.
Step 3: build a RAG pipeline
RAG stands for retrieval-augmented generation. It sounds harder than it is:
- Retrieval: when a question comes in, find the parts of your knowledge base that are about it.
- Augmented: give those parts to the model along with the question, so it knows things about your specific product.
- Generation: the model writes the answer the customer reads.
To find the right parts, you split your articles into chunks, turn each chunk into an embedding (a list of numbers that captures its meaning), and store those. When a question comes in, you embed it the same way and pick the chunks whose embeddings are closest. I explain embeddings and cosine similarity properly in how semantic search works. For a big help center you'd keep the embeddings in a vector database like pgvector or Chroma. For a few dozen articles, a NumPy array is enough, and that's what the demo uses.
Why support is cheap to automate
Support doesn't need a frontier model. The answer is already sitting in the article the pipeline retrieved, so the model only has to read it and rewrite it for one customer's question. Small open-source models like Gemma 4 or Qwen 3.6 handle that fine, and you can run them on your own hardware. Even through an API, millions of tokens on models that size cost a few dollars.
The demo goes further and uses Qwen3 1.7B, which runs on a laptop CPU. I go into picking the cheapest model that still does the job in this article on choosing an LLM.
Build a support agent in Python
The demo is a help center for a made-up invoicing app called Tallybook: four short articles plus two scripts, one to index them and one to answer questions. It uses Ollama to run the model locally, so it costs nothing to run. Install Ollama from its site, then pull the model and install the Python packages:
ollama pull qwen3:1.7b
pip install --extra-index-url https://download.pytorch.org/whl/cpu torch sentence-transformers numpy requests
The extra index gets the CPU-only build of PyTorch, which is much smaller than the default. I tested this with Python 3.13, sentence-transformers 6.3 and Ollama 0.40 on a 4-core machine.
support-agent/
├── kb/
│ ├── change-plan.md
│ ├── export-invoices.md
│ ├── reset-password.md
│ └── team-members.md
├── ingest.py
├── ask.py
├── triage.py
└── tickets.json
The knowledge base
Each article is a Markdown file with one # title and a ## heading per situation. Here's kb/reset-password.md:
# How to reset your password
## Reset it from the login page
1. Go to the login page and click "Forgot password?".
2. Enter the email address on your account.
3. Open the email from Tallybook and click the reset link. The link expires after 30 minutes.
4. Choose a new password with at least 10 characters.
## If the reset email never arrives
Check your spam folder first. If it's not there, make sure you typed the email address you signed up with. Accounts created with "Sign in with Google" don't have a password, so no reset email is sent. Sign in with Google instead.
The other three articles follow the same format, one about plans and refunds and the others about invoice exports and team members.
Index the articles: ingest.py
import json
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
def chunk_article(path):
"""Split a help article into one chunk per ## section."""
lines = path.read_text().splitlines()
title = lines[0].removeprefix("# ")
sections = []
for line in lines[1:]:
if line.startswith("## "):
sections.append([line.removeprefix("## "), []])
elif sections:
sections[-1][1].append(line)
return [
{
"source": f"{title} > {heading}",
"file": path.name,
"text": f"{title} > {heading}\n" + "\n".join(body).strip(),
}
for heading, body in sections
]
chunks = [c for path in sorted(Path("kb").glob("*.md")) for c in chunk_article(path)]
vectors = embedder.encode([c["text"] for c in chunks], normalize_embeddings=True)
Path("chunks.json").write_text(json.dumps(chunks, indent=2))
np.save("embeddings.npy", vectors)
print(f"Indexed {len(chunks)} chunks from {len(set(c['file'] for c in chunks))} articles")
Each ## section becomes one chunk, with the article title and heading put in front of the text. That way a chunk like "If the reset email never arrives" still says it's about password resets. all-MiniLM-L6-v2 is a small, free embedding model that runs fine on a CPU. normalize_embeddings=True scales every vector to length 1, so later a plain dot product gives the cosine similarity. Run it once, and again whenever you change an article:
Indexed 9 chunks from 4 articles
Answer questions: ask.py
import json
import sys
import numpy as np
import requests
from sentence_transformers import SentenceTransformer
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3:1.7b"
MIN_SCORE = 0.3 # below this, the help center has nothing relevant
SYSTEM_PROMPT = """You are a support agent at Tallybook, an invoicing app.
Answer the customer using only the help articles you are given.
For how-to questions, give the steps in order as a numbered list.
For yes/no questions, answer in one or two sentences.
Write like a person on the support team: plain and friendly, no emojis, no em dashes,
no "Great question" or "You're absolutely right", and no closing pleasantries.
If the articles don't answer the question, reply with exactly: ESCALATE"""
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
chunks = json.load(open("chunks.json"))
vectors = np.load("embeddings.npy")
def retrieve(question, k=3):
"""Return the k chunks closest in meaning to the question, with their scores."""
q = embedder.encode(question, normalize_embeddings=True)
scores = vectors @ q # cosine similarity, since every vector is normalized
top = np.argsort(scores)[::-1][:k]
return [(float(scores[i]), chunks[i]) for i in top]
def answer(question):
hits = retrieve(question)
if hits[0][0] < MIN_SCORE:
return "ESCALATE", hits
context = "\n\n".join(chunk["text"] for _, chunk in hits)
response = requests.post(
OLLAMA_URL,
json={
"model": MODEL,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"Help articles:\n\n{context}\n\nCustomer: {question}"},
],
"stream": False,
"think": False,
"options": {"temperature": 0.2},
},
timeout=300,
)
response.raise_for_status()
return response.json()["message"]["content"].strip(), hits
if __name__ == "__main__":
question = " ".join(sys.argv[1:])
reply, hits = answer(question)
for score, chunk in hits:
print(f"[{score:.2f}] {chunk['source']}")
print()
if reply.upper().strip(".") == "ESCALATE":
print("No answer in the help center. Handing this one to a human.")
else:
print(reply)
retrieve() embeds the question with the same model and scores it against every chunk. answer() sends the top three chunks and the question to the model through Ollama's chat API. "think": False turns off Qwen3's thinking mode, which a support answer doesn't need and which makes it far slower. The low temperature keeps the model close to the article's wording.
The system prompt has the voice rules from step 2, plus the two that matter most for support: answer only from the articles, and say ESCALATE when they don't cover the question. The final check accepts "Escalate" too, because the model sometimes writes it that way, and you don't want a customer to see that word.
Run it
Start Ollama if it isn't running already (ollama serve), index the articles, then ask a question:
python ingest.py
python ask.py "How do I reset my password?"
[0.66] How to reset your password > Reset it from the login page
[0.56] How to reset your password > If the reset email never arrives
[0.23] Changing or canceling your plan > Cancel your subscription
1. Go to the login page and click "Forgot password?".
2. Enter the email address on your account.
3. Open the email from Tallybook and click the reset link. The link expires after 30 minutes.
4. Choose a new password with at least 10 characters.
The lines in brackets are the retrieved chunks and their scores, so you can see which article the answer came from. A yes/no question gets a short answer that names the role from the article:
[0.51] Adding team members > Roles
[0.42] Exporting your invoices > Export to CSV
[0.38] Exporting your invoices > Export to PDF
Yes. Members can create and send invoices but can't see billing or delete clients.
And a question the help center doesn't cover goes to a person:
[0.26] Exporting your invoices > Export to PDF
[0.26] Adding team members > Roles
[0.22] Exporting your invoices > Export to CSV
No answer in the help center. Handing this one to a human.
Each answer took about 8 seconds on a 4-core CPU, and about half of that was Python loading PyTorch and the embedding model. In a real deployment you load those once when the server starts, so only the model call (around 3.5 seconds here) is left.
Handing questions to a human
The agent has two ways to give up. MIN_SCORE catches questions nowhere near anything in the help center, before the model is even called. The model's own ESCALATE catches the rest.
I measured where to set the threshold. The five questions the articles answer scored between 0.51 and 0.79, and the three they don't scored 0.34 ("My invoice PDF has the wrong logo"), 0.26 (QuickBooks) and about 0 (the weather). So far so good, but with more test questions the ranges overlapped: "upgrade to pro" is answered by an article and only scored 0.32, while "How do I delete my account?" isn't covered and scored 0.41.
So the threshold can't be the real gate. I set it low, at 0.3, to filter obvious junk, and left the decision to the model. With the threshold turned off entirely, Qwen3 1.7B escalated all six uncovered questions I tried and still answered "upgrade to pro" correctly from the right article. When you build your own, run your real tickets through retrieve() and look at the scores before you pick a number.
Bonus: triage your support tickets with AI
Once you have a model running, you can point it at your support tickets too. Sorting tickets into categories makes them easier to review, and a satisfaction score per ticket tells you how your support is landing. Read enough tickets this way and the recurring problems show up too. If a hundred tickets point at the same thing, that's a problem in your product you should fix.
tickets.json holds six sample tickets:
[
"I was charged twice this month. Second charge on the 3rd. I want the extra one refunded.",
"Can't log in. I click forgot password but the email never comes. Tried three times today.",
"Thanks, the CSV export worked perfectly, that's exactly what my accountant needed.",
"Reset email still hasn't arrived after an hour. This is the second day I can't get into my account and I have invoices due.",
"How do I add my bookkeeper so she can send invoices but not see our billing?",
"Your app charged my card after I canceled. Really annoyed, please fix this."
]
triage.py asks the model to fill in a JSON schema for each one:
import json
from collections import Counter
import requests
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3:1.7b"
SCHEMA = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["account", "billing", "how-to", "bug", "feedback"]},
"satisfaction": {"type": "integer", "minimum": 0, "maximum": 10},
"problem": {"type": "string"},
},
"required": ["category", "satisfaction", "problem"],
}
PROMPT = """Read this support ticket for Tallybook, an invoicing app.
category: what the ticket is about.
satisfaction: how happy the customer sounds, 0 (furious) to 10 (delighted).
problem: the underlying problem in five words or fewer, or "none".
Ticket: {ticket}"""
def triage(ticket):
response = requests.post(
OLLAMA_URL,
json={
"model": MODEL,
"messages": [{"role": "user", "content": PROMPT.format(ticket=ticket)}],
"format": SCHEMA,
"stream": False,
"think": False,
"options": {"temperature": 0},
},
timeout=300,
)
response.raise_for_status()
return json.loads(response.json()["message"]["content"])
results = [triage(ticket) for ticket in json.load(open("tickets.json"))]
for r in results:
print(f"{r['category']:<9} {r['satisfaction']:>2}/10 {r['problem']}")
print("\nTickets per category:", dict(Counter(r["category"] for r in results)))
Passing a schema as format makes Ollama constrain the output to valid JSON in that shape, and the enum keeps the categories to a fixed list you can count. Run python triage.py:
billing 8/10 duplicate charge
how-to 7/10 forgot password
feedback 10/10 CSV export worked perfectly
account 5/10 email not arriving
how-to 8/10 how to add bookkeeper with billing restrictions
billing 3/10 card charged after cancellation
Tickets per category: {'billing': 2, 'how-to': 2, 'feedback': 1, 'account': 1}
The six tickets took about 9 seconds. The categories are mostly right (I'd file the second ticket under account), and the problem summaries are good enough to group. Counting those over a few hundred tickets is how you find the recurring problems.
The satisfaction scores are where the 1.7B model falls short. A customer who was charged twice got 8 out of 10, and someone locked out for two days with invoices due got 5. Prompt changes didn't fix it. Switching the model line to MODEL = "qwen3:4b" did: it scored the six tickets 3, 2, 10, 2, 7 and 2, which matches how those customers sound. It took about 21 seconds instead of 9, and it filed the CSV thank-you under account. So use the bigger model if you want satisfaction scores, and treat them as a rough signal either way.
Putting it on your website
Once the pipeline gives good answers, deploying it is the easy part. Load the embedding model and the index once in a small web server, call answer() from a chat endpoint, and put a chat widget on your site that posts to it. Anything that comes back as ESCALATE should open a ticket for your team, with the customer's question attached, so nothing gets dropped.
The hard part is the knowledge base. If your articles are wrong or missing, the agent either escalates everything or confidently repeats the mistake. Get the articles right first. And you don't need an expensive model for any of this. Support is one of the cheapest things you can automate, because the answers are already written down.

