💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add support for similarity backed context in extractor pipelines, closes #119
davidmezzettiaefb12e1e134
diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.pyindex e7499d71..5f4a7644 100644--- a/src/python/txtai/api/base.py+++ b/src/python/txtai/api/base.py@@ -67,7 +67,7 @@ class API:# Custom pipeline parametersif pipeline == "extractor":- config["embeddings"] = self.embeddings+ config["similarity"] = self.embeddingselif pipeline == "similarity" and "path" not in config and "labels" in self.pipelines:config["model"] = self.pipelines["labels"]diff --git a/src/python/txtai/pipeline/extractor.py b/src/python/txtai/pipeline/extractor.pyindex e9d1c134..40fdf490 100644--- a/src/python/txtai/pipeline/extractor.py+++ b/src/python/txtai/pipeline/extractor.py@@ -4,6 +4,7 @@ Extractor modulefrom .base import Pipelinefrom .questions import Questions+from .similarity import Similarityfrom .tokenizer import Tokenizer@@ -12,12 +13,12 @@ class Extractor(Pipeline):Class that uses an extractive question-answering model to extract content from a given text context."""- def __init__(self, embeddings, path, quantize=False, gpu=False, model=None, tokenizer=None):+ def __init__(self, similarity, path, quantize=False, gpu=True, model=None, tokenizer=None, minscore=None, mintokens=None):"""Builds a new extractor.Args:- embeddings: embeddings model+ similarity: similarity instance (Embeddings or Similarity instance)path: path to qa modelquantize: True if model should be quantized before inference, False otherwise.gpu: if gpu inference should be used (only works if GPUs are available)@@ -25,8 +26,8 @@ class Extractor(Pipeline):tokenizer: Tokenizer class"""- # Embeddings model- self.embeddings = embeddings+ # Similarity instance+ self.similarity = similarity# QA Pipelineself.pipeline = Questions(path, quantize, gpu, model)@@ -34,6 +35,12 @@ class Extractor(Pipeline):# Tokenizer class use default method if not setself.tokenizer = tokenizer if tokenizer else Tokenizer+ # Minimum score to include context match+ self.minscore = minscore if minscore is not None else 0.0++ # Minimum number of tokens to include context match+ self.mintokens = mintokens if mintokens is not None else 0.0+def __call__(self, queue, texts):"""Extracts answers to input questions. This method runs queries against a list of text, finds the top n best matches@@ -97,14 +104,17 @@ class Extractor(Pipeline):must = [token.strip("+") for token in query.split() if token.startswith("+") and len(token) > 1]mnot = [token.strip("-") for token in query.split() if token.startswith("-") and len(token) > 1]- # Tokenize search query- query = self.tokenizer.tokenize(query)-# List of matchesmatches = []# Get list of (id, score) - sorted by highest score- scores = self.embeddings.similarity(query, tokenlist)+ if isinstance(self.similarity, Similarity):+ scores = self.similarity(query, [t for _, t in segments])+ else:+ # Assume this is an Embeddings instance, tokenize and run similarity query+ query = self.tokenizer.tokenize(query)+ scores = self.similarity.similarity(query, tokenlist)+for x, score in scores:# Get segment texttext = segments[x][1]@@ -112,10 +122,13 @@ class Extractor(Pipeline):# Add result if:# - all required tokens are present or there are not required tokens AND# - all prohibited tokens are not present or there are not prohibited tokens+ # - score is above minimum score required+ # - number of tokens is above minimum number of tokens requiredif (not must or all([token.lower() in text.lower() for token in must])) and (not mnot or all([token.lower() not in text.lower() for token in mnot])):- matches.append(segments[x] + (score,))+ if score >= self.minscore and len(tokenlist[x]) >= self.mintokens:+ matches.append(segments[x] + (score,))# Add query matches sorted by highest scoreresults.append(matches)diff --git a/test/python/testextractor.py b/test/python/testextractor.pyindex 9c25184c..d11890ed 100644--- a/test/python/testextractor.py+++ b/test/python/testextractor.py@@ -6,7 +6,7 @@ import platformimport unittestfrom txtai.embeddings import Embeddings-from txtai.pipeline import Extractor+from txtai.pipeline import Extractor, Similarityclass TestExtractor(unittest.TestCase):@@ -83,6 +83,19 @@ class TestExtractor(unittest.TestCase):answers = extractor([(question, question, question, True)], self.data)self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))+ def testSimilarity(self):+ """+ Test qa extraction using a Similarity pipeline to build context+ """++ # Create extractor instance+ extractor = Extractor(Similarity("prajjwal1/bert-medium-mnli"), "distilbert-base-cased-distilled-squad")++ question = "How many home runs?"++ answers = extractor([(question, "HRs", question, True)], self.data)+ self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))+def testSnippet(self):"""Test qa extraction with a full answer snippet