Frontiers/Natural Language for AI Agents

Lesson 6.53,004 words

Natural Language for AI Agents

Language is how agents acquire the knowledge already written down and how they communicate with the humans they serve. This lesson gives the classical AI account of language as a source of information: n-gram language models and the information-seeking tasks built on them — text classification, information retrieval (BM25, the inverted index, PageRank), and information extraction with finite-state templates and hidden Markov models.

╌╌╌╌

Two facts drive a rational agent toward language. First, most of what humans know is written down: over a trillion pages on the web, almost all of it in natural language, so an agent that wants to acquire knowledge must read the ambiguous, messy prose people actually write.1 Second, an agent that acts on our behalf has to communicate — take instructions, ask questions, report results — and the shared system of signs we use for that is language. Chapter 22 of AIMA treats the first (language as a source of information); Chapter 23 treats the second (language as communication). This lesson gives that classical account in one pass.

It is a classical account on purpose. The models here are n-gram counts, context-free grammars, and hidden Markov models — the tools AI had before the deep-learning turn. They are worth knowing exactly because they name the problems cleanly: what a language model is, what parsing computes, why translation is a search. The modern treatment of every one of these tasks, with neural networks and transformers, lives in the dedicated natural language processing subject; we link to the relevant lesson as each task comes up.

Language models: predicting the next symbol

A formal language like Python can be defined as a set of strings, generated by an exact grammar. Natural languages cannot be defined this way. Everyone agrees Not to be invited is sad is English, but grammaticality judgments blur at the edges, and the same string carries many meanings — He saw her duck is either a waterfowl or an act of evasion.2 So instead of a crisp membership test, a natural language model is a probability distribution over strings: rather than asking whether a string is in the language, we ask , how probable that sentence is.

The simplest such model works over characters. Writing for the probability of a sequence of characters, an n-gram model assumes each character depends only on the before it — a Markov chain of order . For a trigram model (),

The conditional table is estimated by counting: how often does each three-letter sequence appear in a corpus of text. The same machinery runs over words instead of characters; the only change is that the vocabulary jumps from ~100 symbols to tens of thousands, and we must reserve a symbol <UNK> for words never seen in training.

An n-gram model factors the probability of a sequence into a product of conditionals, each looking back a fixed window of symbols (a trigram, , shown). The Markov assumption is what makes the table finite.

What character models are good for. One clean task is language identification: given a text, which of English, German, Spanish, ... is it? Build a trigram model for each candidate language , then apply Bayes' rule to pick the most probable language given the text,

Computer systems do this with greater than 99% accuracy. The same character-level approach handles spelling correction, genre classification, and named-entity recognition, because it can associate a substring like ex with drug names and generalize to words it has never seen.

Smoothing

The trouble with counting is that a corpus is only a sample of the true distribution. Common sequences like th are well estimated (about 1.5% of English trigrams), but a legitimate sequence like ht (as in http) may have count zero in the training text, and a zero count assigns to any sentence containing it — clearly wrong. Smoothing reallocates a little probability mass to unseen sequences.3 The oldest fix is Laplace (add-one) smoothing; it works poorly. A backoff model does better: estimate n-gram counts, but for any sequence with a low or zero count, back off to the -gram. Linear interpolation blends the trigram, bigram, and unigram estimates,

with the mixing weights tuned on held-out data. A model is chosen by cross-validation and scored by perplexity, , the weighted average branching factor: a lower perplexity is a better model. All of this — n-gram counts, smoothing, perplexity — is developed with worked numbers in the NLP subject's n-gram language models lesson.

A bigram model on a toy corpus

For example, take a three-sentence corpus, each sentence wrapped in a start marker <s> and an end marker </s> so the model can score where a sentence begins and ends:

text
<s> the cat sat </s><s> the cat ran </s><s> the dog sat </s>

A bigram word model estimates by the maximum-likelihood count ratio . Tallying adjacent pairs gives the counts below; the context word runs down the left, the predicted word across the top.

thecatdogsatran</s>row total
<s>3000003
the0210003
cat0001102
dog0001001
sat0000022
ran0000011

Dividing each row by its total gives the conditional table: , , , , and the deterministic , . Now score the held-out sentence <s> the cat sat </s> as a product of conditionals:

