AI and machine learning · Intermediate · 24 min
Build semantic search over an FAQ with embeddings in Python
By Padding · Updated 18 Nov 2026
Python 3.15 · sentence-transformers 6.3.0 · PyTorch 2.15.0 (CPU) · NumPy 2.5.5 · rank-bm25 0.2.2
You will index 150 FAQ answers with a local embedding model, search them with a matrix product, reject questions the FAQ cannot answer, and measure the result against a BM25 keyword baseline and a hybrid of the two on 20 labelled queries.
On this page
A help centre search box fails in a familiar way. A customer types "my phone was stolen", the FAQ entry is called "Someone stole my phone", and a keyword search treats "stolen" and "stole" as unrelated words, so the right entry drops out of the results. Semantic search fixes much of that: an embedding model turns each FAQ entry and each question into a vector, and entries whose meaning is close to the question come out on top, whatever words they use.
In this tutorial you build that search for a made-up mobile-money service, Tumba Wallet, with 150 FAQ entries. Everything stays in memory: the vectors live in a NumPy file, a search is one matrix product, and there is no database or hosted API. Then you do the part that is often skipped. You label 20 real-sounding questions with the right answers and measure how often each approach puts the right entry in its top three: embeddings, a classic BM25 keyword search, and a hybrid of the two.
The embedding model is all-MiniLM-L6-v2, a small English model under the Apache 2.0 licence that runs comfortably on a laptop CPU. If you have not used embeddings before, read turn text into embeddings with sentence-transformers first; this tutorial assumes you know what cosine similarity measures.
Step 1 · Create the project and install the libraries
Create a project folder and a virtual environment, so nothing is installed into your system Python:
mkdir -p ~/faq-search-demo
cd ~/faq-search-demo
python3 -m venv .venv
source .venv/bin/activateInstall PyTorch first, from PyTorch's CPU-only package index. Without --index-url, pip on Linux fetches the default build with GPU libraries, which is several gigabytes larger and no faster on a machine without a supported GPU. On macOS the same command installs the standard Apple silicon build:
pip install torch==2.15.0 --index-url https://download.pytorch.org/whl/cpuThen install sentence-transformers, NumPy and rank-bm25. Exact versions mean a later release cannot change your scores without you noticing:
pip install sentence-transformers==6.3.0 numpy==2.5.5 rank-bm25==0.2.2On a prepaid data plan, note the size first: the PyTorch wheel is around 200 MB, and the model you download in a later step is about 90 MB. Both are downloaded once. After that, everything in this tutorial runs offline.
Check it worked
python -c "import torch, sentence_transformers, numpy, rank_bm25; print(torch.__version__, sentence_transformers.__version__, numpy.__version__)"On Linux the output is 2.15.0+cpu 6.3.0 2.5.5. On macOS the first value is 2.15.0. If you open a new terminal later, run cd ~/faq-search-demo and source .venv/bin/activate again before the other commands.
Step 2 · Add the FAQ data
Each FAQ entry is one line with three fields separated by |: a short id, the question as the help centre wrote it, and the answer. The id prefix says which area it belongs to (pin, send, agent, bill and so on), which makes search results easy to read. Create faq.txt:
cat > faq.txt <<'TXT'
acct-01|How do I open a Tumba Wallet account?|Dial *345# or install the app, choose Register, enter your phone number and full name, then set a four-digit PIN. The account is ready in about two minutes.
acct-02|Can I register without a smartphone?|Yes. Any phone that can dial *345# can register and use the wallet. The menu works on basic feature phones and needs no data bundle.
acct-03|What documents do I need to register?|A national ID card, voter card, passport or driving licence. Agents scan it when you register in person, and the app takes a photo of it.
acct-04|Can I have two wallets on one phone number?|No. Each phone number holds one wallet. To run a second wallet, register it on a different SIM card in your own name.
acct-05|How do I change the name on my account?|Visit an agent or service centre with your ID and the document that shows the new name, such as a marriage certificate. Name changes take up to three working days.
acct-06|How do I close my wallet?|Withdraw or send out your balance first, then call customer care or visit a service centre to close it. A closed wallet cannot be reopened on the same number.
acct-07|My SIM card was lost. Is my wallet gone?|No. Your money stays in the wallet. Replace the SIM at your network provider with the same number, then reset your PIN to use the wallet again.
acct-08|Can I open a wallet for my child?|Wallets are for people aged 18 and over. A parent can open a savings pocket in their own wallet and name it for a child.
acct-09|How do I update my date of birth?|Take your ID to an agent or service centre. The date on your wallet must match the ID, so we cannot change it over the phone.
acct-10|Why was my registration rejected?|Usually the photo of the ID was blurred or the name typed did not match the ID. Try again in good light, or register with an agent.
pin-01|I forgot my PIN. How do I reset it?|Dial *345#, choose My Account, then Reset PIN, and answer the security questions. If you cannot answer them, visit a service centre with your ID.
pin-02|How do I change my PIN?|In the app go to Settings, then Security, then Change PIN, or dial *345# and choose My Account. Enter the old PIN, then the new one twice.
pin-03|My wallet is locked after wrong PIN attempts|Three wrong PINs in a row lock the wallet for 24 hours. To unlock it sooner, call customer care from the registered number and verify your identity.
pin-04|Will customer care ever ask for my PIN?|Never. No staff member or agent needs your PIN. Anyone who asks for it is trying to steal from you, so hang up and report the number.
pin-05|Can I use fingerprint login in the app?|Yes, on phones with a fingerprint reader. Turn it on in Settings, then Security. You still need the PIN for large payments and new devices.
pin-06|Is it safe to let an agent type my PIN?|No. Always type the PIN yourself and cover the keypad. An agent never needs to touch your phone to complete a deposit or withdrawal.
pin-07|How do I set security questions?|Go to Settings, then Security, then Security questions. Pick three questions and answers you will remember, because they are needed to reset your PIN.
pin-08|What makes a strong PIN?|Avoid birthdays, repeated digits like 1111 and sequences like 1234. Do not use the same PIN as your bank card or phone lock screen.
pin-09|Can I log in to the app on a new phone?|Yes. Install the app, sign in with your number and PIN, then confirm with the one-time code we send by SMS. Your old phone is signed out.
pin-10|I did not receive the one-time code|Check that your phone has signal and that the number is correct. Wait two minutes before asking for a new code. Codes expire after five minutes.
send-01|How do I send money to another wallet?|Choose Send Money, enter the recipient's number or pick a contact, type the amount and confirm with your PIN. The money arrives within seconds.
send-02|I sent money to the wrong number|Call customer care straight away with the transaction ID. If the money has not been withdrawn, we can hold it and ask the receiver to approve a reversal.
send-03|Can I cancel a transfer after sending it?|A completed transfer cannot be cancelled from the app. Contact customer care at once and ask for a reversal, quoting the transaction ID.
send-04|How do I send money to someone on another network?|Choose Send Money, then Other Networks, pick the network and enter the number. Transfers to other networks carry a small extra fee.
send-05|Why did my transfer fail?|The usual reasons are not enough balance to cover the amount and the fee, a daily limit reached, or a wrong recipient number. The SMS gives the reason.
send-06|Can I schedule a payment for later?|Yes. In the app, choose Send Money, then Schedule, pick the date and how often to repeat it. Make sure the balance is there on the day.
send-07|How do I save a favourite recipient?|After a transfer, tap Save recipient, or open Contacts in the app and add the number with a name. Saved recipients appear first when you send.
send-08|Does the recipient need a Tumba Wallet account?|No. Someone without a wallet receives an SMS with a voucher code and can collect the cash at any agent with their ID within seven days.
send-09|How do I split a bill with friends?|Open Requests, choose Split, enter the total and add the friends. Each one receives a payment request for their share.
send-10|Is there a confirmation before money leaves my wallet?|Yes. Every transfer shows the recipient's registered name and the fee before you enter your PIN. Check the name before you confirm.
recv-01|How do I receive money?|Share your phone number with the sender. When the money arrives you get an SMS with the amount, the sender's name and the new balance.
recv-02|Someone says they sent money but I have nothing|Ask the sender for the transaction ID and check your statement in the app. Delays are rare; if it is missing after an hour, call customer care.
recv-03|How do I request money from someone?|Open Requests, choose New request, enter their number and the amount, and add a note. They receive a prompt to approve or decline.
recv-04|Can I receive money from abroad?|Yes. Partner remittance services send directly to your wallet number. The money arrives in local currency and the SMS shows the rate used.
recv-05|I received money I was not expecting|Do not send it back yourself, because this is a common scam. Call customer care with the transaction ID and we will check and reverse it if needed.
recv-06|Is there a limit on how much I can receive?|Yes. Your tier sets a maximum balance. A transfer that would take you above it is rejected and the sender is refunded.
recv-07|How do I share my QR code to get paid?|In the app, tap Receive to show your personal QR code. The payer scans it with their app and the amount comes straight to your wallet.
recv-08|Does receiving money cost anything?|No. Receiving from another Tumba wallet is free. Fees apply only when you send, withdraw or pay some bills.
recv-09|Can my employer pay my salary into the wallet?|Yes. Employers use the bulk payments service. Give them your registered number and name exactly as they appear on your ID.
recv-10|How long does a payment from a bank take to arrive?|Bank to wallet transfers usually arrive within minutes. Transfers sent outside banking hours can take until the next working day.
agent-01|How do I withdraw cash?|At an agent, choose Withdraw Cash, enter the agent number and the amount, and confirm with your PIN. Take the cash only after the agent receives the SMS.
agent-02|How do I deposit cash into my wallet?|Give the cash to any agent with your number. The agent sends it to your wallet and you both get an SMS. Count your change and check the SMS before leaving.
agent-03|Where can I find an agent near me?|Open Agents in the app to see a map of nearby agents, or dial *345# and choose Find Agent to get a list by area.
agent-04|The agent has no cash|Agents sometimes run short of cash at busy times. Try another agent nearby, or come back later. Report agents who regularly refuse withdrawals.
agent-05|An agent charged me extra|Agents must not charge more than the fee shown in the app. Report it to customer care with the agent number, and we will refund the extra.
agent-06|Can I withdraw at a bank ATM?|Yes, at partner ATMs. Choose Cardless Withdrawal in the app, get a one-time code and enter it with the amount at the ATM within 30 minutes.
agent-07|How do I become an agent?|Apply on our website with a registered business, a shop front and a float to start with. A field officer visits before your application is approved.
agent-08|The agent deposited to the wrong number|Ask the agent to call customer care straight away with the transaction ID. Do not leave until the agent has reported it.
agent-09|Can someone withdraw for me?|No. Withdrawals need your PIN and, above a set amount, your ID. Send the money to the other person's wallet so they can withdraw it themselves.
agent-10|What hours are agents open?|Each agent sets their own hours. Most are open from early morning to evening, and the map in the app shows opening hours where the agent has added them.
air-01|How do I buy airtime?|Choose Airtime, then pick your number or another number, enter the amount and confirm with your PIN. Airtime arrives instantly and carries no fee.
air-02|Can I buy data bundles with my wallet?|Yes. Choose Airtime, then Data Bundles, pick the network and the bundle size, and confirm. The bundle is active as soon as the SMS arrives.
air-03|I bought airtime but did not receive it|Wait ten minutes, then check the number you entered on your statement. If the airtime is still missing, call customer care with the transaction ID.
air-04|Can I set up automatic airtime top-up?|Yes. In the app open Airtime, then Auto top-up, choose a low-balance amount and a top-up value. We top up when your airtime drops below it.
air-05|Can I buy airtime for any network?|You can buy airtime and bundles for all major networks in the country, not only the network your SIM is on.
air-06|Do I get a discount when buying airtime?|Airtime bought through the wallet earns a small bonus on some networks. The current bonus is shown on the Airtime screen.
air-07|I bought airtime for the wrong number|Airtime cannot be reversed once it reaches a phone, because the network has already credited it. Ask the owner of that number to send it back.
air-08|Can I buy a monthly unlimited bundle?|Bundles depend on what each network offers. All the bundles a network sells appear under Data Bundles, including weekly and monthly ones.
air-09|Can I use the wallet when I have no airtime?|Yes. The *345# menu is free to dial and works without airtime or data. The app needs a data connection or Wi-Fi.
air-10|How do I check my data bundle balance?|Data balances are kept by your network, not by the wallet. Dial your network's balance code or check its own app.
bill-01|How do I pay my electricity bill?|Choose Pay Bills, then Electricity, pick your provider and enter the meter number and amount. A prepaid token arrives by SMS within a minute.
bill-02|I paid for electricity but did not get the token|Tokens are usually sent within a minute. If it is late, open the transaction in the app and tap Resend token, or call customer care.
bill-03|Can I pay school fees with my wallet?|Yes, for schools registered with us. Choose Pay Bills, then School Fees, search for the school and enter the student number.
bill-04|How do I pay for TV subscription?|Choose Pay Bills, then TV, pick the provider and enter the smart card number. Your subscription is renewed within minutes.
bill-05|Can I save my meter number?|Yes. After a bill payment, tap Save biller. Saved billers appear at the top of Pay Bills with the account number filled in.
bill-06|I paid the wrong bill account|Contact the biller first, because they hold the money. We can confirm the payment details and the transaction ID to help them refund you.
bill-07|Can I pay water bills?|Yes. Choose Pay Bills, then Water, pick your water company and enter the account number from your printed bill.
bill-08|Is there a fee for paying bills?|Most bill payments are free. Some billers add a small convenience fee, which is shown on the confirmation screen before you enter your PIN.
bill-09|Can I get a receipt for a bill payment?|Every payment has a receipt in the app under History. Tap the payment and choose Share receipt to send it as a PDF or image.
bill-10|Can I pay government fees such as passport fees?|Some government services accept wallet payments. Look for them under Pay Bills, then Government. You need the payment reference from the agency.
merch-01|How do I pay at a shop?|Choose Pay Merchant, enter the till number shown at the counter or scan the shop's QR code, enter the amount and confirm with your PIN.
merch-02|What is a till number?|A till number is a short code that identifies a shop that accepts Tumba Wallet. Paying to a till sends money to the business, not a personal wallet.
merch-03|How can my business accept wallet payments?|Register for a merchant account in the app under Business, with your business registration and ID. You get a till number and a printed QR code.
merch-04|I paid a shop but they say they did not receive it|Show the shop the SMS with the transaction ID. The shop can check its merchant statement. If it is still missing, call customer care.
merch-05|Do shops pay a fee for wallet payments?|Merchants pay a small fee on each payment, which is listed in the merchant terms. Customers do not pay a fee to pay a shop.
merch-06|Can I get a refund from a shop?|Refunds are up to the shop. The shop can send the refund from its merchant account to your wallet, and you get an SMS when it arrives.
merch-07|Can I pay online with my wallet?|Yes, at online shops that show Tumba Wallet at checkout. Enter your number and approve the payment prompt on your phone with your PIN.
merch-08|What is the difference between a till number and a paybill number?|A till is for paying a shop at the counter. A paybill number is for paying a company account, such as a utility, and also needs an account reference.
merch-09|How do I withdraw money from my merchant account?|Move it to your personal wallet, or send it to a linked bank account from the merchant dashboard. Bank transfers settle the next working day.
merch-10|Can I have staff accounts for my shop tills?|Yes. In the merchant dashboard add each cashier as a staff user. Staff can accept payments but cannot withdraw money or change settings.
bank-01|How do I link my bank account?|Go to Bank Services, choose Link account, pick your bank and enter your account number. Your bank sends a code to confirm the link.
bank-02|How do I move money from my wallet to my bank?|Choose Bank Services, then Wallet to Bank, pick the linked account and enter the amount. Most transfers arrive within minutes during banking hours.
bank-03|Why can I not see my bank in the list?|Only partner banks appear. If your bank is not listed, send money from your bank using its own app to your wallet number instead.
bank-04|My bank transfer is pending|Transfers outside banking hours or on public holidays wait until the next working day. If it is pending longer than that, contact customer care.
bank-05|Can I get a loan from my bank through the wallet?|Some partner banks offer loans in the app under Bank Services. The bank decides who qualifies and sets the terms.
bank-06|Is there a fee to send to a bank?|Yes. Wallet to bank transfers carry a fee that depends on the amount. The exact fee is shown before you confirm.
bank-07|How do I unlink a bank account?|Go to Bank Services, choose Linked accounts, select the account and tap Remove. Scheduled transfers to that account are cancelled.
bank-08|Can I link more than one bank account?|Yes, up to three bank accounts. Choose which one to use each time you move money.
bank-09|Do I need internet banking to link my account?|No. Your bank confirms the link with a code sent to the phone number registered with the bank, which must match your wallet number.
bank-10|The name on my bank does not match my wallet|The bank may reject the link if the names differ. Update your wallet name with ID at a service centre, or ask your bank to correct theirs.
intl-01|Can I send money to another country?|Yes, to partner countries. Choose Send Money, then International, pick the country and enter the receiver's wallet number or bank details.
intl-02|Which exchange rate do you use?|The rate for international transfers is shown before you confirm and is fixed for that transfer. Rates change during the day.
intl-03|How long does an international transfer take?|Transfers to another mobile wallet usually arrive within minutes. Transfers to a foreign bank account can take up to three working days.
intl-04|Can I receive money from family in Europe or America?|Yes. Ask them to use a partner remittance service and choose Tumba Wallet as the delivery method, entering your number with the country code.
intl-05|Why was my international transfer blocked?|We check cross-border transfers against sanctions and anti-fraud rules. A blocked transfer is refunded, and customer care can tell you what is needed.
intl-06|What details do I need for a foreign bank transfer?|The receiver's full name, bank name, account number and the bank's SWIFT code. Some countries also need the receiver's address.
intl-07|Can I use my wallet while travelling abroad?|The app and *345# work while you roam, but roaming charges from your network may apply. You can still send money and pay bills at home.
intl-08|Is there a limit on international transfers?|Yes. International transfers have their own monthly limit, which depends on your tier. Full KYC is needed to send abroad.
intl-09|Can I cancel an international transfer?|You can cancel it from History only while it shows as Processing. Once it has been paid out it cannot be cancelled.
intl-10|Do I pay tax on money sent from abroad?|Receiving remittances is not a taxable event in our terms, but tax rules are set by the government. Ask a tax adviser about your situation.
limit-01|What are the account tiers?|Tier 1 needs only a phone number and name. Tier 2 adds a verified ID. Tier 3 adds proof of address and has the highest limits.
limit-02|How do I upgrade my account tier?|Open Profile, then Upgrade, and upload your ID and a photo of yourself. Tier 3 also needs proof of address, such as a utility bill.
limit-03|What is the daily transfer limit?|The daily limit depends on your tier and is shown under Profile, then Limits. It resets at midnight.
limit-04|What is the maximum balance I can hold?|Each tier has a maximum balance, shown under Profile, then Limits. Upgrade your tier to hold more.
limit-05|Why do you need a selfie for verification?|The selfie is matched to the photo on your ID to confirm it is really you. This protects your wallet from people using a stolen ID.
limit-06|How long does verification take?|Most ID checks finish within an hour. Checks that need a person to look at the documents take up to two working days.
limit-07|My verification was rejected|The SMS gives the reason. Common causes are a blurred photo, an expired ID or a name that does not match. Upload new photos to try again.
limit-08|Can I raise my limit for one large payment?|No. Limits are fixed by tier for regulatory reasons. Upgrade your tier, or split the payment over several days.
limit-09|What is proof of address?|A recent utility bill, bank statement or tenancy agreement in your name, dated within the last three months.
limit-10|Is my ID information kept private?|Your documents are stored encrypted and used only for verification and legal checks. Read the privacy notice in the app for details.
fee-01|What does it cost to send money?|Sending to another Tumba wallet costs a small flat fee that rises with the amount. The fee table is in the app under Help, then Fees.
fee-02|How much is the withdrawal fee?|The withdrawal fee depends on the amount and is shown before you confirm. Withdrawing at an agent and at an ATM cost the same.
fee-03|Why was I charged twice?|A double charge is usually one transfer and its fee shown on separate lines. If the amount itself appears twice, call customer care with both transaction IDs.
fee-04|Are there monthly account fees?|No. There is no monthly fee and no fee for keeping money in the wallet.
fee-05|Are there free transfers?|The first three transfers each month to other Tumba wallets are free for amounts under the small transfer limit.
fee-06|Where can I see all the fees I have paid?|Open History and filter by Fees, or download a statement, which lists each fee next to its transaction.
fee-07|Do you charge for checking my balance?|Checking your balance is free in the app and on *345#. Your network does not charge for the USSD session either.
fee-08|Why did the fee change?|Fees are reviewed from time to time. We send an SMS at least 30 days before any fee goes up, and the new table is in the app.
fee-09|Do I pay a fee to receive a voucher?|No. The sender pays the fee when sending to someone without a wallet. Collecting the cash at an agent is free.
fee-10|Is the fee taken from the amount I send?|No. The fee is added on top of the amount, so the receiver gets the full amount you typed.
save-01|How do I save money in the wallet?|Open Savings and create a pocket with a name and a target. Move money in whenever you like, or set an automatic weekly amount.
save-02|Do savings pockets earn interest?|Yes. Savings pockets earn interest paid monthly. The current rate is shown on the Savings screen.
save-03|Can I lock my savings so I do not spend them?|Yes. Choose a locked pocket and pick an end date. Money in a locked pocket cannot be moved out until that date.
save-04|How do I borrow money?|Open Loans to see the amount you can borrow, which depends on how you use the wallet. Pick an amount and term and accept the terms with your PIN.
save-05|Why is my loan limit so low?|Your loan limit grows as you use the wallet regularly and repay on time. New wallets start with a small limit.
save-06|What happens if I repay my loan late?|A late fee is added, and your loan limit may drop. Late repayment can also be reported to credit bureaus. Contact us early if you are struggling.
save-07|Can I repay my loan early?|Yes. Open Loans and choose Repay. Repaying early reduces the fee on most loan types and can raise your next limit.
save-08|How do group savings work?|Create a group in Savings, invite members and set a contribution amount and schedule. Everyone can see contributions, and payouts need the group's approval.
save-09|Can I withdraw from a savings pocket?|You can move money from a flexible pocket back to your main balance at any time. Locked pockets open on their end date.
save-10|Is my money safe if Tumba Wallet goes out of business?|Customer balances are held in trust accounts at regulated banks, separate from the company's own money, so they are protected.
app-01|The app keeps crashing|Update to the latest version from your app store, then restart your phone. If it still crashes, clear the app's cache or reinstall it.
app-02|Does the app work on old Android phones?|The app supports Android 8 and later and uses little storage. On older phones, use *345#, which offers the main services.
app-03|How much data does the app use?|Most actions use a few kilobytes. Turn on Data saver in Settings to stop images loading, which helps on small prepaid bundles.
app-04|Can I use the app in my language?|Yes. Go to Settings, then Language. The app and the *345# menu are available in English, French, Swahili, Hausa, Yoruba and Amharic.
app-05|The USSD menu says session timed out|USSD sessions end after about 30 seconds without input. Dial *345# again and move through the menu a little faster.
app-06|How do I check my balance?|Open the app to see it on the home screen, or dial *345#, choose My Account, then Balance, and enter your PIN.
app-07|How do I get a statement?|In the app, open History and choose Download statement, pick the dates and it is sent to your email as a PDF. Statements are free.
app-08|Why does the app ask for my location?|Location helps show agents near you and detect fraud. You can turn it off in your phone's settings, but the agent map will not work.
app-09|I am not getting transaction SMS messages|Check that your inbox is not full and that the number is not blocked. Notifications in the app still show every transaction.
app-10|Can I use the wallet on a tablet or computer?|The app runs on Android and iOS tablets. There is no desktop version, but merchants can use the merchant dashboard in a web browser.
safe-01|I think someone knows my PIN|Change your PIN now in Settings, then Security. If money has already left your wallet, call customer care at once so we can freeze it.
safe-02|How do I report a fraud call?|Note the caller's number, do not share any codes, and forward the details to our fraud line. We use reports to block scam numbers.
safe-03|Someone stole my phone|Call customer care from another phone to block the wallet straight away. Then block the SIM with your network and get a replacement.
safe-04|What is a fake reversal scam?|A scammer sends a fake SMS saying they sent you money by mistake and asks you to send it back. Always check your real balance before acting.
safe-05|How do I dispute a transaction?|Open the transaction in History and tap Report a problem, or call customer care with the transaction ID. We reply within five working days.
safe-06|How do I freeze my wallet?|In the app go to Settings, then Security, then Freeze wallet, or call customer care. A frozen wallet cannot send or withdraw until you unfreeze it.
safe-07|Is it safe to use public Wi-Fi with the app?|The app encrypts all traffic, but avoid shared phones and unknown networks for large payments. Mobile data is the safer choice.
safe-08|Someone used my wallet without permission|Freeze the wallet, then call customer care to report unauthorised transactions. We investigate and refund money taken because of our error.
safe-09|How can I tell if an SMS is really from Tumba Wallet?|Real messages come from the sender name TUMBA and never ask for your PIN or code. Check any message against your balance in the app.
safe-10|How do I contact customer care?|Call 345 free from your registered number, chat in the app under Help, or visit a service centre. Phone lines are open every day from 7am to 10pm.
TXTNow a small module that loads the file and decides what text gets embedded. Each entry is embedded as its question and answer together, because customers' questions often match words that appear only in the answer. The module also pins the model and the exact revision of its files on Hugging Face, so the vectors you build today match the ones you build next month:
cat > faq.py <<'PY'
from pathlib import Path
MODEL = "sentence-transformers/all-MiniLM-L6-v2"
REVISION = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41"
def load_faq(path="faq.txt"):
entries = []
for line in Path(path).read_text(encoding="utf-8").splitlines():
if line.strip():
faq_id, question, answer = line.split("|")
entries.append({"id": faq_id, "question": question, "answer": answer})
return entries
def entry_text(entry):
return f"{entry['question']} {entry['answer']}"
PYCheck it worked
python -c "from faq import load_faq; faq = load_faq(); print(len(faq), len({e['id'] for e in faq}), faq[0]['question'])"The output is 150 150 How do I open a Tumba Wallet account?: 150 entries and 150 different ids. If split raises ValueError: too many values to unpack, a line contains an extra |; if it says not enough values, a line lost one when you pasted it.
Step 3 · Embed the FAQ and save the index
build_index.py loads the model, embeds all 150 entries in batches of 32, and saves two files: faq_vectors.npy with one row of 384 numbers per entry, and faq_ids.json with the ids in the same order. Row 7 of the matrix belongs to the seventh id, so the two files must always be written together.
cat > build_index.py <<'PY'
import json
import time
import numpy as np
from sentence_transformers import SentenceTransformer
from faq import MODEL, REVISION, entry_text, load_faq
faq = load_faq()
model = SentenceTransformer(MODEL, revision=REVISION, device="cpu")
started = time.perf_counter()
vectors = model.encode(
[entry_text(e) for e in faq],
batch_size=32,
normalize_embeddings=True,
convert_to_numpy=True,
)
elapsed = time.perf_counter() - started
np.save("faq_vectors.npy", vectors.astype(np.float32))
with open("faq_ids.json", "w", encoding="utf-8") as f:
json.dump([e["id"] for e in faq], f)
norms = np.linalg.norm(vectors, axis=1)
print("entries:", len(faq))
print("shape:", vectors.shape, vectors.dtype)
print(f"norms: min {norms.min():.4f} max {norms.max():.4f}")
print(f"encoded in {elapsed:.1f} s")
longest = max(len(model.tokenizer(entry_text(e))["input_ids"]) for e in faq)
print(f"longest entry: {longest} tokens (model limit {model.max_seq_length})")
PY
python build_index.pyTwo arguments to encode matter here. batch_size=32 sends 32 texts through the model at a time, which is much faster than one by one and keeps memory use small; for a few thousand entries you do not need to change it. normalize_embeddings=True scales every vector to length 1. Cosine similarity is the dot product of two vectors divided by both their lengths, so when every length is 1, cosine similarity is just the dot product. That is what makes the search in the next step a single matrix product.
The last line checks truncation. The model reads at most 256 word pieces and silently ignores the rest, so a long answer would be judged by its first part only. FAQ entries are short, but check it whenever you index new content. Longer documents need splitting first, as in split documents into chunks for a RAG app.
The first run downloads the model to ~/.cache/huggingface and may print a warning about unauthenticated requests to the Hugging Face Hub. It is harmless for a public model; no token is needed.
Check it worked
The output looks like this (the time depends on your CPU):
entries: 150
shape: (150, 384) float32
norms: min 1.0000 max 1.0000
encoded in 0.9 s
longest entry: 52 tokens (model limit 256)Both norms are 1.0000, so every vector is normalised. ls -l faq_vectors.npy shows about 230 KB: 150 rows of 384 four-byte floats, plus a small header.
Step 4 · Search with a matrix product
To search, embed the question the same way, normalised, and multiply the whole matrix by it. vectors @ q gives 150 dot products in one call, which are the 150 cosine similarities. np.argsort(-scores) orders the rows from highest score to lowest, and the first k are the results. Create search.py:
cat > search.py <<'PY'
import json
import sys
import numpy as np
from sentence_transformers import SentenceTransformer
from faq import MODEL, REVISION, load_faq
class SemanticSearch:
def __init__(self):
self.faq = {e["id"]: e for e in load_faq()}
self.vectors = np.load("faq_vectors.npy")
with open("faq_ids.json", encoding="utf-8") as f:
self.ids = json.load(f)
if self.ids != list(self.faq):
raise SystemExit("faq_ids.json does not match faq.txt: run build_index.py again")
self.model = SentenceTransformer(MODEL, revision=REVISION, device="cpu")
def search(self, query, k=3):
q = self.model.encode(query, normalize_embeddings=True, convert_to_numpy=True)
scores = self.vectors @ q
top = np.argsort(-scores)[:k]
return [(self.ids[i], float(scores[i])) for i in top]
if __name__ == "__main__":
engine = SemanticSearch()
for query in sys.argv[1:]:
print(f"> {query}")
for faq_id, score in engine.search(query):
print(f" {score:.3f} {faq_id} {engine.faq[faq_id]['question']}")
PY
python search.py "i sent money to the wrong number" "my pin is locked" "how much is it to send money to my sister"The class checks that faq_ids.json still matches faq.txt before searching. Edit the FAQ without rebuilding the index and the rows would point at the wrong answers, so it refuses to start instead.
On 150 entries a full sort takes microseconds. On a few hundred thousand you would use np.argpartition to find the top k without sorting everything, and past a few million, an approximate index such as the HNSW index in vector search with PostgreSQL and pgvector.
Check it worked
Each query prints three results with a score, an id and the FAQ question. For i sent money to the wrong number, send-02 I sent money to the wrong number appears in the top three; in our run it scored about 0.68. The other two results are entries the model judged close in meaning, and their order can shift slightly between machines. That is why you will measure the top three later, not only the top one. The PIN query returns a pin- entry first.
Step 5 · Say "no good answer" below a threshold
A search always returns something, even for "recipe for jollof rice". In a help centre, a wrong answer shown with confidence is worse than "I could not find that, here is how to reach customer care". The fix is a threshold: if the best score is below it, show no answer.
Pick the threshold from your own data, not from a blog post, because score ranges differ between models. Print the best score for questions that belong in the FAQ and for questions that do not:
cat > threshold.py <<'PY'
from search import SemanticSearch
on_topic = [
"i sent money to the wrong number",
"how do I pay for electricity",
"my PIN is not working",
"is there a fee to receive money",
"how do I top up my phone",
"how do I save for school fees",
]
off_topic = [
"what is the weather in Nairobi tomorrow",
"recipe for jollof rice",
"who won the football match last night",
"how do I fix a flat bicycle tyre",
"translate good morning into French",
]
engine = SemanticSearch()
for label, queries in (("on-topic", on_topic), ("off-topic", off_topic)):
for query in queries:
faq_id, score = engine.search(query, k=1)[0]
print(f"{label:9} {score:.3f} {faq_id:9} {query}")
PY
python threshold.pyIn our run, the on-topic questions scored between 0.38 and 0.69, and the off-topic ones between 0.12 and 0.23. The lowest on-topic score was how do I top up my phone, at 0.38: the FAQ says "airtime", and the closest entry it found was the one about automatic top-up. A threshold of 0.30 sits in the gap with room on both sides. Put it in answer.py, which returns the best answer or nothing:
cat > answer.py <<'PY'
import sys
from search import SemanticSearch
THRESHOLD = 0.30
engine = SemanticSearch()
def answer(query):
faq_id, score = engine.search(query, k=1)[0]
if score < THRESHOLD:
return None, score
return engine.faq[faq_id], score
for query in sys.argv[1:]:
entry, score = answer(query)
if entry is None:
print(f"{score:.3f} no good answer: {query}")
else:
print(f"{score:.3f} {entry['id']}: {entry['answer']}")
PY
python answer.py "how do I top up my phone" "recipe for jollof rice"Five off-topic questions are not enough to set a threshold for production. Collect real questions from your search logs, include the near misses (questions about a competitor, about the bank behind your wallet), and check the threshold again whenever you change the model or the FAQ.
This check confirms that 0.30 still sits in the gap between the two groups, so a model or FAQ change that closes the gap fails loudly:
Check it worked
The first line starts with a score near 0.38 and an air- id with the answer text. The second line reads something like 0.132 no good answer: recipe for jollof rice. If an off-topic question in your own list scores above 0.30, raise the threshold and re-run both scripts.
Step 6 · Label test queries and measure against BM25
Trying a few searches by hand tells you little. To compare approaches you need a fixed set of questions, each labelled with the entry or entries that answer it. Write them the way customers do, not the way the FAQ is written: short, lower case, sometimes only a phrase from a screen or an SMS. Two of these questions accept either of two entries, separated by a comma:
cat > queries.txt <<'TXT'
i sent cash to the wrong person by mistake, can i get it back|send-02
forgot pin|pin-01
my wallet got blocked after I typed the pin wrong three times|pin-03
how much does it cost to take out cash|fee-02
where is the closest place to cash out|agent-03
*345# session timed out|app-05
prepaid meter token not received|bill-02
my phone was stolen, what should I do|safe-03
can my shop take payments from customers|merch-03
transfer from wallet into my bank account|bank-02
sending money to my brother in another country|intl-01
how do I increase my limits|limit-02
do I earn anything on money I put aside|save-02
the app eats too much of my data|app-03
swift code for a foreign bank|intl-06
someone phoned pretending to work for you and wanted a code|safe-02
a stranger sent me money and now wants it back|recv-05,safe-04
can I use it with no internet|air-09,app-02
smart card number|bill-04
cardless withdrawal|agent-06
TXTThe baseline is BM25, the keyword ranking behind most search engines. It scores an entry higher when it contains the query's words, especially rare ones, and it knows nothing about meaning. rank-bm25 implements it in pure Python. The tokeniser below lower-cases the text and keeps runs of letters and digits.
The measure is hit rate at 3: the share of queries where at least one correct entry is in the top three. It matches what a customer sees, a short list under the search box.
cat > evaluate.py <<'PY'
import re
import numpy as np
from rank_bm25 import BM25Okapi
from faq import entry_text, load_faq
from search import SemanticSearch
K = 3
faq = load_faq()
ids = [e["id"] for e in faq]
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
bm25 = BM25Okapi([tokenize(entry_text(e)) for e in faq])
semantic = SemanticSearch()
def keyword_ranking(query, n):
scores = bm25.get_scores(tokenize(query))
return [ids[i] for i in np.argsort(-scores)[:n]]
def semantic_ranking(query, n):
return [faq_id for faq_id, _ in semantic.search(query, k=n)]
def load_queries(path="queries.txt"):
pairs = []
for line in open(path, encoding="utf-8"):
if line.strip():
query, gold = line.rstrip("\n").split("|")
pairs.append((query, set(gold.split(","))))
return pairs
def report(methods):
queries = load_queries()
for name, rank in methods.items():
misses = [q for q, gold in queries if not gold & set(rank(q, K))]
hits = len(queries) - len(misses)
print(f"{name:9} hit@{K}: {hits}/{len(queries)} = {hits / len(queries):.2f}")
for q in misses:
print(f" missed: {q}")
if __name__ == "__main__":
report({"bm25": keyword_ranking, "semantic": semantic_ranking})
PY
python evaluate.pyCheck it worked
The output has a hit rate for each method, followed by the queries it missed. In our run BM25 found 14 of 20 (0.70) and semantic search 16 of 20 (0.80). Read the misses, because they say more than the numbers. BM25 missed my phone was stolen, what should I do and someone phoned pretending to work for you and wanted a code: the FAQ says "stole" and "fraud call", and BM25 does not know they mean the same. Semantic search missed smart card number, a bare phrase with no question around it, which BM25 matched exactly. Both missed how do I increase my limits, because the FAQ calls it upgrading your tier. That is a content problem: add the customers' wording to the entry and rebuild the index.
Step 7 · Combine both rankings with reciprocal rank fusion
The two methods miss different questions, which suggests combining them. Their scores cannot be added directly: BM25 scores have no fixed range, while cosine scores sit between -1 and 1. Reciprocal rank fusion ignores scores and uses positions. Each method's top 20 gives every entry 1 / (60 + rank), the values are added up, and entries are sorted by the total. An entry ranked well by both methods wins; an entry ranked first by only one still does well. The constant 60 comes from the paper that introduced the method and dampens the difference between rank 1 and rank 2.
cat > hybrid.py <<'PY'
from evaluate import keyword_ranking, report, semantic_ranking
CANDIDATES = 20
def reciprocal_rank_fusion(rankings, k=60):
fused = {}
for ranking in rankings:
for rank, faq_id in enumerate(ranking, start=1):
fused[faq_id] = fused.get(faq_id, 0.0) + 1 / (k + rank)
return sorted(fused, key=fused.get, reverse=True)
def hybrid_ranking(query, n):
rankings = [keyword_ranking(query, CANDIDATES), semantic_ranking(query, CANDIDATES)]
return reciprocal_rank_fusion(rankings)[:n]
if __name__ == "__main__":
report({"bm25": keyword_ranking, "semantic": semantic_ranking, "hybrid": hybrid_ranking})
print(hybrid_ranking("transfer from wallet into my bank account", 3))
PY
python hybrid.pyCheck it worked
The output repeats the two earlier lines and adds hybrid. In our run the hybrid also found 16 of 20, the same as semantic search alone, but with different misses: it recovered smart card number from BM25 and lost someone phoned pretending to work for you and wanted a code, where BM25's poor ranking pulled the right entry out of the top three. The last line is the hybrid's top three for one query and contains bank-02.
The lesson is that fusion is not a free win. On 20 queries, one question either way is noise, so the honest conclusion is that semantic search clearly beats keywords here and the hybrid ties. With more labelled queries, many exact-term searches (codes, product names, error messages) favour the hybrid, and many paraphrases favour embeddings. Decide with your own logs and this script, and re-run it whenever you change the FAQ, the model or the threshold.
A note for multilingual help centres: all-MiniLM-L6-v2 is an English model. If customers write in French, Swahili, Hausa or a mix of languages, look at a multilingual model such as paraphrase-multilingual-MiniLM-L12-v2, check that its model card lists your languages (that one covers French but not Swahili, Hausa or Yoruba), and add questions in those languages to queries.txt before you trust it.
Step 8 · Clean up
Reranking the top results with a slower model is covered in rerank search results with a cross-encoder, which builds its own data and stands on its own. When you have finished here, leave the virtual environment and remove the project folder and the downloaded model:
deactivate
cd ~
rm -rf ~/faq-search-demo
rm -rf ~/.cache/huggingface/hub/models--sentence-transformers--all-MiniLM-L6-v2Check it worked
ls ~/faq-search-demo reports that the folder does not exist.
Next steps
- Make the top result more precise by rereading the top 20 with a slower, more accurate model: rerank search results with a cross-encoder.
- Move the vectors into a database when the FAQ outgrows memory: vector search with PostgreSQL and pgvector, then combine keyword and vector search in PostgreSQL.
- Go back to the basics of what the scores mean: turn text into embeddings with sentence-transformers.
Part of these paths
Related tutorials
- Turn text into embeddings and compare meaning with sentence-transformersYou will run a small embedding model on your own CPU, turn a dozen sentences into vectors, and check with cosine similarity that paraphrases score high while sentences that only share keywords do not.
- Rerank search results with a cross-encoderYou will add a cross-encoder reranking stage to an embedding search over 60 FAQ answers and measure, on 20 labelled queries, how much it lifts hit rate at 1 and MRR and how many milliseconds it adds per query on CPU.
- How to Do Vector Similarity Search in PostgreSQL with pgvectorYou will install PostgreSQL 18 with the pgvector extension on Ubuntu 26.04, store and compare vectors with SQL, load the chunks from the previous tutorial into a table, and add an HNSW index to make nearest-neighbour search fast.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials