Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Refactor API code into smaller components #63

davidmezzetti8544d2eb3610
diff --git a/src/python/txtai/api/__init__.py b/src/python/txtai/api/__init__.py
new file mode 100644
index 00000000..b3715b22
--- /dev/null
+++ b/src/python/txtai/api/__init__.py
@@ -0,0 +1,7 @@
+"""
+API imports
+"""
+
+from .application import app, start
+from .base import API
+from .factory import Factory
diff --git a/src/python/txtai/api/application.py b/src/python/txtai/api/application.py
new file mode 100644
index 00000000..b4e1d187
--- /dev/null
+++ b/src/python/txtai/api/application.py
@@ -0,0 +1,214 @@
+"""
+FastAPI application module
+"""
+
+import os
+
+from typing import List
+
+import yaml
+
+from fastapi import Body, FastAPI, Request
+
+from .base import API
+from .factory import Factory
+
+# API instance
+app = FastAPI()
+
+# Global API instance
+INSTANCE = None
+
+
[email protected]_event("startup")
+def start():
+ """
+ FastAPI startup event. Pre-loads embeddings index.
+ """
+
+ # pylint: disable=W0603
+ global INSTANCE
+
+ # Load YAML settings
+ with open(os.getenv("CONFIG"), "r") as f:
+ # Read configuration
+ config = yaml.safe_load(f)
+
+ # Instantiate API instance
+ api = os.getenv("API_CLASS")
+ INSTANCE = Factory.get(api)(config) if api else API(config)
+
+
+def search(query: str, request: Request):
+ """
+ Finds documents in the embeddings model most similar to the input query. Returns
+ a list of {id: value, score: value} sorted by highest score, where id is the
+ document id in the embeddings model.
+
+ Args:
+ query: query text
+ request: FastAPI request
+
+ Returns:
+ list of {id: value, score: value}
+ """
+
+ return INSTANCE.search(query, request)
+
+
[email protected]("/batchsearch")
+def batchsearch(queries: List[str] = Body(...), limit: int = Body(...)):
+ """
+ Finds documents in the embeddings model most similar to the input queries. Returns
+ a list of {id: value, score: value} sorted by highest score per query, where id is
+ the document id in the embeddings model.
+
+ Args:
+ queries: queries text
+ limit: maximum results
+
+ Returns:
+ list of {id: value, score: value} per query
+ """
+
+ return INSTANCE.batchsearch(queries, limit)
+
+
+def add(documents: List[dict] = Body(...)):
+ """
+ Adds a batch of documents for indexing.
+
+ Args:
+ documents: list of {id: value, text: value}
+ """
+
+ INSTANCE.add(documents)
+
+
+def index():
+ """
+ Builds an embeddings index for previously batched documents. No further documents can be added
+ after this call.
+ """
+
+ INSTANCE.index()
+
+
[email protected]("/similarity")
+def similarity(query: str = Body(...), texts: List[str] = Body(...)):
+ """
+ Computes the similarity between query and list of text. Returns a list of
+ {id: value, score: value} sorted by highest score, where id is the index
+ in texts.
+
+ Args:
+ query: query text
+ texts: list of text
+
+ Returns:
+ list of {id: value, score: value}
+ """
+
+ return INSTANCE.similarity(query, texts)
+
+
[email protected]("/batchsimilarity")
+def batchsimilarity(queries: List[str] = Body(...), texts: List[str] = Body(...)):
+ """
+ Computes the similarity between list of queries and list of text. Returns a list
+ of {id: value, score: value} sorted by highest score per query, where id is the
+ index in texts.
+
+ Args:
+ queries: queries text
+ texts: list of text
+
+ Returns:
+ list of {id: value, score: value} per query
+ """
+
+ return INSTANCE.batchsimilarity(queries, texts)
+
+
[email protected]("/transform")
+def transform(text: str):
+ """
+ Transforms text into an embeddings array.
+
+ Args:
+ text: input text
+
+ Returns:
+ embeddings array
+ """
+
+ return INSTANCE.transform(text)
+
+
[email protected]("/batchtransform")
+def batchtransform(texts: List[str] = Body(...)):
+ """
+ Transforms list of text into embeddings arrays.
+
+ Args:
+ texts: list of text
+
+ Returns:
+ embeddings arrays
+ """
+
+ return INSTANCE.batchtransform(texts)
+
+
[email protected]("/extract")
+def extract(queue: List[dict] = Body(...), texts: List[str] = Body(...)):
+ """
+ Extracts answers to input questions.
+
+ Args:
+ queue: list of {name: value, query: value, question: value, snippet: value}
+ texts: list of text
+
+ Returns:
+ list of {name: value, answer: value}
+ """
+
+ return INSTANCE.extract(queue, texts)
+
+
+def label(text: str = Body(...), labels: List[str] = Body(...)):
+ """
+ Applies a zero shot classifier to text using a list of labels. Returns a list of
+ {id: value, score: value} sorted by highest score, where id is the index in labels.
+
+ Args:
+ text: input text
+ labels: list of labels
+
+ Returns:
+ list of {id: value, score: value} per text element
+ """
+
+ return INSTANCE.label(text, labels)
+
+
[email protected]("/batchlabel")
+def batchlabel(texts: List[str] = Body(...), labels: List[str] = Body(...)):
+ """
+ Applies a zero shot classifier to list of text using a list of labels. Returns a list of
+ {id: value, score: value} sorted by highest score, where id is the index in labels per
+ text element.
+
+ Args:
+ texts: list of text
+ labels: list of labels
+
+ Returns:
+ list of {id: value score: value} per text element
+ """
+
+ return INSTANCE.label(texts, labels)
diff --git a/src/python/txtai/api.py b/src/python/txtai/api/base.py
similarity index 64%
rename from src/python/txtai/api.py
rename to src/python/txtai/api/base.py
index a3bd7a24..d5fc9c22 100644
--- a/src/python/txtai/api.py
+++ b/src/python/txtai/api/base.py
@@ -6,20 +6,8 @@ import os
import pickle
import tempfile
-from typing import List
-
-import yaml
-
-from fastapi import Body, FastAPI, Request
-
-from .embeddings import Embeddings
-from .pipeline import Extractor, Labels, Similarity
-
-# API instance
-app = FastAPI()
-
-# Global API instance
-INSTANCE = None
+from ..embeddings import Embeddings
+from ..pipeline import Extractor, Labels, Similarity
class API:
@@ -305,223 +293,3 @@ class API:
return [[{"id": uid, "score": float(score)} for uid, score in result] for result in self.labels(text, labels)]
return None
-
-
-class Factory:
- """
- API factory. Creates new API instances.
- """
-
- @staticmethod
- def get(atype):
- """
- Gets a new instance of atype.
-
- Args:
- atype: API instance class
-
- Returns:
- instance of atype
- """
-
- parts = atype.split(".")
- module = ".".join(parts[:-1])
- m = __import__(module)
- for comp in parts[1:]:
- m = getattr(m, comp)
-
- return m
-
-
[email protected]_event("startup")
-def start():
- """
- FastAPI startup event. Pre-loads embeddings index.
- """
-
- # pylint: disable=W0603
- global INSTANCE
-
- # Load YAML settings
- with open(os.getenv("CONFIG"), "r") as f:
- # Read configuration
- config = yaml.safe_load(f)
-
- # Instantiate API instance
- api = os.getenv("API_CLASS")
- INSTANCE = Factory.get(api)(config) if api else API(config)
-
-
-def search(query: str, request: Request):
- """
- Finds documents in the embeddings model most similar to the input query. Returns
- a list of {id: value, score: value} sorted by highest score, where id is the
- document id in the embeddings model.
-
- Args:
- query: query text
- request: FastAPI request
-
- Returns:
- list of {id: value, score: value}
- """
-
- return INSTANCE.search(query, request)
-
-
[email protected]("/batchsearch")
-def batchsearch(queries: List[str] = Body(...), limit: int = Body(...)):
- """
- Finds documents in the embeddings model most similar to the input queries. Returns
- a list of {id: value, score: value} sorted by highest score per query, where id is
- the document id in the embeddings model.
-
- Args:
- queries: queries text
- limit: maximum results
-
- Returns:
- list of {id: value, score: value} per query
- """
-
- return INSTANCE.batchsearch(queries, limit)
-
-
-def add(documents: List[dict] = Body(...)):
- """
- Adds a batch of documents for indexing.
-
- Args:
- documents: list of {id: value, text: value}
- """
-
- INSTANCE.add(documents)
-
-
-def index():
- """
- Builds an embeddings index for previously batched documents. No further documents can be added
- after this call.
- """
-
- INSTANCE.index()
-
-
[email protected]("/similarity")
-def similarity(query: str = Body(...), texts: List[str] = Body(...)):
- """
- Computes the similarity between query and list of text. Returns a list of
- {id: value, score: value} sorted by highest score, where id is the index
- in texts.
-
- Args:
- query: query text
- texts: list of text
-
- Returns:
- list of {id: value, score: value}
- """
-
- return INSTANCE.similarity(query, texts)
-
-
[email protected]("/batchsimilarity")
-def batchsimilarity(queries: List[str] = Body(...), texts: List[str] = Body(...)):
- """
- Computes the similarity between list of queries and list of text. Returns a list
- of {id: value, score: value} sorted by highest score per query, where id is the
- index in texts.
-
- Args:
- queries: queries text
- texts: list of text
-
- Returns:
- list of {id: value, score: value} per query
- """
-
- return INSTANCE.batchsimilarity(queries, texts)
-
-
[email protected]("/transform")
-def transform(text: str):
- """
- Transforms text into an embeddings array.
-
- Args:
- text: input text
-
- Returns:
- embeddings array
- """
-
- return INSTANCE.transform(text)
-
-
[email protected]("/batchtransform")
-def batchtransform(texts: List[str] = Body(...)):
- """
- Transforms list of text into embeddings arrays.
-
- Args:
- texts: list of text
-
- Returns:
- embeddings arrays
- """
-
- return INSTANCE.batchtransform(texts)
-
-
[email protected]("/extract")
-def extract(queue: List[dict] = Body(...), texts: List[str] = Body(...)):
- """
- Extracts answers to input questions.
-
- Args:
- queue: list of {name: value, query: value, question: value, snippet: value}
- texts: list of text
-
- Returns:
- list of {name: value, answer: value}
- """
-
- return INSTANCE.extract(queue, texts)
-
-
-def label(text: str = Body(...), labels: List[str] = Body(...)):
- """
- Applies a zero shot classifier to text using a list of labels. Returns a list of
- {id: value, score: value} sorted by highest score, where id is the index in labels.
-
- Args:
- text: input text
- labels: list of labels
-
- Returns:
- list of {id: value, score: value} per text element
- """
-
- return INSTANCE.label(text, labels)
-
-
[email protected]("/batchlabel")
-def batchlabel(texts: List[str] = Body(...), labels: List[str] = Body(...)):
- """
- Applies a zero shot classifier to list of text using a list of labels. Returns a list of
- {id: value, score: value} sorted by highest score, where id is the index in labels per
- text element.
-
- Args:
- texts: list of text
- labels: list of labels
-
- Returns:
- list of {id: value score: value} per text element
- """
-
- return INSTANCE.label(texts, labels)
diff --git a/src/python/txtai/api/factory.py b/src/python/txtai/api/factory.py
new file mode 100644
index 00000000..766b6883
--- /dev/null
+++ b/src/python/txtai/api/factory.py
@@ -0,0 +1,29 @@
+"""
+API factory module
+"""
+
+
+class Factory:
+ """
+ API factory. Creates new API instances.
+ """
+
+ @staticmethod
+ def get(atype):
+ """
+ Gets a new instance of atype.
+
+ Args:
+ atype: API instance class
+
+ Returns:
+ instance of atype
+ """
+
+ parts = atype.split(".")
+ module = ".".join(parts[:-1])
+ m = __import__(module)
+ for comp in parts[1:]:
+ m = getattr(m, comp)
+
+ return m