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 LLM pipeline to support multiple framework methods. Closes #614. Closes #611. Closes #554

davidmezzetti6ce37d4cfc84
diff --git a/setup.py b/setup.py
index 15d344c6..d1fba20a 100644
--- a/setup.py
+++ b/setup.py
@@ -49,12 +49,19 @@ extras["pipeline-data"] = ["beautifulsoup4>=4.9.3", "nltk>=3.5", "pandas>=1.1.0"
extras["pipeline-image"] = ["imagehash>=4.2.1", "pillow>=7.1.2", "timm>=0.4.12"]
+extras["pipeline-llm"] = ["litellm>=1.12.0", "llama-cpp-python>=0.2.20"]
+
extras["pipeline-text"] = ["fasttext>=0.9.2", "sentencepiece>=0.1.91"]
extras["pipeline-train"] = ["accelerate>=0.19.0", "onnx>=1.11.0", "onnxmltools>=1.9.1", "onnxruntime>=1.11.0"]
extras["pipeline"] = (
- extras["pipeline-audio"] + extras["pipeline-data"] + extras["pipeline-image"] + extras["pipeline-text"] + extras["pipeline-train"]
+ extras["pipeline-audio"]
+ + extras["pipeline-data"]
+ + extras["pipeline-image"]
+ + extras["pipeline-llm"]
+ + extras["pipeline-text"]
+ + extras["pipeline-train"]
)
extras["similarity"] = [
diff --git a/src/python/txtai/pipeline/__init__.py b/src/python/txtai/pipeline/__init__.py
index cc9b3453..a2ea84eb 100644
--- a/src/python/txtai/pipeline/__init__.py
+++ b/src/python/txtai/pipeline/__init__.py
@@ -9,6 +9,7 @@ from .factory import PipelineFactory
from .hfmodel import HFModel
from .hfpipeline import HFPipeline
from .image import *
+from .llm import *
from .nop import Nop
from .text import *
from .tensors import Tensors
diff --git a/src/python/txtai/pipeline/llm/__init__.py b/src/python/txtai/pipeline/llm/__init__.py
new file mode 100644
index 00000000..64676e74
--- /dev/null
+++ b/src/python/txtai/pipeline/llm/__init__.py
@@ -0,0 +1,10 @@
+"""
+LLM imports
+"""
+
+from .factory import GenerationFactory
+from .generation import Generation
+from .huggingface import *
+from .litellm import LiteLLM
+from .llama import LlamaCpp
+from .llm import LLM
diff --git a/src/python/txtai/pipeline/llm/factory.py b/src/python/txtai/pipeline/llm/factory.py
new file mode 100644
index 00000000..50e9e0a1
--- /dev/null
+++ b/src/python/txtai/pipeline/llm/factory.py
@@ -0,0 +1,86 @@
+"""
+Factory module
+"""
+
+from ...util import Resolver
+
+from .huggingface import HFGeneration
+from .litellm import LiteLLM
+from .llama import LlamaCpp
+
+
+class GenerationFactory:
+ """
+ Methods to create generative models.
+ """
+
+ @staticmethod
+ def create(path, method, **kwargs):
+ """
+ Creates a new Generation instance.
+
+ Args:
+ path: model path
+ method: llm framework
+ kwargs: model keyword arguments
+ """
+
+ # Derive method
+ method = GenerationFactory.method(path, method)
+
+ # LiteLLM generation
+ if method == "litellm":
+ return LiteLLM(path, **kwargs)
+
+ # llama.cpp generation
+ if method == "llama.cpp":
+ return LlamaCpp(path, **kwargs)
+
+ # Hugging Face Transformers generation
+ if method == "transformers":
+ return HFGeneration(path, **kwargs)
+
+ # Resolve custom method
+ return GenerationFactory.resolve(path, method, **kwargs)
+
+ @staticmethod
+ def method(path, method):
+ """
+ Get or derives the LLM framework.
+
+ Args:
+ path: model path
+ method: llm framework
+
+ Return:
+ llm framework
+ """
+
+ if not method:
+ if LiteLLM.ismodel(path):
+ method = "litellm"
+ elif LlamaCpp.ismodel(path):
+ method = "llama.cpp"
+ else:
+ method = "transformers"
+
+ return method
+
+ @staticmethod
+ def resolve(path, method, **kwargs):
+ """
+ Attempt to resolve a custom LLM framework.
+
+ Args:
+ path: model path
+ method: llm framework
+ kwargs: model keyword arguments
+
+ Returns:
+ Generation instance
+ """
+
+ try:
+ return Resolver()(method)(path, **kwargs)
+ except Exception as e:
+ raise ImportError(f"Unable to resolve generation framework: '{method}'") from e
diff --git a/src/python/txtai/pipeline/llm/generation.py b/src/python/txtai/pipeline/llm/generation.py
new file mode 100644
index 00000000..4bae2933
--- /dev/null
+++ b/src/python/txtai/pipeline/llm/generation.py
@@ -0,0 +1,84 @@
+"""
+Generation module
+"""
+
+from ...util import TemplateFormatter
+
+
+class Generation:
+ """
+ Base class for generative models. This class has common logic for building prompts and cleaning model results.
+ """
+
+ def __init__(self, path=None, template=None, **kwargs):
+ """
+ Creates a new Generation instance.
+
+ Args:
+ path: model path
+ template: prompt template
+ kwargs: additional keyword arguments
+ """
+
+ self.path = path
+ self.template = template
+ self.kwargs = kwargs
+
+ def __call__(self, text, maxlength, **kwargs):
+ """
+ Generates text using input text
+
+ Args:
+ text: text|list
+ maxlength: maximum sequence length
+ kwargs: additional generation keyword arguments
+
+ Returns:
+ generated text
+ """
+
+ # List of texts
+ texts = text if isinstance(text, list) else [text]
+
+ # Apply template, if necessary
+ if self.template:
+ formatter = TemplateFormatter()
+ texts = [formatter.format(self.template, text=x) for x in texts]
+
+ # Run pipeline
+ results = self.execute(texts, maxlength, **kwargs)
+
+ # Clean generated text
+ results = [self.clean(texts[x], result) for x, result in enumerate(results)]
+
+ return results[0] if isinstance(text, str) else results
+
+ def execute(self, texts, maxlength, **kwargs):
+ """
+ Runs a list of prompts through a generative model.
+
+ Args:
+ texts: list of prompts to run
+ maxlength: maximum sequence length
+ kwargs: additional generation keyword arguments
+ """
+
+ raise NotImplementedError
+
+ def clean(self, prompt, result):
+ """
+ Applies a series of rules to clean generated text.
+
+ Args:
+ prompt: original input prompt
+ result: result text
+
+ Returns:
+ clean text
+ """
+
+ # Replace input prompt
+ text = result.replace(prompt, "")
+
+ # Apply text cleaning rules
+ return text.replace("$=", "<=").strip()
diff --git a/src/python/txtai/pipeline/text/llm.py b/src/python/txtai/pipeline/llm/huggingface.py
similarity index 56%
rename from src/python/txtai/pipeline/text/llm.py
rename to src/python/txtai/pipeline/llm/huggingface.py
index 0f704b67..e08e81ce 100644
--- a/src/python/txtai/pipeline/text/llm.py
+++ b/src/python/txtai/pipeline/llm/huggingface.py
@@ -1,28 +1,42 @@
"""
-LLM Module
+Hugging Face module
"""
from ...models import Models
-from ...util import TemplateFormatter
from ..hfpipeline import HFPipeline
+from .generation import Generation
-class LLM(HFPipeline):
+
+class HFGeneration(Generation):
+ """
+ Hugging Face Transformers generative model.
+ """
+
+ def __init__(self, path, template=None, **kwargs):
+ # Call parent constructor
+ super().__init__(path, template, **kwargs)
+
+ # Create HuggingFace LLM pipeline
+ self.llm = HFLLM(path, **kwargs)
+
+ def execute(self, texts, maxlength, **kwargs):
+ return self.llm(texts, maxlength=maxlength, **kwargs)
+
+
+class HFLLM(HFPipeline):
"""
- Runs prompts through a large language model (LLM). This pipeline autodetects if the model path is a text generation or
- sequence to sequence model.
+ Hugging Face Transformers large language model (LLM) pipeline. This pipeline autodetects if the model path
+ is a text generation or sequence to sequence model.
"""
- def __init__(self, path=None, quantize=False, gpu=True, model=None, task=None, template=None, **kwargs):
- super().__init__(self.task(path, task, **kwargs), path if path else "google/flan-t5-base", quantize, gpu, model, **kwargs)
+ def __init__(self, path=None, quantize=False, gpu=True, model=None, task=None, **kwargs):
+ super().__init__(self.task(path, task, **kwargs), path, quantize, gpu, model, **kwargs)
# Load tokenizer, if necessary
self.pipeline.tokenizer = self.pipeline.tokenizer if self.pipeline.tokenizer else Models.tokenizer(path, **kwargs)
- # Template to apply to all inputs. Must include a {text} parameter.
- self.template = template
-
def __call__(self, text, prefix=None, maxlength=512, workers=0, **kwargs):
"""
Generates text using input text
@@ -45,42 +59,28 @@ class LLM(HFPipeline):
if prefix:
texts = [f"{prefix}{x}" for x in texts]
- # Apply template, if necessary
- if self.template:
- formatter = TemplateFormatter()
- texts = [formatter.format(self.template, text=x) for x in texts]
-
# Run pipeline
results = self.pipeline(texts, max_length=maxlength, num_workers=workers, **kwargs)
- # Get generated text
- results = [self.clean(texts[x], result) for x, result in enumerate(results)]
+ # Extract generated text
+ results = [self.extract(result) for result in results]
return results[0] if isinstance(text, str) else results
- def clean(self, prompt, result):
+ def extract(self, result):
"""
- Applies a series of rules to clean generated text.
+ Extracts generated text from a pipeline result.
Args:
- prompt: original input prompt
- result: input result
+ result: pipeline result
Returns:
- clean text
+ generated text
"""
# Extract output from list, if necessary
result = result[0] if isinstance(result, list) else result
-
- # Get generated text field
- text = result["generated_text"]
-
- # Replace input prompt
- text = text.replace(prompt, "")
-
- # Apply text cleaning rules
- return text.replace("$=", "<=").strip()
+ return result["generated_text"]
def task(self, path, task, **kwargs):
"""
@@ -104,3 +104,21 @@ class LLM(HFPipeline):
# Map to Hugging Face task. Default to text2text-generation pipeline when task not resolved.
return mapping.get(task, "text2text-generation")
+
+
+class Generator(HFLLM):
+ """
+ Generate text with a causal language model.
+ """
+
+ def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
+ super().__init__(path, quantize, gpu, model, "language-generation", **kwargs)
+
+
+class Sequences(HFLLM):
+ """
+ Generate text with a sequence-sequence model.
+ """
+
+ def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
+ super().__init__(path, quantize, gpu, model, "sequence-sequence", **kwargs)
diff --git a/src/python/txtai/pipeline/llm/litellm.py b/src/python/txtai/pipeline/llm/litellm.py
new file mode 100644
index 00000000..992cf9ee
--- /dev/null
+++ b/src/python/txtai/pipeline/llm/litellm.py
@@ -0,0 +1,70 @@
+"""
+LiteLLM module
+"""
+
+import os
+import contextlib
+
+# Conditional import
+try:
+ import litellm as api
+
+ LITELLM = True
+except ImportError:
+ LITELLM = False
+
+from .generation import Generation
+
+
+class LiteLLM(Generation):
+ """
+ LiteLLM generative model.
+ """
+
+ @staticmethod
+ def ismodel(path):
+ """
+ Checks if path is a LiteLLM model.
+
+ Args:
+ path: input path
+
+ Returns:
+ True if this is a LiteLLM model, False otherwise
+ """
+
+ if isinstance(path, str) and LITELLM:
+ with open(os.devnull, "w", encoding="utf-8") as f, contextlib.redirect_stdout(f):
+ try:
+ return api.get_llm_provider(path)
+ except ValueError:
+ return False
+
+ return False
+
+ def __init__(self, path, template=None, **kwargs):
+ super().__init__(path, template, **kwargs)
+
+ if not LITELLM:
+ raise ImportError('LiteLLM is not available - install "llm" extra to enable')
+
+ # Register prompt template
+ self.register(path)
+
+ def execute(self, texts, maxlength, **kwargs):
+ results = []
+ for text in texts:
+ result = api.completion(model=self.path, messages=[{"content": text, "role": "user"}], max_tokens=maxlength, **{**kwargs, **self.kwargs})
+ results.append(result["choices"][0]["message"]["content"])
+
+ return results
+
+ def register(self, path):
+ """
+ Registers a custom prompt template for path.
+
+ Args:
+ path: model path
+ """
+
+ api.register_prompt_template(model=path, roles={"user": {"pre_message": "", "post_message": ""}})
diff --git a/src/python/txtai/pipeline/llm/llama.py b/src/python/txtai/pipeline/llm/llama.py
new file mode 100644
index 00000000..0d24b4ee
--- /dev/null
+++ b/src/python/txtai/pipeline/llm/llama.py
@@ -0,0 +1,77 @@
+"""
+Llama module
+"""
+
+import os
+
+from huggingface_hub import hf_hub_download
+
+# Conditional import
+try:
+ from llama_cpp import Llama
+
+ LLAMA_CPP = True
+except ImportError:
+ LLAMA_CPP = False
+
+from .generation import Generation
+
+
+class LlamaCpp(Generation):
+ """
+ llama.cpp generative model.
+ """
+
+ @staticmethod
+ def ismodel(path):
+ """
+ Checks if path is a llama.cpp model.
+
+ Args:
+ path: input path
+
+ Returns:
+ True if this is a llama.cpp model, False otherwise
+ """
+
+ return isinstance(path, str) and path.lower().endswith(".gguf")
+
+ def __init__(self, path, template=None, **kwargs):
+ super().__init__(path, template, **kwargs)
+
+ if not LLAMA_CPP:
+ raise ImportError('llama.cpp is not available - install "llm" extra to enable')
+
+ # Check if this is a local path, otherwise download from the HF Hub
+ path = path if os.path.exists(path) else self.download(path)
+
+ # Create llama.cpp instance
+ self.llm = Llama(path, verbose=kwargs.get("verbose", False), **kwargs)
+
+ def execute(self, texts, maxlength, **kwargs):
+ results = []
+ for text in texts:
+ result = self.llm(text, max_tokens=maxlength, **kwargs)
+ results.append(result["choices"][0]["text"])
+
+ return results
+
+ def download(self, path):
+ """
+ Downloads path from the Hugging Face Hub.
+
+ Args:
+ path: full model path
+
+ Returns:
+ local cached model path
+ """
+
+ # Split into parts
+ parts = path.split("/")
+
+ # Calculate repo id split
+ repo = 2 if len(parts) > 2 else 1
+
+ # Download and cache file
+ return hf_hub_download(repo_id="/".join(parts[:repo]), filename="/".join(parts[repo:]))
diff --git a/src/python/txtai/pipeline/llm/llm.py b/src/python/txtai/pipeline/llm/llm.py
new file mode 100644
index 00000000..232ebde0
--- /dev/null
+++ b/src/python/txtai/pipeline/llm/llm.py
@@ -0,0 +1,48 @@
+"""
+LLM module
+"""
+
+from .factory import GenerationFactory
+
+
+class LLM:
+ """
+ Pipeline for running large language models (LLMs). This class supports the following LLM backends:
+
+ - Local LLMs with Hugging Face Transformers
+ - Local LLMs with llama.cpp
+ - Remote API LLMs with LiteLLM
+ - Custom generation implementations
+ """
+
+ def __init__(self, path=None, method=None, **kwargs):
+ """
+ Creates a new LLM.
+
+ Args:
+ path: model path
+ method: llm model framework, infers from path if not provided
+ kwargs: model keyword arguments
+ """
+
+ # Default LLM if not provided
+ path = path if path else "google/flan-t5-base"
+
+ # Generation instance
+ self.generator = GenerationFactory.create(path, method, **kwargs)
+
+ def __call__(self, text, maxlength=512, **kwargs):
+ """
+ Generates text using input text
+
+ Args:
+ text: text|list
+ maxlength: maximum sequence length
+ kwargs: additional generation keyword arguments
+
+ Returns:
+ generated text
+ """
+
+ # Run LLM generation
+ return self.generator(text, maxlength, **kwargs)
diff --git a/src/python/txtai/pipeline/text/__init__.py b/src/python/txtai/pipeline/text/__init__.py
index c7b9f9fa..7b1f0738 100644
--- a/src/python/txtai/pipeline/text/__init__.py
+++ b/src/python/txtai/pipeline/text/__init__.py
@@ -5,11 +5,8 @@ Text imports
from .crossencoder import CrossEncoder
from .entity import Entity
from .extractor import Extractor
-from .generator import Generator
from .labels import Labels
-from .llm import LLM
from .questions import Questions
-from .sequences import Sequences
from .similarity import Similarity
from .summary import Summary
from .translation import Translation
diff --git a/src/python/txtai/pipeline/text/generator.py b/src/python/txtai/pipeline/text/generator.py
deleted file mode 100644
index 556105ba..00000000
--- a/src/python/txtai/pipeline/text/generator.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Generator module
-"""
-
-from .llm import LLM
-
-
-class Generator(LLM):
- """
- Generate text with a causal language model.
- """
-
- def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
- super().__init__(path, quantize, gpu, model, "language-generation", **kwargs)
diff --git a/src/python/txtai/pipeline/text/sequences.py b/src/python/txtai/pipeline/text/sequences.py
deleted file mode 100644
index 1425797d..00000000
--- a/src/python/txtai/pipeline/text/sequences.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Sequences module
-"""
-
-from .llm import LLM
-
-
-class Sequences(LLM):
- """
- Runs text through a sequence-sequence model.
- """
-
- def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
- super().__init__(path, quantize, gpu, model, "sequence-sequence", **kwargs)
diff --git a/test/python/testoptional.py b/test/python/testoptional.py
index 50e53b24..b726a2ee 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -28,9 +28,11 @@ class TestOptional(unittest.TestCase):
"fasttext",
"hnswlib",
"imagehash",
- "nltk",
"libcloud.storage.providers",
+ "litellm",
+ "llama_cpp",
"networkx",
+ "nltk",
"onnxmltools",
"onnxruntime",
"onnxruntime.quantization",
@@ -152,6 +154,8 @@ class TestOptional(unittest.TestCase):
Caption,
HFOnnx,
ImageHash,
+ LiteLLM,
+ LlamaCpp,
MLOnnx,
Objects,
Segmentation,
@@ -171,6 +175,12 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
ImageHash()
+ with self.assertRaises(ImportError):
+ LiteLLM("huggingface/t5-small")
+
+ with self.assertRaises(ImportError):
+ LlamaCpp("TheBloke/TinyLlama-1.1B-Chat-v0.3-GGUF/tinyllama-1.1b-chat-v0.3.Q2_K.gguf")
+
with self.assertRaises(ImportError):
MLOnnx()
diff --git a/test/python/testpipeline/testextractor.py b/test/python/testpipeline/testextractor.py
index 6df98c1e..5461214b 100644
--- a/test/python/testpipeline/testextractor.py
+++ b/test/python/testpipeline/testextractor.py
@@ -195,6 +195,14 @@ class TestExtractor(unittest.TestCase):
self.assertEqual(self.extractor.snippet(None, None), None)
+ def testStringInput(self):
+ """
+ Test extractor with single string input
+ """
+
+ result = self.extractor("How many home runs?", self.data)
+ self.assertEqual(result["answer"], "3")
+
def testTasks(self):
"""
Test loading models with task parameter
diff --git a/test/python/testpipeline/testlitellm.py b/test/python/testpipeline/testlitellm.py
new file mode 100644
index 00000000..a3ccd8fd
--- /dev/null
+++ b/test/python/testpipeline/testlitellm.py
@@ -0,0 +1,69 @@
+"""
+LiteLLM module tests
+"""
+
+import json
+import unittest
+
+from http.server import HTTPServer, BaseHTTPRequestHandler
+from threading import Thread
+
+from txtai.pipeline import LLM
+
+
+class RequestHandler(BaseHTTPRequestHandler):
+ """
+ Test HTTP handler.
+ """
+
+ def do_POST(self):
+ """
+ POST request handler.
+ """
+
+ # Generate mock response
+ response = [{"generated_text": "blue"}]
+ response = json.dumps(response).encode("utf-8")
+
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", len(response))
+ self.end_headers()
+
+ self.wfile.write(response)
+ self.wfile.flush()
+
+
+class TestLiteLLM(unittest.TestCase):
+ """
+ LiteLLM tests.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Create mock http server.
+ """
+
+ cls.httpd = HTTPServer(("127.0.0.1", 8000), RequestHandler)
+
+ server = Thread(target=cls.httpd.serve_forever)
+ server.setDaemon(True)
+ server.start()
+
+ @classmethod
+ def tearDownClass(cls):
+ """
+ Shutdown mock http server.
+ """
+
+ cls.httpd.shutdown()
+
+ def testGeneration(self):
+ """
+ Test generation with LiteLLM
+ """
+
+ # Test model generation with llama.cpp
+ model = LLM("huggingface/t5-small", api_base="http://127.0.0.1:8000")
+ self.assertEqual(model("The sky is"), "blue")
diff --git a/test/python/testpipeline/testllama.py b/test/python/testpipeline/testllama.py
new file mode 100644
index 00000000..f4318812
--- /dev/null
+++ b/test/python/testpipeline/testllama.py
@@ -0,0 +1,22 @@
+"""
+Llama module tests
+"""
+
+import unittest
+
+from txtai.pipeline import LLM
+
+
+class TestLlama(unittest.TestCase):
+ """
+ llama.cpp tests.
+ """
+
+ def testGeneration(self):
+ """
+ Test generation with llama.cpp
+ """
+
+ # Test model generation with llama.cpp
+ model = LLM("TheBloke/TinyLlama-1.1B-Chat-v0.3-GGUF/tinyllama-1.1b-chat-v0.3.Q2_K.gguf")
+ self.assertEqual(model("2 + 2 = ", maxlength=10, seed=0, stop=["."]), "4")
diff --git a/test/python/testpipeline/testllm.py b/test/python/testpipeline/testllm.py
index add96b2d..2b272bcd 100644
--- a/test/python/testpipeline/testllm.py
+++ b/test/python/testpipeline/testllm.py
@@ -8,7 +8,7 @@ import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
-from txtai.pipeline import LLM
+from txtai.pipeline import LLM, Generation
class TestLLM(unittest.TestCase):
@@ -30,6 +30,22 @@ class TestLLM(unittest.TestCase):
model = LLM("hf-internal-testing/tiny-random-gpt2", task="language-generation", torch_dtype=torch.float32)
self.assertIsNotNone(model(start))
+ def testCustom(self):
+ """
+ Test custom LLM framework
+ """
+
+ model = LLM("hf-internal-testing/tiny-random-gpt2", task="language-generation", method="txtai.pipeline.HFGeneration")
+ self.assertIsNotNone(model("Hello, how are"))
+
+ def testCustomNotFound(self):
+ """
+ Test resolving an unresolvable LLM framework
+ """
+
+ with self.assertRaises(ImportError):
+ LLM("hf-internal-testing/tiny-random-gpt2", method="notfound.generation")
+
def testExternal(self):
"""
Test externally loaded model
@@ -43,3 +59,11 @@ class TestLLM(unittest.TestCase):
# Test that text is generated
self.assertIsNotNone(model(start))
+
+ def testNotImplemented(self):
+ """
+ Test exceptions for non-implemented methods
+ """
+
+ generation = Generation()
+ self.assertRaises(NotImplementedError, generation.execute, None, None)