Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Full txtai API support, closes #41

davidmezzetticd104886189e
diff --git a/src/python/txtai/api.py b/src/python/txtai/api.py
index 431ea0fe..e21065b4 100644
--- a/src/python/txtai/api.py
+++ b/src/python/txtai/api.py
@@ -8,34 +8,51 @@ from typing import List
import yaml
-from fastapi import FastAPI, Query, Request
+from fastapi import Body, FastAPI, Request
from .embeddings import Embeddings
+from .extractor import Extractor
+from .labels import Labels
# API instance
app = FastAPI()
-# Embeddings index instance
-INDEX = None
+# Global API instance
+INSTANCE = None
class API(object):
"""
Base API template. Downstream applications can extend this base template to add custom search functionality.
"""
- def __init__(self, index):
+ def __init__(self, config):
"""
Creates an embeddings index instance that is called by FastAPI.
Args:
- index: index configuration
+ config: index configuration
"""
- # Store index settings
- self.index = index
+ # Initialize member variables
+ self.config, self.documents, self.embeddings, self.extractor, self.labels = config, None, None, None, None
- self.embeddings = Embeddings()
- self.embeddings.load(self.index["path"])
+ # Create/load embeddings index depending on writable flag
+ if self.config.get("writable"):
+ self.embeddings = Embeddings(self.config["embeddings"])
+ elif self.config.get("path"):
+ self.embeddings = Embeddings()
+ self.embeddings.load(self.config["path"])
+
+ # Create extractor instance
+ if "extractor" in self.config:
+ # Extractor settings
+ extractor = self.config["extractor"]
+
+ self.extractor = Extractor(self.embeddings, extractor["path"], extractor.get("quantize"))
+
+ # Create labels instance
+ if "labels" in self.config:
+ self.labels = Labels()
def size(self, request):
"""
@@ -64,21 +81,64 @@ class API(object):
list of (uid, score)
"""
- return self.embeddings.search(query, self.size(request))
+ if self.embeddings:
+ return self.embeddings.search(query, self.size(request))
- def similarity(self, text1, text2):
+ return None
+
+ def add(self, documents):
+ """
+ Adds a batch of documents for indexing.
+
+ Args:
+ documents: list of {id: value, text: value}
+ """
+
+ # Only add batch if index is marked writable
+ if self.config.get("writable"):
+ # Create current batch if necessary
+ if not self.documents:
+ self.documents = []
+
+ # Add batch
+ self.documents.extend([(document["id"], document["text"], None) for document in documents])
+
+ def index(self):
+ """
+ Builds an embeddings index. No further documents can be added after this call. Downstream applications can
+ override this method to also store full documents in an external system.
+ """
+
+ if self.config.get("writable") and self.documents:
+ # Build scoring index if scoring method provided
+ if self.config.get("scoring"):
+ embeddings.score(self.documents)
+
+ # Build embeddings index
+ self.embeddings.index(self.documents)
+
+ # Save index
+ self.embeddings.save(self.config["path"])
+
+ # Clear buffer
+ self.documents = None
+
+ def similarity(self, search, data):
"""
Calculates the similarity between text1 and list of elements in text2.
Args:
- text1: text
- text2: list of text to compare against
+ search: text
+ data: list of text to compare against
Returns:
list of similarity scores
"""
- return [float(x) for x in self.embeddings.similarity(text1, text2)]
+ if self.embeddings:
+ return [float(x) for x in self.embeddings.similarity(search, data)]
+
+ return None
def transform(self, text):
"""
@@ -91,7 +151,47 @@ class API(object):
embeddings array
"""
- return [float(x) for x in self.embeddings.transform((None, text, None))]
+ if self.embeddings:
+ return [float(x) for x in self.embeddings.transform((None, text, None))]
+
+ return None
+
+ def extract(self, documents, queue):
+ """
+ Extracts answers to input questions
+
+ Args:
+ documents: list of {id: value, text: value}
+ queue: list of {name: value, query: value, question: value, snippet: value)
+
+ Returns:
+ extracted answers
+ """
+
+ # Convert to a list of (id, text)
+ sections = [(document["id"], document["text"]) for document in documents]
+
+ # Convert queue to tuples
+ queue = [(x["name"], x["query"], x.get("question"), x.get("snippet")) for x in queue]
+
+ return self.extractor(sections, queue)
+
+ def label(self, text, labels):
+ """
+ Applies a zero shot classifier to a text section using a list of labels.
+
+ Args:
+ text: input text
+ labels: list of labels
+
+ Returns:
+ list of (label, score) for section
+ """
+
+ if self.labels:
+ return self.labels(text, labels)
+
+ return None
class Factory(object):
"""
@@ -112,7 +212,7 @@ class Factory(object):
parts = atype.split('.')
module = ".".join(parts[:-1])
- m = __import__( module )
+ m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
@@ -125,16 +225,16 @@ def start():
"""
# pylint: disable=W0603
- global INDEX
+ global INSTANCE
# Load YAML settings
- with open(os.getenv("INDEX_SETTINGS"), "r") as f:
+ with open(os.getenv("CONFIG"), "r") as f:
# Read configuration
- index = yaml.safe_load(f)
+ config = yaml.safe_load(f)
- # Instantiate API class
+ # Instantiate API instance
api = os.getenv("API_CLASS")
- INDEX = Factory.get(api)(index) if api else API(index)
+ INSTANCE = Factory.get(api)(config) if api else API(config)
@app.get("/search")
def search(q: str, request: Request):
@@ -149,22 +249,41 @@ def search(q: str, request: Request):
query results
"""
- return INDEX.search(q, request)
+ return INSTANCE.search(q, request)
+
+def add(documents: List[dict]):
+ """
+ Adds a batch of documents for indexing.
+
+ Args:
+ documents: list of dicts with each entry containing an id and text element
+ """
+
+ INSTANCE.add(documents)
+
+def index():
+ """
+ Builds an index for previously batched documents.
+ """
+
+ INSTANCE.index()
[email protected]("/similarity")
-def similarity(t1: str, t2: List[str]=Query(None)):
[email protected]("/similarity")
+def similarity(search: str = Body(None), data: List[str] = Body(None)):
"""
Calculates the similarity between text1 and list of elements in text2.
Args:
- t1: text
- t2: list of text to compare against
+ search: search text
+ data: list of text to compare against
Returns:
list of similarity scores
"""
- return INDEX.similarity(t1, t2)
+ return INSTANCE.similarity(search, data)
@app.get("/embeddings")
def embeddings(t: str):
@@ -178,4 +297,34 @@ def embeddings(t: str):
embeddings array
"""
- return INDEX.transform(t)
+ return INSTANCE.transform(t)
+
[email protected]("/extract")
+def extract(documents: List[dict], queue: List[dict]):
+ """
+ Extracts answers to input questions
+
+ Args:
+ documents: list of {id: value, text: value}
+ queue: list of {name: value, query: value, question: value, snippet: value)
+
+ Returns:
+ extracted answers
+ """
+
+ return INSTANCE.extract(documents, queue)
+
+def label(text: str = Body(None), labels: List[str] = Body(None)):
+ """
+ Applies a zero shot classifier to a text section using a list of labels.
+
+ Args:
+ text: input text
+ labels: list of labels
+
+ Returns:
+ list of (label, score) for section
+ """
+
+ return INSTANCE.label(text, labels)