The sentence has transitions, so its perplexity is — a model this confident on this sentence branches, on average, as if choosing among only ~1.3 words at each step.

Where a zero count kills the sentence, and interpolation rescues it

Now score a different held-out sentence, <s> the dog ran </s>. Every word is in the vocabulary, yet the bigram dog ran never occurred in training, so and

A single unseen bigram sets the whole product to zero and the perplexity to infinity — the model assigns zero probability to a reasonable sentence. Linear interpolation repairs this by blending the bigram estimate with a unigram estimate that is nonzero. With for the bigram and for the unigram (weights summing to 1), and the unigram over the 9 word tokens in the corpus,

which is small but positive, so the sentence probability is nonzero and its perplexity is finite. The mixing weight guarantees that any in-vocabulary word keeps a floor of probability even when its bigram was never seen.

Linear interpolation as a mixture. The bigram estimate P(ran given dog) is zero (unseen), but the unigram P(ran) is positive; the weighted blend lambda_2 * bigram + lambda_1 * unigram lands at a small nonzero value, so the sentence probability escapes zero.

Text classification

The first information-seeking task is text classification (also categorization): given a document, assign it to one of a fixed set of classes.4 Language identification was an instance; so is spam detection, where the classes are spam and ham (not-spam), and sentiment analysis, where a review is positive or negative. Spam detection is a supervised problem with a training set ready to hand: the spam folder supplies positive examples, the inbox supplies negative ones.

There are two complementary ways to frame it. In the language-modeling view, train one n-gram model on the spam folder and another on the inbox, then classify by Bayes' rule,

with the priors estimated by counting messages of each class. In the machine-learning view, represent the message as a feature vector and apply any classifier. The simplest representation is bag of words: features are the vocabulary words, values are their counts, and word order is discarded. Add the assumption that the features are conditionally independent given the class, and this becomes the naive Bayes model.

Naive Bayes for spam. Each word is a feature that depends only on the class; the class prior times the per-word likelihoods gives the posterior, and we pick the larger. The independence assumption is the "naive" part.

Classifying one message by hand

For example, suppose a training set of spam messages and ham messages gives the per-class word counts below, over a four-word vocabulary. is the total number of word tokens in class ; the maximum-likelihood likelihood of a word is . To keep any unseen word from zeroing the product, add-one (Laplace) smoothing uses with vocabulary size .

wordcount in spamcount in ham
free81
money62
meeting17
report510
total 2020

The priors are . Classify the new message free money meeting by comparing the posteriors up to the shared normalizer, i.e. comparing for each class:

Spam wins, against . Normalizing gives a posterior . The verdict tracks intuition: free and money pull hard toward spam, and meeting pulls toward ham, but not hard enough to overturn the other two. Notice that a single strongly-skewed word — had meeting appeared times in spam without smoothing — would have driven the spam score to exactly and forced a ham verdict on the strength of one absent word; the add-one floor is what keeps the decision to the product of evidence rather than its weakest link.

