In-Context Learning
Used by SupervisedTermExtractor with method="llm". The model is reached through an LLM client, and the default "knn" selection of demonstrations needs the optional transformers extra for its sentence encoder.
llm
INSTRUCTIONS = ('Identify the terms in the following text.', 'Extract the terms from the following text.', 'Find the domain-specific terms in the following text.', 'Identify the words or phrases that are relevant to the underlying domain of the input text.')
module-attribute
The task instructions of Banerjee et al. (2024).
MARKERS = (('Input:', 'Output:'), ('Text:', 'Terminology:'))
module-attribute
The markers of the input text and of its terms of Banerjee et al. (2024).
TEMPLATES = tuple((instruction, *markers) for instruction in INSTRUCTIONS for markers in MARKERS)
module-attribute
The eight prompt templates of Banerjee et al. (2024, Table 4.3 of Banerjee, 2025), as
(instruction, input marker, output marker): template 1 is TEMPLATES[0]. Each
instruction is paired with each pair of markers.
SELECTIONS = ('knn', 'random')
module-attribute
The ways of choosing the demonstrations of each prompt.
NO_TERMS = 'None'
module-attribute
The answer of a demonstration without terms.
SENTENCE = re.compile('\\S(?:.*?\\S)?(?=\\s*$|(?<=[.!?])\\s)', re.DOTALL)
module-attribute
A sentence of plain text: up to a ".", "!" or "?" followed by whitespace.
PIECE = re.compile(f'{WORD.pattern}|[^\\w\\s]')
module-attribute
A word or punctuation mark of a term written by the model.
BULLET = re.compile('^(?:[-*•]+|\\d+[.)])\\s+')
module-attribute
A list marker before a term.
STRIP = ' \t"\'`“”‘’.:;!?'
module-attribute
Characters stripped from both ends of a term written by the model.
ABBREVIATION = re.compile('(.+?)\\s+\\((.+)\\)')
module-attribute
A term followed by its abbreviation in brackets, as in "hazard ratio (HR)".
Sentence(text, words, lemmas=None, offset=0)
dataclass
A sentence, with the offsets of its words within it.
offset = 0
class-attribute
instance-attribute
The offset of the sentence in its document.
words_as_written()
The words of the sentence.
term(first, last)
The term made of words first to last - 1, by their lemmas if any.
LLMTermExtractor(client=None, k=5, template=5, selection='knn', encoder=None, n=10, random_state=None, n_jobs=None, stopwords='english', words_layer=None, lemma_layer=None, terms_layer=GOLD_LAYER, sentences_layer=None)
Term extraction by in-context learning with a large language model, as in Banerjee et al. (2024).
Each sentence is sent to the model in a prompt with k training sentences and their
terms, the demonstrations, and the model answers with the terms of the sentence.
The demonstrations are the training sentences most similar to it (Liu et al., 2022)
or a random sample of them.
Initialize the extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Union[LLMClient, str]
|
The model: an |
None
|
k
|
int
|
The number of demonstrations in each prompt; 0 asks the model without examples. |
5
|
template
|
Union[int, Tuple[str, str, str]]
|
The number of a template of
|
5
|
selection
|
str
|
"knn" for the training sentences most similar to each sentence, by the cosine of their embeddings, with the most similar last, or "random" for a random sample of them. |
'knn'
|
encoder
|
Optional[Encoder]
|
The sentence encoder of "knn", or None for
|
None
|
n
|
int
|
Drop terms of more than this many words. |
10
|
random_state
|
Optional[int]
|
Seed of the "random" selection. |
None
|
n_jobs
|
Optional[int]
|
The number of prompts sent at once, -1 for one per CPU, or None for one. |
None
|
stopwords
|
Union[str, Iterable[str], None]
|
Drop terms that start or end
with a stopword, as for |
'english'
|
words_layer
|
Optional[str]
|
For Teanga input, the span layer holding the
words, or None for |
None
|
lemma_layer
|
Optional[str]
|
For Teanga input, a sequence layer holding the lemma of each word, to give each term by its lemmas and match labels to them, or None to give terms as written. |
None
|
terms_layer
|
str
|
For Teanga input without labels, the span layer of the gold terms to take the demonstrations from. |
GOLD_LAYER
|
sentences_layer
|
Optional[str]
|
For Teanga input, the span layer of the
sentences, or None for |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If there is no client, or the template, |
fit_strings(corpus, labels)
Take the demonstrations from a list of strings, each sentence with the terms labelled 1 that it contains.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
List[str]
|
List of text documents. |
required |
labels
|
Dict[str, int]
|
Dictionary with terms as keys and binary labels as values. |
required |
fit_teanga(corpus, labels=None)
Take the demonstrations from a Teanga corpus, each sentence with its gold terms or with the terms labelled 1 that it contains.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Corpus
|
Teanga corpus object. |
required |
labels
|
Optional[Dict[str, int]]
|
Dictionary with terms as keys and binary
labels as values, or None for the gold terms of |
None
|
predict_strings(corpus)
Extract the terms of a list of strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
List[str]
|
List of text documents. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ATEResults |
ATEResults
|
The terms found in each document, each scoring 1.0. |
predict_teanga(corpus)
Extract the terms of a Teanga corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Corpus
|
Teanga corpus object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ATEResults |
ATEResults
|
The terms found in each document, each scoring 1.0, with the |
ATEResults
|
offsets of each occurrence the model found. |
prompts(sentences)
Write the prompt of each sentence, with its demonstrations.
A training sentence is never a demonstration for itself, so that the terms of the training corpus can be extracted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sentences
|
List[Sentence]
|
The sentences. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: The prompt of each sentence. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the extractor has not been trained. |
string_sentences(text)
Split plain text into sentences, after each ".", "!" or "?" followed by whitespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text. |
required |
Returns:
| Type | Description |
|---|---|
list[Sentence]
|
List[Sentence]: The sentences that have words. |
split_teanga(corpus, words_layer=None, sentences_layer=None, lemma_layer=None)
Split each document of a Teanga corpus into sentences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Corpus
|
The Teanga corpus. |
required |
words_layer
|
Optional[str]
|
The span layer holding the words, or None for
|
None
|
sentences_layer
|
Optional[str]
|
The span layer of the sentences, or None for
|
None
|
lemma_layer
|
Optional[str]
|
A sequence layer holding the lemma of each word, or None. |
None
|
Returns:
| Type | Description |
|---|---|
list[list[Sentence]]
|
List[List[Sentence]]: The sentences of each document. |
gold_spans(corpus, documents, terms_layer=GOLD_LAYER)
Get the gold terms of each sentence from split_teanga.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Corpus
|
The Teanga corpus. |
required |
documents
|
List[List[Sentence]]
|
Its sentences, from |
required |
terms_layer
|
str
|
The span layer of the gold terms. |
GOLD_LAYER
|
Returns:
| Type | Description |
|---|---|
list[list[list[tuple[int, int]]]]
|
List[List[List[Tuple[int, int]]]]: For each sentence of each document, the |
list[list[list[tuple[int, int]]]]
|
offsets within it of the gold terms that start in it, in order. |
labelled_spans(sentence, terms, n)
Find the labelled terms in a sentence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sentence
|
Sentence
|
The sentence. |
required |
terms
|
Set[str]
|
The terms, normalised as by |
required |
n
|
int
|
The maximum number of words of a term. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
List[Tuple[int, int]]: The offsets within the sentence of each run of up to |
list[tuple[int, int]]
|
words that is a term. |
make_prompt(template, demonstrations, text)
Write the prompt for a sentence: the instruction, each demonstration with its terms, and the sentence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
Tuple[str, str, str]
|
The instruction, the input marker and the
output marker, as in |
required |
demonstrations
|
Iterable[Tuple[str, List[str]]]
|
Example sentences, each with its terms. |
required |
text
|
str
|
The sentence to find the terms of. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The prompt. |
parse_answer(answer, template)
Read the terms from a model's answer.
The terms are split at commas or, if there are none, at newlines and semicolons. Anything after the input marker, where the model starts a new example, is ignored, as is "None". A term followed by its abbreviation in brackets, as in "hazard ratio (HR)", gives the term and the abbreviation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
answer
|
str
|
The answer. |
required |
template
|
Tuple[str, str, str]
|
The template of the prompt. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: The terms, as written, without duplicates. |
unbracket(term)
Strip a bracket from either end of a term if it has no partner, or a pair of brackets around the whole term.
find_term(sentence, term)
Find a term written by the model in a sentence, ignoring case and spacing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sentence
|
Sentence
|
The sentence. |
required |
term
|
str
|
The term. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
List[Tuple[int, int]]: The index of the first word and of the word after the |
list[tuple[int, int]]
|
last of each occurrence that starts and ends at the edges of words. |