Detailed content
🔤 Turn text into data
NLP (Natural Language Processing, or natural language processing, is a set of techniques that lets a program read, organize, and produce human language. The starting problem is always the same: a computer only works with numbers. Before it can classify a complaint or summarize a contract, text has to become a sequence of numbers—and every choice in that conversion affects the result later on.
Until around 2018, NLP work was dominated by rules and small models trained for a single task. Today, an LLM can do almost anything with a well-written instruction. But the fundamentals still apply: tokens cost money and fit within a limited window, messy text produces messy answers, and the same word can mean different things depending on the context.
📘 New terms
Tokenization means breaking text into pieces (tokens) from the model’s vocabulary. Today’s models use subwords, generated by algorithms such as BPE (Byte Pair Encoding): common words become one token; rare words are split into parts. Normalization means standardizing text before processing it—spaces, line breaks, capitalization, and invisible characters.
What it is
The path is text → tokens → numeric IDs → vectors. The vectors (embeddings) carry the meaning the model has learned; everything that comes next—classification, extraction, search—operates on them.
✓ Always normalize
- ✓Unicode in NFC form (composed and decomposed accents become the same).
- ✓Repeated spaces, tabs, and extra line breaks.
- ✓Email signatures, footers, and HTML that carry no meaning.
- ✓Personal data that doesn’t need to go to the model (LGPD, Module 2.9).
✗ Don’t destroy the signal
- ✗Removing accents: “pais” and “país” are no longer different.
- ✗Removing “não” as a stop word: the sentence reverses its meaning.
- ✗Converting everything to lowercase when acronyms and names matter.
- ✗Removing emojis from reviews: they often carry the sentiment.
💡 Tip
With LLMs, aggressive cleaning with older techniques (stemming, removing stop words) does more harm than good. Clean up formatting noise and personal data; leave the language as it is.
Why learn
Understanding tokens explains the bill that arrives at the end of the month, why a document “doesn’t fit” in the context window, and why poorly cleaned text confuses the model. It’s the foundation for sizing any text pipeline before writing the first line of code.
Key concepts
🏷️ Classify text
Text classification means assigning each text a label from a closed list: the subject of a support ticket, the sentiment of a review, the urgency of an email, whether a message is spam. It’s the most common NLP task in businesses because it lets you route, count, and prioritize without anyone reading everything.
There are three approaches. The classic turns text into word counts (TF-IDF) and trains a simple model, such as logistic regression in scikit-learn—fast and inexpensive, but it needs hundreds of labeled examples. The fine-tuning of a small model (from the BERT family) delivers high quality, with training costs. And zero-shot with an LLM classifies using only the label list and an instruction, with no training at all.
📘 New terms
TF-IDF weights each word by its frequency in the text and its rarity across the entire dataset. Zero-shot means doing the task without examples; few-shot means including a few examples in the prompt itself. Structured output means requiring the model to respond in a machine-readable format, such as JSON.
What it is
A function that takes text and returns a label from a list you define, preferably with a short explanation and in a format the rest of the system can validate.
| Approach | Requires | Best when | Caution |
|---|---|---|---|
| TF-IDF + linear model | Hundreds of labeled examples | High volume, stable labels, minimal cost | Doesn’t understand synonyms or irony |
| Fine-tuning (BERT and similar models) | Labeled examples and a GPU | High quality with low latency | Retraining for every new label |
| Zero-shot/few-shot LLM | A list of labels and a good instruction | Getting started today, changing labels | Cost and latency per item; validate the output |
Try this: local zero-shot classifier, saved as classifier.py.
# Installation: pip install openai | ollama pull qwen2.5:7b
# classifier.py — uses Ollama's OpenAI-compatible route (local and free)
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # Ollama ignores the key
LABELS = ["delivery", "payment", "product", "compliment", "other"]
INSTRUCTION = (
"You classify messages from customers of an online store. "
'Respond ONLY with JSON in the format {"label": "...", "reason": "..."}. '
"Valid labels: " + ", ".join(LABELS) + ". "
"Use 'other' when none applies. The reason must be no more than 12 words."
)
def classify(text: str) -> dict:
resp = client.chat.completions.create(
model="qwen2.5:7b",
temperature=0, # same input, same output (almost always)
response_format={"type": "json_object"}, # forces valid JSON
messages=[{"role": "system", "content": INSTRUCTION},
{"role": "user", "content": text}],
)
data = json.loads(resp.choices[0].message.content)
if data.get("label") not in LABELS: # never blindly trust the output
data["label"] = "other"
return data
if __name__ == "__main__":
print(classify("<paste a real customer message here, without personal data>"))
How to check: run python3 classificador.py. The output should be a dictionary like {'rotulo': 'entrega', 'motivo': '...'}. Test five messages with different labels and one that has nothing to do with the store: it should be classified as "outro". To use a paid API, change only base_url, api_key e model.
💡 Tip
Start with the LLM to identify the right labels and gather examples. As volume grows and the labels stabilize, use responses reviewed by people to train a small, inexpensive classifier. This is a common way to reduce costs without losing quality.
Why learn
Almost every customer support, triage, or sentiment analysis system starts with classification. Knowing how to choose between the classic approach, fine-tuning, and an LLM—and how to validate the output—helps you avoid both an overly expensive project and one that breaks on the first response in the wrong format.
Key concepts
🧾 Extract entities
NER (Named Entity Recognition, finding people’s names, companies, places, dates, and amounts in text, and identifying the type of each. With this, a contract becomes a spreadsheet row: parties, amount, term, jurisdiction. A news story becomes a list of the companies mentioned.
There are two families of tools. Libraries like spaCy include ready-to-use models for Portuguese (pt_core_news_sm) that quickly identify people, places, and organizations at no cost. For fields specific to your business (order number, product name, penalty clause), an LLM with a JSON schema is usually more flexible: you describe the fields, and the model fills them in.
📘 New terms
JSON Schema is a formal description of a JSON’s fields, types, and required properties. Ollama accepts this schema in the format parameter and constrains generation so the response fits it. BIO tags (Begin, Inside, Outside) is the classic way to mark entities word by word when training NER models.
What it is
Information extraction: find passages with specific meanings in free-form text and return them organized by type, ready to go into a database or another pipeline step.
Goal: extract entities with a JSON schema and check that nothing was made up.
# Installation: pip install requests | ollama pull qwen2.5:7b
import json, requests
CAMPOS = ["pessoas", "organizacoes", "locais", "datas", "valores"]
SCHEMA = {
"type": "object",
"properties": {c: {"type": "array", "items": {"type": "string"}} for c in CAMPOS},
"required": CAMPOS,
}
def extrair(texto: str) -> dict:
r = requests.post("http://localhost:11434/api/chat", json={
"model": "qwen2.5:7b",
"stream": False,
"format": SCHEMA, # the response is restricted to this schema
"options": {"temperature": 0},
"messages": [
{"role": "system", "content": "Extract the entities from the text. Copy each passage "
"exactly as it appears. Don't make anything up: use an empty list when there are none."},
{"role": "user", "content": texto},
],
}, timeout=120)
r.raise_for_status()
return json.loads(r.json()["message"]["content"])
texto = "<paste a paragraph from a contract, news story, or email>"
ents = extrair(texto)
print(json.dumps(ents, ensure_ascii=False, indent=2))
# Anti-fabrication check: every passage must appear literally in the text
for tipo, itens in ents.items():
for item in itens:
if item not in texto:
print(f"WARNING [{tipo}] is not in the text: {item!r}")
How to check: With the sentence from the diagram, the output should have all five lists filled and no "WARNING" line. Then paste text with no dates: dates it should come back empty. If a warning appears, the model rewrote or made up a passage—treat that as an error, not a success.
💡 Tip
For standard entities at scale, try spaCy first: pip install spacy e python -m spacy download pt_core_news_sm. It runs on CPU, with no GPU, and serves as a baseline for comparison with the LLM.
Why learn
Much of the value of NLP in companies comes from extracting data from documents: receipts, contracts, medical reports, résumés, and emails. Knowing how to extract data using a schema and verify it against the original text is what separates a demo from a process you can trust.
Key concepts
📄 Summarize long texts
Summarizing seems simple until a document runs to dozens of pages. Even with large context windows, models tend to pay less attention to the middle of very long texts, and a single summary hides where each claim came from. The robust method is to split, summarize the parts, and then combine them, keeping a reference for each passage.
There are two types of summary. An extractive summary selects sentences from the original and copies them—safe because nothing is rewritten. An abstractive summary rewrites the text in other words—more fluent, but it can distort the meaning. For legal, medical, or financial texts, a middle ground works well: an abstractive summary with direct quotes from the passages that support each point.
📘 New terms
Chunking is to divide the document into passages (chunks) of a controlled size, preferably following sections and paragraphs. Overlap (overlap) is repeating part of the end of one passage at the beginning of the next so an idea isn't cut in half. Map-reduce means applying the same operation to each passage (map) and then combining the results (reduce).
What it is
Summary in stages: the document is divided into passages, each passage gets a partial summary with a reference to its source, and finally a final summary combines the partial summaries in the format the reader needs.
For decision-makers
Five points, with risks first, each with its source page. End with "what remains to be decided."
For implementers
List obligations, deadlines, and owners in a table. No long paragraphs.
For the system
JSON with fixed fields (topic, parties, dates, amounts) for indexing and filtering later.
💡 Tip
Split by structure (headings, clauses, sections), not by a fixed number of characters. A cut in the middle of a clause produces two incorrect partial summaries.
Why learn
Reports, meeting minutes, case files, and manuals are long and read in a hurry. A traceable summary saves hours of reading without hiding where each conclusion came from—and the same pattern of splitting, processing, and combining works for translation, extraction, and review of large documents.
Key concepts
🔎 Semantic search
Keyword search only finds content that uses the same word. Someone who asks “my package hasn’t arrived” won’t find the text “delivery time”—even though that’s exactly what they’re looking for. Semantic search compares meanings: it turns the question and documents into vectors and returns the documents whose vectors are closest.
This is the central part of RAG (retrieval-augmented generation), covered in the module on knowledge bases: before answering, the system searches for relevant passages and provides them to the LLM. In production, the vectors are stored in a dedicated database— pgvector in Postgres, Qdrant or Chroma. To learn, a NumPy array is enough.
📘 New terms
Cosine similarity measures the angle between two vectors: near 1, they point in the same direction (similar meanings); near 0, they’re unrelated. If the vectors are normalized (length 1), the cosine becomes a simple dot product. Hybrid search combines keywords and vectors, useful when exact codes and names matter.
What it is
Search by similarity of meaning: an embedding model converts texts into vectors, and the query returns the texts closest to the question by cosine similarity, even when they have no words in common.
Try this: local semantic search with nomic-embed-text.
# Installation: pip install requests numpy | ollama pull nomic-embed-text
import requests
import numpy as np
def embed(textos: list[str]) -> np.ndarray:
r = requests.post("http://localhost:11434/api/embed",
json={"model": "nomic-embed-text", "input": textos}, timeout=120)
r.raise_for_status()
v = np.array(r.json()["embeddings"], dtype=float)
return v / np.linalg.norm(v, axis=1, keepdims=True) # normalize: cosine = dot product
# nomic-embed-text recommends different prefixes for documents and queries
docs = [
"The delivery time is 5 to 10 business days after payment is confirmed.",
"Expired bills can be reissued in the customer area.",
"Returns are accepted within 7 calendar days after receipt.",
"<add passages from your own knowledge base here, one per item>",
]
D = embed(["search_document: " + d for d in docs])
def buscar(pergunta: str, k: int = 2) -> None:
q = embed(["search_query: " + pergunta])[0]
notas = D @ q
for i in np.argsort(-notas)[:k]:
print(f"{notas[i]:.3f} {docs[i]}")
buscar("my package still hasn’t arrived")
How to check: The first result should be the sentence about delivery time, even though it doesn’t contain the word “package.” Change the question to “can I return the T-shirt?”—the sentence about returns should move to the top. Scores vary from model to model; compare the ranking, not the absolute value.
Why learn
Semantic search is the foundation of assistants that answer using company documents, ticket deduplication, and content recommendations. Understanding the vector and the metric helps you diagnose why a search fails—before blaming the LLM for a bad answer.
Key concepts
🌍 Portuguese and other languages
Most of the training data for models is still in English. Today’s LLMs handle Portuguese well, but differences still arise: more tokens for the same content, slang and regional expressions being misinterpreted, confusion between Brazilian and European Portuguese, and errors with local formats—CPF, CEP, dates in day/month format, decimal commas, “R$ 1.234,56.”
For translation, you have open, dedicated models such as NLLB from Meta, and general-purpose LLMs, which translate well and also follow tone and glossary instructions. For systems that receive text in multiple languages, the standard approach is to detect the language first and decide whether to process it in the original language with a multilingual model or translate it first.
📘 New terms
A multilingual model is trained on several languages at once and places equivalent sentences close together in embedding space—so a question in Portuguese can find a document in Spanish. A glossary, in translation, is a list of terms that should always be translated the same way (or left untranslated, such as product names).
What it is
It means treating language and local formats as part of the problem: detect the language, choose the right model and prompt, standardize numbers, dates, and Brazilian documents, and test with real texts from your audience.
✓ Works well
- ✓Explicitly request “Brazilian Portuguese” in the system prompt.
- ✓Convert “R$ 1.234,56” and “03/02/2026” with code, not the model.
- ✓Validate CPF and CNPJ using the check digit after extraction.
- ✓Use a fixed glossary in the translation prompt for company terms.
✗ Common pitfalls
- ✗Test only with English text and publish for Brazilian customers.
- ✗Let the model interpret “02/03” without knowing the date format.
- ✗Ignore text with typos and WhatsApp abbreviations.
- ✗Translate first and then extract, losing original names and values.
💡 Tip
Build your test set with messages written the way your customers actually write—with “vc,” “pq,” typos, and transcribed audio. Models that perform well on clean text can do much worse on informal text, and only testing shows how much.
Why learn
Examples, tutorials, and benchmarks are often in English. Anyone building for a Brazilian audience needs to know the typical failure points in Portuguese and local formats—that’s where a system that “worked in testing” breaks with its first real customer.
Key concepts
🧪 Pipeline and evaluation
A text pipeline chains together the steps in this module: normalize, detect language, classify, extract, validate, and record. Each step has defined inputs and outputs, and each can fail. Without measuring, you don’t know which step failed or whether a model or prompt change improved or worsened the result.
The tool for this is the test set: a few dozen real, anonymized examples with the correct answer labeled by a person. Run every change against it. The resulting number doesn’t need to be perfect; it needs to be comparable across versions.
📘 New terms
Accuracy is the fraction of correct predictions out of the total. Precision for a label: of the items the model assigned that label, how many were correct. Recall (Recall): of the items that actually belonged to that label, how many the model found. F1 combines the two. With imbalanced classes, look at precision and recall for each label, not just accuracy.
What it is
A sequence of text processing steps with defined input and output contracts, tracked with a labeled test set that measures every change before it reaches users.
Step 1 · Gather real examples. Start with 30 to 50 anonymized messages covering all labels and difficult cases.
Step 2 · Label the correct answer. Having two people label the same sample reveals where the labels themselves are ambiguous.
Step 3 · Measure the current version. Run the script below and save the result as your baseline.
Step 4 · Change one thing at a time. Prompt, model, or step. Measure again and compare with the baseline.
Step 5 · Review the errors. The error list teaches you more than the number: ambiguous label, informal text, missing context.
Goal: measure the classifier from Topic 2 with a test set (evaluate.py).
# evaluate.py — save in the same folder as classifier.py (Topic 2)
from collections import Counter
from classificador import classificar
TESTE = [ # (text, correct label) — replace with 30+ real, anonymized examples
("My order has been stuck with the carrier for a week", "entrega"),
("The payment slip expired and I can't generate another one", "pagamento"),
("The T-shirt arrived with an open seam", "produto"),
("Excellent service, they resolved it in minutes", "elogio"),
("Are you open on the holiday?", "outro"),
("<real text>", "<correct label>"),
]
tp, fp, fn = Counter(), Counter(), Counter()
erros = []
for texto, certo in TESTE:
previsto = classificar(texto)["rotulo"]
if previsto == certo:
tp[certo] += 1
else:
fp[previsto] += 1
fn[certo] += 1
erros.append((texto, certo, previsto))
total = len(TESTE)
acertos = sum(tp.values())
print(f"accuracy: {acertos}/{total} = {acertos / total:.0%}")
for r in sorted({c for _, c in TESTE}):
prec = tp[r] / (tp[r] + fp[r]) if tp[r] + fp[r] else 0.0
rev = tp[r] / (tp[r] + fn[r]) if tp[r] + fn[r] else 0.0
print(f"{r:10s} precision={prec:.2f} recall={rev:.2f}")
for texto, certo, previsto in erros:
print(f"ERROR expected={certo:10s} got={previsto:10s} | {texto}")
How to check: run python3 avaliar.py (delete the example line with < > first). You should see the accuracy, one line per label, and the error list. Change the prompt in classifier.py, run it again, and compare: if accuracy improves but one label gets worse, the change isn’t a complete win.
💡 Tip
Keep the test set in the repository alongside the code. In Module 2.8, it becomes an automatic gate: no version goes to production if its result falls below the baseline.
Why learn
Without a test set, every prompt adjustment is a guess and every model switch is a risk. With one, you can switch to a cheaper model knowing how much quality you lose, prove the improvement to your team, and catch errors before they reach customers.
Key concepts
✅ Module summary
Next module:
2.8 — MLOps and Production 🛠️