💡 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 LiteRT-LM LLM, closes #1095
davidmezzetti798ff2e0ed80
diff --git a/setup.py b/setup.pyindex e671cc59..6b0b2923 100644--- a/setup.py+++ b/setup.py@@ -100,7 +100,7 @@ extras["pipeline-data"] = ["beautifulsoup4>=4.9.3", "chonkie>=1.0.2", "docling>=extras["pipeline-image"] = ["imagehash>=4.2.1", "pillow>=7.1.2", "timm>=0.4.12"]-extras["pipeline-llm"] = ["httpx>=0.28.1", "litellm>=1.37.16", "llama-cpp-python>=0.2.75"]+extras["pipeline-llm"] = ["httpx>=0.28.1", "litert-lm-api>=0.11.0", "litellm>=1.37.16", "llama-cpp-python>=0.2.75"]extras["pipeline-text"] = ["gliner>=0.2.23", "sentencepiece>=0.1.91", "staticvectors>=0.2.0"]diff --git a/src/python/txtai/pipeline/llm/__init__.py b/src/python/txtai/pipeline/llm/__init__.pyindex 35974aac..3f8ba807 100644--- a/src/python/txtai/pipeline/llm/__init__.py+++ b/src/python/txtai/pipeline/llm/__init__.py@@ -6,6 +6,7 @@ from .factory import GenerationFactoryfrom .generation import Generationfrom .huggingface import *from .litellm import LiteLLM+from .litert import LiteRTfrom .llama import LlamaCppfrom .llm import LLMfrom .opencode import OpenCodediff --git a/src/python/txtai/pipeline/llm/factory.py b/src/python/txtai/pipeline/llm/factory.pyindex f89dce95..1f905759 100644--- a/src/python/txtai/pipeline/llm/factory.py+++ b/src/python/txtai/pipeline/llm/factory.py@@ -6,6 +6,7 @@ from ...util import Resolverfrom .huggingface import HFGenerationfrom .litellm import LiteLLM+from .litert import LiteRTfrom .llama import LlamaCppfrom .opencode import OpenCode@@ -33,6 +34,10 @@ class GenerationFactory:if method == "litellm":return LiteLLM(path, **kwargs)+ # LiteRT generation+ if method == "litert":+ return LiteRT(path, **kwargs)+# llama.cpp generationif method == "llama.cpp":return LlamaCpp(path, **kwargs)@@ -64,6 +69,8 @@ class GenerationFactory:if not method:if LiteLLM.ismodel(path):method = "litellm"+ elif LiteRT.ismodel(path):+ method = "litert"elif LlamaCpp.ismodel(path):method = "llama.cpp"elif OpenCode.ismodel(path):diff --git a/src/python/txtai/pipeline/llm/litert.py b/src/python/txtai/pipeline/llm/litert.pynew file mode 100644index 00000000..7bee25e9--- /dev/null+++ b/src/python/txtai/pipeline/llm/litert.py@@ -0,0 +1,92 @@+"""+LiteRT module+"""++import os++# Conditional import+try:+ import litert_lm++ LITERT = True+except ImportError:+ LITERT = False++from .generation import Generation++from ...util import Download+++class LiteRT(Generation):+ """+ LiteRT generative model.+ """++ @staticmethod+ def ismodel(path):+ """+ Checks if path is a LiteRT model.++ Args:+ path: input path++ Returns:+ True if this is a LiteRT model, False otherwise+ """++ return isinstance(path, str) and path.lower().endswith(".litertlm")++ def __init__(self, path, template=None, **kwargs):+ super().__init__(path, template, **kwargs)++ if not LITERT:+ raise ImportError('LiteRT is not available - install "pipeline" extra to enable')++ # Set log level+ litert_lm.set_min_log_severity(litert_lm.LogSeverity.INFO if kwargs.get("verbose") else litert_lm.LogSeverity.ERROR)++ # Check if this is a local path, otherwise download from the HF Hub+ path = path if os.path.exists(path) else Download()(path)++ # Create the engine+ self.engine = self.createengine(path, **kwargs)++ def stream(self, texts, maxlength, stream, stop, **kwargs):+ for message in texts:+ # LiteRT only takes the last message and needs the rest as input to the conversation+ queue, message = (message[:-1], message[-1]) if len(message) > 1 else (None, message[0])++ with self.engine.create_conversation(messages=queue) as conversation:+ # LLM inference+ yield from self.response(conversation.send_message_async(message) if stream else [conversation.send_message(message)])++ def response(self, result):+ for chunk in result:+ for item in chunk.get("content", []):+ if item.get("type") == "text":+ yield item["text"]++ def createengine(self, path, **kwargs):+ """+ Creates a new LiteRT engine.++ Args:+ path: model path+ kwargs: additional keyword args+ """++ # pylint: disable=W0702+ try:+ # GPU Backend enabled+ gpu = kwargs.get("gpu", True)++ return litert_lm.Engine(+ path,+ backend=litert_lm.Backend.GPU if gpu else litert_lm.Backend.CPU,+ enable_speculative_decoding=gpu,+ max_num_tokens=kwargs.get("maxlength"),+ )++ except:+ # Fallback to CPU backend+ return litert_lm.Engine(path, backend=litert_lm.Backend.CPU)diff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 062c2f85..bf4af69d 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -40,6 +40,7 @@ class TestOptional(unittest.TestCase):"imagehash","libcloud.storage.providers","litellm",+ "litert_lm","llama_cpp","model2vec","msgpack",@@ -233,6 +234,7 @@ class TestOptional(unittest.TestCase):HTMLToMarkdown,ImageHash,LiteLLM,+ LiteRT,LlamaCpp,Microphone,MLOnnx,@@ -279,6 +281,9 @@ class TestOptional(unittest.TestCase):with self.assertRaises(ImportError):LiteLLM("huggingface/t5-small")+ with self.assertRaises(ImportError):+ LiteRT("litert-community/SmolLM2-360M-Instruct/SmolLM2_360M_instruct.litertlm")+with self.assertRaises(ImportError):LlamaCpp("TheBloke/TinyLlama-1.1B-Chat-v0.3-GGUF/tinyllama-1.1b-chat-v0.3.Q2_K.gguf")diff --git a/test/python/testpipeline/testllm/testlitert.py b/test/python/testpipeline/testllm/testlitert.pynew file mode 100644index 00000000..eaff5bc3--- /dev/null+++ b/test/python/testpipeline/testllm/testlitert.py@@ -0,0 +1,27 @@+"""+LiteRT module tests+"""++import unittest++from txtai.pipeline import LLM+++class TestLiteRT(unittest.TestCase):+ """+ LiteRT tests.+ """++ def testGeneration(self):+ """+ Test generation with LiteRT+ """++ # Test model generation with LiteRT+ model = LLM("litert-community/SmolLM2-360M-Instruct/SmolLM2_360M_instruct.litertlm")++ # Test standard+ self.assertIsNotNone(model("Hello"))++ # Test streaming+ self.assertIsNotNone(list(model("Hello", stream=True)))