Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Add new LLM default parameters, closes #998. Closes #999.

davidmezzetti75c4f54f63eb
diff --git a/docs/faq.md b/docs/faq.md
index 8b4df4ac..ec560985 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -72,7 +72,7 @@ from txtai import LLM
path = "Qwen/Qwen3-0.6B"
model = AutoModelForCausalLM.from_pretrained(
path,
- torch_dtype=torch.bfloat16,
+ dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(path)
diff --git a/docs/observability.md b/docs/observability.md
index a05b2524..29e13228 100644
--- a/docs/observability.md
+++ b/docs/observability.md
@@ -94,7 +94,7 @@ with mlflow.start_run():
context=10
)
- rag("Tell me about the Roman Empire", maxlength=2048, stripthink=True)
+ rag("Tell me about the Roman Empire", maxlength=2048)
```
![rag](https://raw.githubusercontent.com/neuml/mlflow-txtai/master/images/rag.png)
@@ -156,7 +156,7 @@ embeddings.load(provider="huggingface-hub", container="neuml/txtai-astronomy")
agent = Agent(
tools=[search],
llm="Qwen/Qwen3-4B-Instruct-2507",
- max_iterations=10,
+ max_steps=10,
)
researcher = """
diff --git a/docs/pipeline/text/llm.md b/docs/pipeline/text/llm.md
index 5f629247..384e0a4b 100644
--- a/docs/pipeline/text/llm.md
+++ b/docs/pipeline/text/llm.md
@@ -29,8 +29,8 @@ llm(
"""
)
-# Instruction tuned models typically require string prompts to
-# follow a specific chat template set by the model
+# Prompts with chat templating can be directly passed
+# The template format varies by model
llm(
"""
<|im_start|>system
@@ -47,9 +47,15 @@ llm([
{"role": "user", "content": "Answer the following question..."}
])
-# When there is no system prompt passed to instruction tuned models,
-# `defaultrole="user"` must be set for string inputs
+# When there is no system prompt passed to instruction tuned models
+# the default role is inferred `defaultrole="auto"`
+llm("Answer the following question...")
+
+# To always generate chat messages for string inputs
llm("Answer the following question...", defaultrole="user")
+
+# To never generate chat messages for string inputs
+llm("Answer the following question...", defaultrole="prompt")
```
The LLM pipeline automatically detects the underlying LLM framework. This can also be manually set.
@@ -98,7 +104,7 @@ from txtai import LLM
path = "Qwen/Qwen3-0.6B"
model = AutoModelForCausalLM.from_pretrained(
path,
- torch_dtype=torch.bfloat16,
+ dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(path)
@@ -151,7 +157,7 @@ Similar to the Python example above, the underlying [Hugging Face pipeline param
```yaml
llm:
path: Qwen/Qwen3-0.6B
- torch_dtype: torch.bfloat16
+ dtype: torch.bfloat16
```
### Run with Workflows
diff --git a/docs/pipeline/text/rag.md b/docs/pipeline/text/rag.md
index 25a6e5a6..da27508a 100644
--- a/docs/pipeline/text/rag.md
+++ b/docs/pipeline/text/rag.md
@@ -42,14 +42,10 @@ rag = RAG(embeddings, "Qwen/Qwen3-0.6B", template="""
""")
# Run RAG pipeline
-# LLM options can be passed as additional arguments
-# - When there is no system prompt passed to instruction tuned models,
-# `defaultrole="user"` must be set for string prompts
-# - Thinking text is removed when `stripthink=True`
-rag("What was won?", defaultrole="user", stripthink=True)
+rag("What was won?")
-# Instruction tuned models require string prompts to
-# follow a specific chat template set by the model
+# Prompts with chat templating can be directly passed
+# The template format varies by model
rag = RAG(embeddings, "Qwen/Qwen3-0.6B", template="""
<|im_start|>system
You are a friendly assistant.<|im_end|>
@@ -64,7 +60,7 @@ rag = RAG(embeddings, "Qwen/Qwen3-0.6B", template="""
<|im_start|>assistant
"""
)
-rag("What was won?", stripthink=True)
+rag("What was won?")
# Inputs are automatically converted to chat messages when a
# system prompt is provided
@@ -81,7 +77,13 @@ rag = RAG(
Context:
{context}
""")
-rag("What was won?", stripthink=True)
+rag("What was won?")
+
+# LLM options can be passed as additional arguments
+# - Streaming RAG response with `stream=True`
+# - String inputs are always converted to user messages with `defaultrole="user"`
+# - Thinking text is removed with `stripthink=True`
+rag("What was won?", stream=True, defaultrole="user", stripThink=True)
```
See the [Embeddings](../../../embeddings) and [LLM](../llm) pages for additional configuration options.
@@ -137,8 +139,6 @@ rag:
Context:
{context}
- defaultrole: user
- stripthink: True
workflow:
search:
diff --git a/src/python/txtai/pipeline/llm/generation.py b/src/python/txtai/pipeline/llm/generation.py
index 562f59d9..6bd49977 100644
--- a/src/python/txtai/pipeline/llm/generation.py
+++ b/src/python/txtai/pipeline/llm/generation.py
@@ -28,7 +28,7 @@ class Generation:
def __call__(self, text, maxlength, stream, stop, defaultrole, stripthink, **kwargs):
"""
- Generates text. Supports the following input formats:
+ Generates content. Supports the following input formats:
- String or list of strings (instruction-tuned models must follow chat templates)
- List of dictionaries with `role` and `content` key-values or lists of lists
@@ -38,12 +38,12 @@ class Generation:
maxlength: maximum sequence length
stream: stream response if True, defaults to False
stop: list of stop strings
- defaultrole: default role to apply to text inputs (prompt for raw prompts (default) or user for user chat messages)
- stripthink: strip thinking text, defaults to False
+ defaultrole: default role to apply to text inputs (`auto` to infer (default), `user` for user chat messages or `prompt` for raw prompts)
+ stripthink: strip thinking tags, defaults to False if stream is enabled, True otherwise
kwargs: additional generation keyword arguments
Returns:
- generated text
+ generated content
"""
# Format inputs
@@ -54,26 +54,32 @@ class Generation:
formatter = TemplateFormatter()
texts = [formatter.format(self.template, text=x) if isinstance(x, str) else x for x in texts]
- # Apply default role, if necessary
- if defaultrole == "user":
- texts = [[{"role": "user", "content": x}] if isinstance(x, str) else x for x in texts]
-
# Run pipeline
- results = self.execute(texts, maxlength, stream, stop, **kwargs)
+ results = self.execute(self.format(texts, defaultrole), maxlength, stream, stop, **kwargs)
# Streaming generation
if stream:
return self.cleanstream(results) if stripthink else results
- # Clean generated text
+ # Clean generated content
results = [self.clean(texts[x], result, stripthink) for x, result in enumerate(results)]
# Extract results based on inputs
return results[0] if isinstance(text, str) or isinstance(text[0], dict) else results
+ def ischat(self):
+ """
+ Returns True if this LLM supports chat.
+
+ Returns:
+ True if this a chat model
+ """
+
+ return True
+
def isvision(self):
"""
- Returns True if this LLM supports vision operations.
+ Returns True if this LLM supports vision.
Returns:
True if this is a vision model
@@ -81,6 +87,38 @@ class Generation:
return False
+ def format(self, texts, defaultrole):
+ """
+ Formats inputs for LLM inference. This method handles wrapping string inputs as chat messages using the following rules.
+
+ - defaultrole == "user" OR
+ - defaultrole == "auto" AND model supports chat AND text doesn't start with an instruction token
+
+ Args:
+ texts: list of inputs
+ defaultrole: default role to apply to text inputs (`auto` to infer (default), `user` for user chat messages or `prompt` for raw prompts)
+
+ Returns:
+ inputs ready for inference
+ """
+
+ # Instruction tokens
+ instruct = ("<|im_start|>", "<|start|>", "<|start_of_role|>", "[INST]")
+
+ results = []
+ for text in texts:
+ # Format chat messages using following rules
+ # - defaultrole == "user"
+ # - defaultrole == "auto" and text doesn't start with a instruction token
+ if isinstance(text, str) and (
+ defaultrole == "user" or (defaultrole == "auto" and self.ischat() and not text.strip().startswith(instruct))
+ ):
+ text = [{"role": "user", "content": text}]
+
+ results.append(text)
+
+ return results
+
def execute(self, texts, maxlength, stream, stop, **kwargs):
"""
Runs a list of prompts through a generative model.
@@ -93,7 +131,7 @@ class Generation:
kwargs: additional generation keyword arguments
Returns:
- generated text
+ generated content
"""
# Streaming generation
@@ -105,7 +143,7 @@ class Generation:
def clean(self, prompt, result, stripthink):
"""
- Applies a series of rules to clean generated text.
+ Applies a series of rules to clean generated content.
Args:
prompt: original input prompt
@@ -113,7 +151,7 @@ class Generation:
stripthink: removes thinking text if true
Returns:
- clean text
+ clean content
"""
# Replace input prompt
@@ -143,7 +181,7 @@ class Generation:
break
# Yield remaining tokens
- yield from text
+ yield from text.lstrip()
yield from results
def cleanthink(self, text):
diff --git a/src/python/txtai/pipeline/llm/huggingface.py b/src/python/txtai/pipeline/llm/huggingface.py
index 1f43a648..1eadd9df 100644
--- a/src/python/txtai/pipeline/llm/huggingface.py
+++ b/src/python/txtai/pipeline/llm/huggingface.py
@@ -25,8 +25,11 @@ class HFGeneration(Generation):
# Create HuggingFace LLM pipeline
self.llm = HFLLM(path, **kwargs)
+ def ischat(self):
+ return self.llm.ischat()
+
def isvision(self):
- return isinstance(self.llm.pipeline.model, AutoModelForImageTextToText)
+ return self.llm.isvision()
def stream(self, texts, maxlength, stream, stop, **kwargs):
yield from self.llm(texts, maxlength=maxlength, stream=stream, stop=stop, **kwargs)
@@ -46,7 +49,7 @@ class HFLLM(HFPipeline):
def __call__(self, text, prefix=None, maxlength=512, workers=0, stream=False, stop=None, **kwargs):
"""
- Generates text. Supports the following input formats:
+ Generates content. Supports the following input formats:
- String or list of strings (instruction-tuned models must follow chat templates)
- List of dictionaries with `role` and `content` key-values or lists of lists
@@ -61,7 +64,7 @@ class HFLLM(HFPipeline):
kwargs: additional generation keyword arguments
Returns:
- generated text
+ generated content
"""
# List of texts
@@ -83,6 +86,26 @@ class HFLLM(HFPipeline):
return results[0] if isinstance(text, str) else results
+ def ischat(self):
+ """
+ Returns True if this model supports chat.
+
+ Returns:
+ True if this a chat model
+ """
+
+ return self.pipeline.tokenizer.chat_template is not None
+
+ def isvision(self):
+ """
+ Returns True if this model supports vision.
+
+ Returns:
+ True if this is a vision model
+ """
+
+ return isinstance(self.pipeline.model, AutoModelForImageTextToText)
+
def parameters(self, texts, maxlength, workers, stop, **kwargs):
"""
Builds a list of arguments and a combined parameter dictionary to use as keyword arguments.
@@ -134,13 +157,13 @@ class HFLLM(HFPipeline):
def extract(self, result):
"""
- Extracts generated text from a pipeline result.
+ Extracts generated content from a pipeline result.
Args:
result: pipeline result
Returns:
- generated text
+ generated content
"""
# Extract output from list, if necessary
@@ -174,7 +197,7 @@ class HFLLM(HFPipeline):
class Generator(HFLLM):
"""
- Generate text with a causal language model.
+ Generates content with a causal language model.
"""
def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
@@ -183,7 +206,7 @@ class Generator(HFLLM):
class Sequences(HFLLM):
"""
- Generate text with a sequence-sequence model.
+ Generates content with a sequence-sequence model.
"""
def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
@@ -192,7 +215,7 @@ class Sequences(HFLLM):
class StreamingResponse:
"""
- Generate text as a streaming response.
+ Generates content as a streaming response.
"""
def __init__(self, pipeline, texts, stop, **kwargs):
diff --git a/src/python/txtai/pipeline/llm/llama.py b/src/python/txtai/pipeline/llm/llama.py
index 2328fd0a..7e20cfaa 100644
--- a/src/python/txtai/pipeline/llm/llama.py
+++ b/src/python/txtai/pipeline/llm/llama.py
@@ -121,7 +121,7 @@ class LlamaCpp(Generation):
kwargs: additional generation keyword arguments
Returns:
- generated text
+ generated content
"""
# LLM call with messages
@@ -142,7 +142,7 @@ class LlamaCpp(Generation):
kwargs: additional generation keyword arguments
Returns:
- generated text
+ generated content
"""
# LLM call with prompt
diff --git a/src/python/txtai/pipeline/llm/llm.py b/src/python/txtai/pipeline/llm/llm.py
index 40728434..a4364b11 100644
--- a/src/python/txtai/pipeline/llm/llm.py
+++ b/src/python/txtai/pipeline/llm/llm.py
@@ -33,14 +33,14 @@ class LLM(Pipeline):
"""
# Default LLM if not provided
- path = path if path else "google/flan-t5-base"
+ path = path if path else "ibm-granite/granite-4.0-350m"
# Generation instance
self.generator = GenerationFactory.create(path, method, **kwargs)
- def __call__(self, text, maxlength=512, stream=False, stop=None, defaultrole="prompt", stripthink=False, **kwargs):
+ def __call__(self, text, maxlength=512, stream=False, stop=None, defaultrole="auto", stripthink=None, **kwargs):
"""
- Generates text. Supports the following input formats:
+ Generates content. Supports the following input formats:
- String or list of strings (instruction-tuned models must follow chat templates)
- List of dictionaries with `role` and `content` key-values or lists of lists
@@ -50,20 +50,33 @@ class LLM(Pipeline):
maxlength: maximum sequence length
stream: stream response if True, defaults to False
stop: list of stop strings, defaults to None
- defaultrole: default role to apply to text inputs (prompt for raw prompts (default) or user for user chat messages)
- stripthink: strip thinking tags, defaults to False
+ defaultrole: default role to apply to text inputs (`auto` to infer (default), `user` for user chat messages or `prompt` for raw prompts)
+ stripthink: strip thinking tags, defaults to False if stream is enabled, True otherwise
kwargs: additional generation keyword arguments
Returns:
- generated text
+ generated content
"""
# Debug logging
logger.debug(text)
+ # Default stripthink to False when streaming, True otherwise
+ stripthink = not stream if stripthink is None else stripthink
+
# Run LLM generation
return self.generator(text, maxlength, stream, stop, defaultrole, stripthink, **kwargs)
+ def ischat(self):
+ """
+ Returns True if this LLM supports chat.
+
+ Returns:
+ True if this a chat model
+ """
+
+ return self.generator.ischat()
+
def isvision(self):
"""
Returns True if this LLM supports vision operations.
diff --git a/test/python/testpipeline/testllm/testllama.py b/test/python/testpipeline/testllm/testllama.py
index 4d5361b8..79636a31 100644
--- a/test/python/testpipeline/testllm/testllama.py
+++ b/test/python/testpipeline/testllm/testllama.py
@@ -63,7 +63,7 @@ class TestLlama(unittest.TestCase):
model = LLM("TheBloke/TinyLlama-1.1B-Chat-v0.3-GGUF/tinyllama-1.1b-chat-v0.3.Q2_K.gguf", chat_format="chatml")
# Test with prompt
- self.assertEqual(model("2 + 2 = ", maxlength=10, seed=0, stop=["."])[0], "4")
+ self.assertEqual(model("2 + 2 = ", maxlength=10, seed=0, stop=["."], defaultrole="prompt")[0], "4")
# Test with list of messages
messages = [{"role": "system", "content": "You are a helpful assistant. You answer math problems."}, {"role": "user", "content": "2+2?"}]
@@ -73,4 +73,4 @@ class TestLlama(unittest.TestCase):
self.assertIsNotNone(model("2 + 2 = ", maxlength=10, seed=0, stop=["."], defaultrole="user"))
# Test streaming
- self.assertEqual(" ".join(x for x in model("2 + 2 = ", maxlength=10, stream=True, seed=0, stop=["."]))[0], "4")
+ self.assertEqual(" ".join(x for x in model("2 + 2 = ", maxlength=10, stream=True, seed=0, stop=["."], defaultrole="prompt"))[0], "4")
diff --git a/test/python/testpipeline/testllm/testllm.py b/test/python/testpipeline/testllm/testllm.py
index 5ae31a28..bc86122f 100644
--- a/test/python/testpipeline/testllm/testllm.py
+++ b/test/python/testpipeline/testllm/testllm.py
@@ -27,10 +27,10 @@ class TestLLM(unittest.TestCase):
start = "Hello, how are"
# Test that text is generated with custom parameters
- model = LLM("hf-internal-testing/tiny-random-gpt2", task="language-generation", torch_dtype="torch.float32")
+ model = LLM("hf-internal-testing/tiny-random-gpt2", task="language-generation", dtype="torch.float32")
self.assertIsNotNone(model(start))
- model = LLM("hf-internal-testing/tiny-random-gpt2", task="language-generation", torch_dtype=torch.float32)
+ model = LLM("hf-internal-testing/tiny-random-gpt2", task="language-generation", dtype=torch.float32)
self.assertIsNotNone(model(start))
def testBatchSize(self):
@@ -63,7 +63,27 @@ class TestLLM(unittest.TestCase):
"""
model = LLM("hf-internal-testing/tiny-random-LlamaForCausalLM")
- self.assertIsNotNone(model("Hello, how are", defaultrole="user"))
+ generator = model.generator
+
+ # Validate that the LLM supports chat messages
+ self.assertEqual(model.ischat(), True)
+
+ messages = [
+ ("<|start|>Hello<|end|>", str),
+ ("Hello", list),
+ ("\n<|im_start|>Hello<|im_end|>", str),
+ ("[INST]Hello[/INST]", str),
+ ]
+
+ for message, expected in messages:
+ # Test auto detection of formats
+ self.assertEqual(type(generator.format([message], "auto")[0]), expected)
+
+ # Test always setting user chat messages
+ self.assertEqual(type(generator.format([message], "user")[0]), list)
+
+ # Test always keeping as prompt text
+ self.assertEqual(type(generator.format([message], "prompt")[0]), str)
def testExternal(self):
"""
@@ -129,6 +149,7 @@ class TestLLM(unittest.TestCase):
# Override execute method
model.generator.execute = method
self.assertEqual(model("Hello, how are", stripthink=True), "you")
+ self.assertEqual(model("Hello, how are", stripthink=False), method()[0])
def testStripThinkStream(self):
"""
@@ -148,6 +169,7 @@ class TestLLM(unittest.TestCase):
# Override execute method
model.generator.execute = method
self.assertEqual("".join(model("Hello, how are", stripthink=True, stream=True)), "you")
+ self.assertEqual("".join(model("Hello, how are", stripthink=False, stream=True)), "".join(list(method())))
def testVision(self):
"""