Feature choice matters more than the choice of algorithm: with enough training data, a good feature (a suspicious bigram, whether the message contains a URL, the sender's history) determines accuracy more than whether one runs naive Bayes, logistic regression, an SVM, or -nearest-neighbors — all of which reach the 98–99% range on spam, and above 99.9% with a careful feature set. Because spam is an adversarial task — spammers rewrite you deserve as yo,u d-eserve to dodge the filter — features must be updated continually. The naive Bayes classifier and its use in sentiment analysis are worked through in the NLP subject's naive Bayes and sentiment lesson.

Information retrieval

Information retrieval (IR) is the task of finding documents relevant to a user's information need — the job of a web search engine.5 An IR system has four parts: a corpus of documents, queries in some query language, a result set of documents judged relevant, and a presentation of that set, usually a ranked list.

The earliest systems used a Boolean keyword model: each word is a Boolean feature, and a query like [information AND retrieval] returns exactly the documents where the expression is true. This is simple but crude — relevance is a single bit, so there is no way to rank, and Boolean queries are unintuitive for ordinary users. Modern systems abandon it for scoring functions over word counts.

Scoring: TF-IDF and BM25

A scoring function takes a document and a query and returns a number; the highest-scoring documents rank first. Three factors set the weight of a query term:

  • Term frequency — how often term appears in document . A document that mentions farming often is more about farming.
  • Inverse document frequency — terms that appear in almost every document (like in) are uninformative and should count for little.
  • Document length — a very long document mentions everything; a short document that mentions all the query words is a better match.

The BM25 function, from the Okapi project and used in Lucene, combines all three:

where is the document length, the average length, the number of documents containing , and , are tuned constants. To avoid scoring every document, systems build an index ahead of time — for each vocabulary word, the hit list of documents that contain it — and only score documents in the intersection of the query words' hit lists.

An inverted index maps each term to its hit list of documents. A query intersects the hit lists of its terms, and only the surviving documents are scored by BM25 and ranked.

The intersection is what makes the index efficient. If the hit lists are stored sorted by document id, intersecting two lists of lengths and is a merge: walk two pointers forward, advancing whichever points to the smaller id, and emit a document only when both pointers agree. That is time, not the of comparing every pair, and for a rare-plus-common term combination one can do better still by galloping the short list's members through the long list with binary search, at . Either way the scorer touches only documents that contain every query word, so a two-word query against a billion-document web scores a few thousand candidates rather than a billion.

BM25 on two toy documents

Rank two short documents against the single-word query [farming]. Suppose the corpus has documents, the average length is words, and farming appears in of them. The two candidates:

  • : farming in Kansas grows corn — length , and farming occurs time.
  • : a -word paragraph that mentions farming times.

First the shared inverse document frequency, with the BM25 smoothing offsets:

Now the term-frequency factor with , . The length-normalization term is . For , , so , and

For , , so , and

So ranks first, to — its three mentions outweigh 's single mention even after is penalized for being longer than average. The penalty is real, though: had length normalization been switched off (), would score and would score , a much wider gap. Length normalization is precisely the term pulling the long document back toward the short, focused one.

Evaluation: precision and recall

How well is an IR system doing? Run it on a set of queries whose relevant documents are known, and count the four cells of the outcome table.

In result setNot in result set
Relevant3020
Not relevant1040

Precision is the fraction of returned documents that are actually relevant, here . Recall is the fraction of all relevant documents that were returned, here . On the web, recall is impractical to measure (no one can examine every page), so search engines report precision-at- such as P@10. The two trade off — returning everything gives recall but low precision — and the F1 score, the harmonic mean , summarizes both in one number. For this table,

closer to the smaller of the two (recall ) than the arithmetic mean would be — the harmonic mean penalizes a large gap between precision and recall, so a system cannot get a high F1 by sacrificing one for the other.

Counting words is not enough on the web, because the highest- page for IBM need not be IBM's home page. PageRank adds a signal from the link graph: a page is important if many important pages link to it.6 Each in-link is a vote, weighted by the voter's own rank, which makes the definition recursive but convergent:

where are the pages linking to , is the number of out-links on page , is the corpus size, and is a damping factor. It has an interpretation as the random surfer model: with probability a surfer follows a random link, and with probability jumps to a random page; is the long-run fraction of time spent at . PageRank is computed by iterating the equation to a fixed point.

Two iterations on a three-node web. Take the link graph , , , . Here , , so the teleport term is . The out-degrees are , , . Start from the uniform vector and apply the update. is linked from only; from only; from and :

Iteration 1, plugging the uniform start () into every right-hand term:

Iteration 2, feeding those values back in:

The ordering has already settled on and near the top with trailing, and further iterations converge toward the stationary distribution (about , , ). scores high because both other pages link to it; recovers because the one page that links to it, , is itself important — the recursion at work.

A three-node link graph for PageRank. Arrows are hyperlinks; each page splits its rank equally among its out-links. After two iterations from a uniform start (d = 0.85), C and A lead and B trails, matching PR(A) = 0.454, PR(B) = 0.192, PR(C) = 0.406.

The related HITS algorithm splits importance into hubs and authorities. When the query is a question and the desired output is a short answer rather than a ranked list, the task becomes question answering, covered in the NLP subject's question answering lesson.

Information extraction

Information extraction (IE) skims text for instances of a class of object and the relations among them — pulling structured records out of prose.7 A typical task is to read IBM ThinkBook 970. Our price: $399.00 and produce the attributes {Manufacturer = IBM, Model = ThinkBook970, Price = 399.00}. AIMA presents six approaches spanning deterministic to stochastic; two matter most.

Finite-state extraction

The simplest system is attribute-based: assume the whole text describes one object and pull out its attributes with a template — a regular expression per attribute. A price template pairs a target regex for a dollar amount with a prefix regex looking for price: nearby, on the idea that some clues come from the value itself and some from the surrounding text.

A finite-state template for prices: a prefix pattern locates the field, the target pattern captures the value. Each box is a regex fragment; matching left-to-right pulls the value out of running text.

Relational extraction goes one step up, recovering multiple objects and their relations. The FASTUS system reads corporate-merger news through cascaded finite-state transducers: a chain of small automata, each transducing the text into a richer format and passing it on. Its five stages are tokenization, complex-word handling, basic-group handling (chunking noun and verb groups), complex-phrase handling, and structure merging. Running the sentence Bridgestone Sports Co. said Friday it has set up a joint venture ... through the chunker yields a tagged sequence:

text
1  NG: Bridgestone Sports Co.    7  PR: in2  VG: said                      8  NG: Taiwan3  NG: Friday                    9  PR: with4  NG: it                       10  NG: a local concern5  VG: had set up               11  CJ: and6  NG: a joint venture          12  NG: a Japanese trading house

where NG is a noun group, VG a verb group, PR a preposition, and CJ a conjunction. Later stages combine these into a JointVenture record. Finite-state IE works well on restricted, regularly formatted domains — especially reverse-engineering text a program generated — and poorly on free human prose.

Probabilistic extraction with HMMs

When the input is noisy or varied, getting every rule and its priority right is hopeless, and a probabilistic model does better. The simplest is the hidden Markov model (HMM), the same temporal model used for reasoning over time. For extraction, the observations are the words of the text and the hidden states label whether each word is in the target, prefix, or postfix part of an attribute, or in the background. Running Viterbi finds the most probable labeling.

An HMM tags each word with a hidden role. Trained on talk announcements, it labels "Andrew McCallum" as the speaker's name; PRE and POST are the context words around the target, and dash is background.

HMMs beat finite-state templates on two counts: they are probabilistic, so a missing word degrades the match gracefully instead of failing outright, and their parameters can be learned from a corpus rather than hand-coded. Modern IE frames the same task as sequence labeling over semantic roles — the NLP subject's semantic roles and information extraction lesson carries it forward with neural taggers.

The tasks so far — classification, retrieval, extraction — treat text as a bag or a sequence of symbols and ask what it is about. None of them look at how the words are arranged: that black dog is well-formed English while dog black is not, because grammar is about structure, not adjacency. Capturing that structure, and using it to parse, translate, and transcribe, is the second half of the classical account. This continues in Language for AI Agents: Grammar, Translation, and Speech.

Footnotes

  1. AIMA, Ch. 22 — Natural Language Processing, chapter introduction: the two motivations for language processing (communication with humans and knowledge acquisition from written text) and the role of language models across information-seeking tasks.
  2. AIMA, §22.1 — Language Models: natural languages defined as probability distributions over strings rather than definitive sets, and the n-gram (Markov chain of order ) character and word models.
  3. AIMA, §22.1.2–22.1.3 — Smoothing and Model Evaluation: Laplace smoothing, backoff and linear-interpolation models, and perplexity as a task-independent measure of model quality.
  4. AIMA, §22.2 — Text Classification: spam detection and sentiment as supervised classification, the language-modeling versus machine-learning (bag-of-words / naive Bayes) framings, feature selection, and the adversarial nature of spam.
  5. AIMA, §22.3 — Information Retrieval: the IR problem's four components, the Boolean keyword model, the BM25 scoring function with TF, IDF, and length normalization, the inverted index, and precision/recall/F1 evaluation.
  6. AIMA, §22.3.4 — The PageRank algorithm: link analysis, the recursive PageRank equation, the damping factor, and the random-surfer interpretation; the HITS hubs-and-authorities variant.
  7. AIMA, §22.4 — Information Extraction: attribute-based and relational extraction with finite-state templates and cascaded transducers (FASTUS), and probabilistic extraction with hidden Markov models over target/prefix/postfix/background states.

╌╌ END ╌╌