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 streaming LLM support, closes #680

davidmezzettidd1067c8776c
diff --git a/examples/rag.py b/examples/rag.py
index 69498231..e3b60a83 100644
--- a/examples/rag.py
+++ b/examples/rag.py
@@ -32,16 +32,14 @@ class Application:
# Load LLM
self.llm = LLM(os.environ.get("LLM", "TheBloke/Mistral-7B-OpenOrca-AWQ"))
- self.template = """<|im_start|>system
-You are a friendly assistant. You answer questions from users.<|im_end|>
-<|im_start|>user
+ # Prompts
+ self.system = "You are a friendly assistant. You answer questions from users."
+ self.template = """
Answer the following question using only the context below. Only include information
specifically discussed.
question: {question}
-context: {context} <|im_end|>
-<|im_start|>assistant
-"""
+context: {context} """
def run(self):
"""
@@ -60,13 +58,12 @@ context: {context} <|im_end|>
if st.session_state.messages and st.session_state.messages[-1]["role"] != "assistant":
with st.chat_message("assistant"):
- with st.spinner("Researching..."):
- # Run RAG
- response = self.rag(question)
+ # Run RAG
+ response = self.rag(question)
- # Render response
- st.write(response)
- st.session_state.messages.append({"role": "assistant", "content": response})
+ # Render response
+ response = st.write_stream(response)
+ st.session_state.messages.append({"role": "assistant", "content": response})
def rag(self, question):
"""
@@ -82,12 +79,15 @@ context: {context} <|im_end|>
# Generate context
context = "\n".join([x["text"] for x in self.embeddings.search(question)])
- # Build prompt
- prompt = self.template.format(question=question, context=context)
- logger.debug(prompt)
+ # Build prompt text
+ text = self.template.format(question=question, context=context)
+ logger.debug(text)
+
+ # Build prompts
+ prompts = [{"role": "system", "content": self.system}, {"role": "user", "content": text}]
# Run RAG
- return self.llm(prompt, maxlength=2048)
+ return self.llm(prompts, maxlength=2048, stream=True)
@st.cache_resource(show_spinner="Downloading models...")
diff --git a/src/python/txtai/api/routers/llm.py b/src/python/txtai/api/routers/llm.py
index ed65ceca..2d2a1a0c 100644
--- a/src/python/txtai/api/routers/llm.py
+++ b/src/python/txtai/api/routers/llm.py
@@ -5,6 +5,7 @@ Defines API paths for llm endpoints.
from typing import List, Optional
from fastapi import APIRouter, Body
+from fastapi.responses import StreamingResponse
from .. import application
from ..route import EncodingAPIRoute
@@ -13,34 +14,48 @@ router = APIRouter(route_class=EncodingAPIRoute)
@router.get("/llm")
-def llm(text: str, maxlength: Optional[int] = None):
+def llm(text: str, maxlength: Optional[int] = None, stream: Optional[bool] = False):
"""
Runs a LLM pipeline for the input text.
Args:
text: input text
maxlength: optional response max length
+ stream: streams response if True
Returns:
response text
"""
- kwargs = {"maxlength": maxlength} if maxlength else {}
- return application.get().pipeline("llm", text, **kwargs)
+ # Build keyword arguments
+ kwargs = {key: value for key, value in [("stream", stream), ("maxlength", maxlength)] if value}
+
+ # Run pipeline
+ result = application.get().pipeline("llm", text, **kwargs)
+
+ # Handle both standard and streaming responses
+ return StreamingResponse(result) if stream else result
@router.post("/batchllm")
-def batchllm(texts: List[str] = Body(...), maxlength: Optional[int] = Body(default=None)):
+def batchllm(texts: List[str] = Body(...), maxlength: Optional[int] = Body(default=None), stream: Optional[bool] = Body(default=False)):
"""
Runs a LLM pipeline for the input texts.
Args:
texts: input texts
maxlength: optional response max length
+ stream: streams response if True
Returns:
- list of response texts
+ response texts
"""
- kwargs = {"maxlength": maxlength} if maxlength else {}
- return application.get().pipeline("llm", texts, **kwargs)
+ # Build keyword arguments
+ kwargs = {key: value for key, value in [("stream", stream), ("maxlength", maxlength)] if value}
+
+ # Run pipeline
+ result = application.get().pipeline("llm", texts, **kwargs)
+
+ # Handle both standard and streaming responses
+ return StreamingResponse(result) if stream else result
diff --git a/src/python/txtai/api/routers/rag.py b/src/python/txtai/api/routers/rag.py
index 23735c30..6679c9c7 100644
--- a/src/python/txtai/api/routers/rag.py
+++ b/src/python/txtai/api/routers/rag.py
@@ -5,6 +5,7 @@ Defines API paths for rag endpoints.
from typing import List, Optional
from fastapi import APIRouter, Body
+from fastapi.responses import StreamingResponse
from .. import application
from ..route import EncodingAPIRoute
@@ -13,34 +14,48 @@ router = APIRouter(route_class=EncodingAPIRoute)
@router.get("/rag")
-def rag(query: str, maxlength: Optional[int] = None):
+def rag(query: str, maxlength: Optional[int] = None, stream: Optional[bool] = False):
"""
Runs a RAG pipeline for the input query.
Args:
query: input RAG query
maxlength: optional response max length
+ stream: streams response if True
Returns:
answer
"""
- kwargs = {"maxlength": maxlength} if maxlength else {}
- return application.get().pipeline("rag", query, **kwargs)
+ # Build keyword arguments
+ kwargs = {key: value for key, value in [("stream", stream), ("maxlength", maxlength)] if value}
+
+ # Run pipeline
+ result = application.get().pipeline("rag", query, **kwargs)
+
+ # Handle both standard and streaming responses
+ return StreamingResponse(result) if stream else result
@router.post("/batchrag")
-def batchrag(queries: List[str] = Body(...), maxlength: Optional[int] = Body(default=None)):
+def batchrag(queries: List[str] = Body(...), maxlength: Optional[int] = Body(default=None), stream: Optional[bool] = Body(default=False)):
"""
Runs a RAG pipeline for the input queries.
Args:
queries: input RAG queries
maxlength: optional response max length
+ stream: streams response if True
Returns:
- list of answers
+ answers
"""
- kwargs = {"maxlength": maxlength} if maxlength else {}
- return application.get().pipeline("rag", queries, **kwargs)
+ # Build keyword arguments
+ kwargs = {key: value for key, value in [("stream", stream), ("maxlength", maxlength)] if value}
+
+ # Run pipeline
+ result = application.get().pipeline("rag", queries, **kwargs)
+
+ # Handle both standard and streaming responses
+ return StreamingResponse(result) if stream else result
diff --git a/src/python/txtai/pipeline/__init__.py b/src/python/txtai/pipeline/__init__.py
index 5deb07ac..5c658be6 100644
--- a/src/python/txtai/pipeline/__init__.py
+++ b/src/python/txtai/pipeline/__init__.py
@@ -10,8 +10,8 @@ from .hfmodel import HFModel
from .hfpipeline import HFPipeline
from .image import *
from .llm import *
+from .llm import RAG as Extractor
from .nop import Nop
from .text import *
-from .text import RAG as Extractor
from .tensors import Tensors
from .train import *
diff --git a/src/python/txtai/pipeline/llm/__init__.py b/src/python/txtai/pipeline/llm/__init__.py
index 64676e74..597a9c84 100644
--- a/src/python/txtai/pipeline/llm/__init__.py
+++ b/src/python/txtai/pipeline/llm/__init__.py
@@ -8,3 +8,4 @@ from .huggingface import *
from .litellm import LiteLLM
from .llama import LlamaCpp
from .llm import LLM
+from .rag import RAG
diff --git a/src/python/txtai/pipeline/llm/generation.py b/src/python/txtai/pipeline/llm/generation.py
index aebac73b..63ec65c0 100644
--- a/src/python/txtai/pipeline/llm/generation.py
+++ b/src/python/txtai/pipeline/llm/generation.py
@@ -24,7 +24,7 @@ class Generation:
self.template = template
self.kwargs = kwargs
- def __call__(self, text, maxlength, **kwargs):
+ def __call__(self, text, maxlength, stream, **kwargs):
"""
Generates text. Supports the following input formats:
@@ -34,6 +34,7 @@ class Generation:
Args:
text: text|list
maxlength: maximum sequence length
+ stream: stream response if True, defaults to False
kwargs: additional generation keyword arguments
Returns:
@@ -49,7 +50,11 @@ class Generation:
texts = [formatter.format(self.template, text=x) for x in texts]
# Run pipeline
- results = self.execute(texts, maxlength, **kwargs)
+ results = self.execute(texts, maxlength, stream, **kwargs)
+
+ # Streaming generation
+ if stream:
+ return results
# Clean generated text
results = [self.clean(texts[x], result) for x, result in enumerate(results)]
@@ -57,17 +62,23 @@ class Generation:
# Extract results based on inputs
return results[0] if isinstance(text, str) or isinstance(text[0], dict) else results
- def execute(self, texts, maxlength, **kwargs):
+ def execute(self, texts, maxlength, stream, **kwargs):
"""
Runs a list of prompts through a generative model.
Args:
texts: list of prompts to run
maxlength: maximum sequence length
+ stream: stream response if True, defaults to False
kwargs: additional generation keyword arguments
"""
- raise NotImplementedError
+ # Streaming generation
+ if stream:
+ return self.stream(texts, maxlength, stream, **kwargs)
+
+ # Full response as content elements
+ return list(self.stream(texts, maxlength, stream, **kwargs))
def clean(self, prompt, result):
"""
@@ -86,3 +97,49 @@ class Generation:
# Apply text cleaning rules
return text.replace("$=", "<=").strip()
+
+ def response(self, result):
+ """
+ Parses response content from the result. This supports both standard and streaming
+ generation.
+
+ For standard generation, the full response is returned. For streaming generation,
+ this method will stream chunks of content.
+
+ Args:
+ result: LLM response
+
+ Returns:
+ response
+ """
+
+ streamed = False
+ for chunk in result:
+ # Expects one of the following parameter paths
+ # - text
+ # - message.content
+ # - delta.content
+ data = chunk["choices"][0]
+ text = data.get("text", data.get("message", data.get("delta")))
+ text = text if isinstance(text, str) else text.get("content")
+
+ # Yield result if there is text AND it's not leading stream whitespace
+ if text is not None and (streamed or text.strip()):
+ yield (text.lstrip() if not streamed else text)
+ streamed = True
+
+ def stream(self, texts, maxlength, stream, **kwargs):
+ """
+ Streams LLM responses.
+
+ Args:
+ texts: list of prompts to run
+ maxlength: maximum sequence length
+ stream: stream response if True, defaults to False
+ kwargs: additional generation keyword arguments
+
+ Returns:
+ list of responses
+ """
+
+ raise NotImplementedError
diff --git a/src/python/txtai/pipeline/llm/huggingface.py b/src/python/txtai/pipeline/llm/huggingface.py
index e288f8f6..d3eee164 100644
--- a/src/python/txtai/pipeline/llm/huggingface.py
+++ b/src/python/txtai/pipeline/llm/huggingface.py
@@ -2,6 +2,10 @@
Hugging Face module
"""
+from threading import Thread
+
+from transformers import TextIteratorStreamer
+
from ...models import Models
from ..hfpipeline import HFPipeline
@@ -21,8 +25,8 @@ class HFGeneration(Generation):
# Create HuggingFace LLM pipeline
self.llm = HFLLM(path, **kwargs)
- def execute(self, texts, maxlength, **kwargs):
- return self.llm(texts, maxlength=maxlength, **kwargs)
+ def stream(self, texts, maxlength, stream, **kwargs):
+ yield from self.llm(texts, maxlength=maxlength, stream=stream, **kwargs)
class HFLLM(HFPipeline):
@@ -37,7 +41,7 @@ class HFLLM(HFPipeline):
# Load tokenizer, if necessary
self.pipeline.tokenizer = self.pipeline.tokenizer if self.pipeline.tokenizer else Models.tokenizer(path, **kwargs)
- def __call__(self, text, prefix=None, maxlength=512, workers=0, **kwargs):
+ def __call__(self, text, prefix=None, maxlength=512, workers=0, stream=False, **kwargs):
"""
Generates text. Supports the following input formats:
@@ -49,6 +53,7 @@ class HFLLM(HFPipeline):
prefix: optional prefix to prepend to text elements
maxlength: maximum sequence length
workers: number of concurrent workers to use for processing data, defaults to None
+ stream: stream response if True, defaults to False
kwargs: additional generation keyword arguments
Returns:
@@ -62,8 +67,21 @@ class HFLLM(HFPipeline):
if prefix:
texts = [f"{prefix}{x}" for x in texts]
+ # Combine all keyword arguments
+ kwargs = {
+ **{
+ "max_length": maxlength,
+ "num_workers": workers,
+ },
+ **kwargs,
+ }
+
+ # Stream response
+ if stream:
+ return StreamingResponse(self.pipeline, texts, **kwargs)()
+
# Run pipeline
- results = self.pipeline(texts, max_length=maxlength, num_workers=workers, **kwargs)
+ results = self.pipeline(texts, **kwargs)
# Extract generated text
results = [self.extract(result) for result in results]
@@ -126,3 +144,30 @@ class Sequences(HFLLM):
def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
super().__init__(path, quantize, gpu, model, "sequence-sequence", **kwargs)
+
+
+class StreamingResponse:
+ """
+ Generate text as a streaming response.
+ """
+
+ def __init__(self, pipeline, texts, **kwargs):
+ # Create streamer
+ self.stream = TextIteratorStreamer(pipeline.tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=5)
+ kwargs["streamer"] = self.stream
+
+ # Create thread
+ self.thread = Thread(target=pipeline, args=[texts], kwargs=kwargs)
+
+ # Store number of inputs
+ self.length = len(texts)
+
+ def __call__(self):
+ # Start the process
+ self.thread.start()
+
+ return self
+
+ def __iter__(self):
+ for _ in range(self.length):
+ yield from self.stream
diff --git a/src/python/txtai/pipeline/llm/litellm.py b/src/python/txtai/pipeline/llm/litellm.py
index 2c08615b..1408b632 100644
--- a/src/python/txtai/pipeline/llm/litellm.py
+++ b/src/python/txtai/pipeline/llm/litellm.py
@@ -51,15 +51,19 @@ class LiteLLM(Generation):
if not LITELLM:
raise ImportError('LiteLLM is not available - install "pipeline" extra to enable')
- def execute(self, texts, maxlength, **kwargs):
- results = []
+ # Ignore common pipeline parameters
+ self.kwargs = {k: v for k, v in self.kwargs.items() if k not in ["quantize", "gpu", "model", "task"]}
+
+ def stream(self, texts, maxlength, stream, **kwargs):
for text in texts:
+ # LLM API call
result = api.completion(
model=self.path,
messages=[{"content": text, "role": "prompt"}] if isinstance(text, str) else text,
max_tokens=maxlength,
- **{**kwargs, **self.kwargs}
+ stream=stream,
+ **{**self.kwargs, **kwargs}
)
- results.append(result["choices"][0]["message"]["content"])
- return results
+ # Stream response
+ yield from self.response(result if stream else [result])
diff --git a/src/python/txtai/pipeline/llm/llama.py b/src/python/txtai/pipeline/llm/llama.py
index d28942a5..f1e4130e 100644
--- a/src/python/txtai/pipeline/llm/llama.py
+++ b/src/python/txtai/pipeline/llm/llama.py
@@ -51,12 +51,9 @@ class LlamaCpp(Generation):
# Create llama.cpp instance
self.llm = Llama(path, n_ctx=0, verbose=kwargs.pop("verbose", False), **kwargs)
- def execute(self, texts, maxlength, **kwargs):
- results = []
+ def stream(self, texts, maxlength, stream, **kwargs):
for text in texts:
- results.append(self.messages(text, maxlength, **kwargs) if isinstance(text, list) else self.prompt(text, maxlength, **kwargs))
-
- return results
+ yield from self.messages(text, maxlength, stream, **kwargs) if isinstance(text, list) else self.prompt(text, maxlength, stream, **kwargs)
def download(self, path):
"""
@@ -78,32 +75,42 @@ class LlamaCpp(Generation):
# Download and cache file
return hf_hub_download(repo_id="/".join(parts[:repo]), filename="/".join(parts[repo:]))
- def messages(self, messages, maxlength, **kwargs):
+ def messages(self, messages, maxlength, stream, **kwargs):
"""
Processes a list of messages.
Args:
messages: list of dictionaries with `role` and `content` key-values
maxlength: maximum sequence length
+ stream: stream response if True, defaults to False
kwargs: additional generation keyword arguments
Returns:
generated text
"""
- return self.llm.create_chat_completion(messages=messages, max_tokens=maxlength, **kwargs)["choices"][0]["message"]["content"]
+ # LLM call with messages
+ result = self.llm.create_chat_completion(messages=messages, max_tokens=maxlength, stream=stream, **kwargs)
+
+ # Stream response
+ yield from self.response(result if stream else [result])
- def prompt(self, text, maxlength, **kwargs):
+ def prompt(self, text, maxlength, stream, **kwargs):
"""
Processes a prompt.
Args:
prompt: prompt text
maxlength: maximum sequence length
+ stream: stream response if True, defaults to False
kwargs: additional generation keyword arguments
Returns:
generated text
"""
- return self.llm(text, max_tokens=maxlength, **kwargs)["choices"][0]["text"]
+ # LLM call with prompt
+ result = self.llm(text, max_tokens=maxlength, stream=stream, **kwargs)
+
+ # Stream response
+ yield from self.response(result if stream else [result])
diff --git a/src/python/txtai/pipeline/llm/llm.py b/src/python/txtai/pipeline/llm/llm.py
index 1a659413..ba894d45 100644
--- a/src/python/txtai/pipeline/llm/llm.py
+++ b/src/python/txtai/pipeline/llm/llm.py
@@ -33,7 +33,7 @@ class LLM(Pipeline):
# Generation instance
self.generator = GenerationFactory.create(path, method, **kwargs)
- def __call__(self, text, maxlength=512, **kwargs):
+ def __call__(self, text, maxlength=512, stream=False, **kwargs):
"""
Generates text. Supports the following input formats:
@@ -43,6 +43,7 @@ class LLM(Pipeline):
Args:
text: text|list
maxlength: maximum sequence length
+ stream: stream response if True, defaults to False
kwargs: additional generation keyword arguments
Returns:
@@ -50,4 +51,4 @@ class LLM(Pipeline):
"""
# Run LLM generation
- return self.generator(text, maxlength, **kwargs)
+ return self.generator(text, maxlength, stream, **kwargs)
diff --git a/src/python/txtai/pipeline/text/rag.py b/src/python/txtai/pipeline/llm/rag.py
similarity index 86%
rename from src/python/txtai/pipeline/text/rag.py
rename to src/python/txtai/pipeline/llm/rag.py
index afe6f096..a201ff22 100644
--- a/src/python/txtai/pipeline/text/rag.py
+++ b/src/python/txtai/pipeline/llm/rag.py
@@ -6,10 +6,11 @@ from ...models import Models
from ..base import Pipeline
from ..data import Tokenizer
-from ..llm import GenerationFactory, LLM
+from ..text import Questions
+from ..text import Similarity
-from .questions import Questions
-from .similarity import Similarity
+from .factory import GenerationFactory
+from .llm import LLM
class RAG(Pipeline):
@@ -35,6 +36,7 @@ class RAG(Pipeline):
output="default",
template=None,
separator=" ",
+ system=None,
**kwargs,
):
"""
@@ -54,6 +56,7 @@ class RAG(Pipeline):
output: output format, 'default' returns (name, answer), 'flatten' returns answers and 'reference' returns (name, answer, reference)
template: prompt template, it must have a parameter for {question} and {context}, defaults to "{question} {context}"
separator: context separator
+ system: system prompt, defaults to None
kwargs: additional keyword arguments to pass to pipeline model
"""
@@ -84,6 +87,9 @@ class RAG(Pipeline):
# Context separator
self.separator = separator
+ # System prompt template
+ self.system = system
+
def __call__(self, queue, texts=None, **kwargs):
"""
Finds answers to input questions. This method runs queries to find the top n best matches and uses that as the context.
@@ -108,6 +114,7 @@ class RAG(Pipeline):
if queue and isinstance(queue[0], dict):
# Convert dict to tuple
queue = [tuple(row.get(x) for x in ["name", "query", "question", "snippet"]) for row in queue]
+
if queue and isinstance(queue[0], str):
# Convert string questions to tuple
queue = [(None, row, row, None) for row in queue]
@@ -132,10 +139,10 @@ class RAG(Pipeline):
snippets.append(snippet)
# Run pipeline and return answers
- answers = self.answers(names, questions, contexts, [[text for _, text, _ in topn] for topn in topns], snippets, **kwargs)
+ answers = self.answers(questions, contexts, **kwargs)
# Apply output formatting to answers and return
- return self.apply(inputs, queries, answers, topns)
+ return self.apply(inputs, names, queries, answers, topns, snippets) if isinstance(answers, list) else answers
def load(self, path, quantize, gpu, model, task, **kwargs):
"""
@@ -296,63 +303,55 @@ class RAG(Pipeline):
return self.tokenizer(text) if self.tokenizer else text
- def answers(self, names, questions, contexts, topns, snippets, **kwargs):
+ def answers(self, questions, contexts, **kwargs):
"""
Executes pipeline and formats extracted answers.
Args:
- names: question identifiers/names
questions: questions
contexts: question context
- topns: same as question context but as a list with each candidate element
- snippets: flags to enable answer snippets per answer
- kwargs: additional keyword arguments to pass to pipeline model
Returns:
- list of (name, answer)
+ answers
"""
- results = []
-
- # Run model inference for question-context pairs
+ # Run model inference with questions pipeline
if isinstance(self.model, Questions):
- # Questions pipeline takes questions and contexts separately
- answers = self.model(questions, contexts)
- else:
- # Combine question and context into single text field for generative pipelines
- answers = self.model([self.template.format(question=questions[x], context=context) for x, context in enumerate(contexts)], **kwargs)
-
- # Extract and format answer
- for x, answer in enumerate(answers):
- # Resolve snippet if necessary
- if answer and snippets[x]:
- answer = self.snippet(topns[x], answer)
-
- results.append((names[x], answer))
+ return self.model(questions, contexts)
- return results
+ # Run generator pipeline
+ return self.model(self.prompts(questions, contexts), **kwargs)
- def snippet(self, topn, answer):
+ def prompts(self, questions, contexts):
"""
- Extracts text surrounding the answer within context.
+ Builds a list of prompts using the passed in questions and contexts.
Args:
- topn: topn items used as a context
- answer: answer within context
+ questions: questions
+ contexts: question context
Returns:
- text surrounding answer as a snippet
+ prompts
"""
- # Searches for first sentence to contain answer
- if answer:
- for x in topn:
- if answer in x:
- return x
+ # Format prompts for generator pipeline
+ prompts = []
+ for x, context in enumerate(contexts):
+ # Create input prompt
+ prompt = self.template.format(question=questions[x], context=context)
+
+ # Add system prompt, if necessary
+ if self.system:
+ prompt = [
+ {"role": "system", "content": self.system.format(question=questions[x], context=context)},
+ {"role": "user", "content": prompt},
+ ]
+
+ prompts.append(prompt)
- return answer
+ return prompts
- def apply(self, inputs, queries, answers, topns):
+ def apply(self, inputs, names, queries, answers, topns, snippets):
"""
Applies the following formatting rules to answers.
- each answer row matches input format (tuple or dict)
@@ -362,14 +361,19 @@ class RAG(Pipeline):
Args:
inputs: original inputs
+ names: question identifiers/names
queries: list of input queries
answers: list of generated answers
topns: top n records used for context
+ snippets: flags to enable answer snippets per answer
Returns:
list of answers matching input format (tuple or dict) containing fields as specified by output format
"""
+ # Resolve answers as snippets
+ answers = self.snippets(names, answers, topns, snippets)
+
# Flatten to list of answers and return
if self.output == "flatten":
answers = [answer for _, answer in answers]
@@ -379,14 +383,45 @@ class RAG(Pipeline):
answers = self.reference(queries, answers, topns)
# Ensure output format matches input format
- if inputs and isinstance(inputs[0], (dict, str)):
+ first = inputs[0] if inputs and isinstance(inputs, list) else inputs
+ if isinstance(first, (dict, str)):
# Add name if input queue had name field
- fields = ["name", "answer", "reference"] if isinstance(inputs[0], dict) and "name" in inputs[0] else [None, "answer", "reference"]
+ fields = ["name", "answer", "reference"] if isinstance(first, dict) and "name" in first else [None, "answer", "reference"]
answers = [{fields[x]: column for x, column in enumerate(row) if fields[x]} for row in answers]
# Unpack single answer, if necessary
return answers[0] if answers and isinstance(inputs, (tuple, dict, str)) else answers
+ def snippets(self, names, answers, topns, snippets):
+ """
+ Extracts text surrounding the answer within context.
+
+ Args:
+ names: question identifiers/names
+ answers: list of generated answers
+ topns: top n records used for context
+ snippets: flags to enable answer snippets per answer
+
+ Returns:
+ answers resolved as snippets per question, if necessary
+ """
+
+ # Extract and format answer
+ results = []
+
+ for x, answer in enumerate(answers):
+ # Resolve snippet if necessary
+ if answer and snippets[x]:
+ # Searches for first text element to contain answer
+ for _, text, _ in topns[x]:
+ if answer in text:
+ answer = text
+ break
+
+ results.append((names[x], answer))
+
+ return results
+
def reference(self, queries, answers, topns):
"""
Reference each answer with the best matching context element id.
diff --git a/src/python/txtai/pipeline/text/__init__.py b/src/python/txtai/pipeline/text/__init__.py
index b0e91d33..146f4d00 100644
--- a/src/python/txtai/pipeline/text/__init__.py
+++ b/src/python/txtai/pipeline/text/__init__.py
@@ -6,7 +6,6 @@ from .crossencoder import CrossEncoder
from .entity import Entity
from .labels import Labels
from .questions import Questions
-from .rag import RAG
from .similarity import Similarity
from .summary import Summary
from .translation import Translation
diff --git a/src/python/txtai/workflow/task/__init__.py b/src/python/txtai/workflow/task/__init__.py
index e62b3806..05d89dc7 100644
--- a/src/python/txtai/workflow/task/__init__.py
+++ b/src/python/txtai/workflow/task/__init__.py
@@ -12,6 +12,7 @@ from .retrieve import RetrieveTask
from .service import ServiceTask
from .storage import StorageTask
from .stream import StreamTask
-from .template import ExtractorTask, TemplateTask
+from .template import *
+from .template import RAGTask as ExtractorTask
from .url import UrlTask
from .workflow import WorkflowTask
diff --git a/src/python/txtai/workflow/task/template.py b/src/python/txtai/workflow/task/template.py
index 2c1605c3..e3390be1 100644
--- a/src/python/txtai/workflow/task/template.py
+++ b/src/python/txtai/workflow/task/template.py
@@ -96,9 +96,9 @@ class TemplateTask(Task):
return None
-class ExtractorTask(TemplateTask):
+class RAGTask(TemplateTask):
"""
- Template task that prepares input for an extractor pipeline.
+ Template task that prepares input for a rag pipeline.
"""
def prepare(self, element):
diff --git a/test/python/testpipeline/testlitellm.py b/test/python/testpipeline/testlitellm.py
index a3ccd8fd..6cc5ccac 100644
--- a/test/python/testpipeline/testlitellm.py
+++ b/test/python/testpipeline/testlitellm.py
@@ -21,12 +21,22 @@ class RequestHandler(BaseHTTPRequestHandler):
POST request handler.
"""
- # Generate mock response
- response = [{"generated_text": "blue"}]
- response = json.dumps(response).encode("utf-8")
+ # Parse input headers
+ length = int(self.headers["content-length"])
+ data = json.loads(self.rfile.read(length))
+
+ if data.get("stream"):
+ # Mock streaming response
+ content = "application/octet-stream"
+ response = """data: {"token": {"text": "blue"}}""".encode("utf-8")
+ else:
+ # Mock standard response
+ content = "application/json"
+ 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-type", content)
self.send_header("content-length", len(response))
self.end_headers()
@@ -67,3 +77,6 @@ class TestLiteLLM(unittest.TestCase):
# 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")
+
+ # Test streaming
+ self.assertEqual(" ".join(x for x in model("The sky is", stream=True)), "blue")
diff --git a/test/python/testpipeline/testllama.py b/test/python/testpipeline/testllama.py
index 7fae1654..f7c0e10d 100644
--- a/test/python/testpipeline/testllama.py
+++ b/test/python/testpipeline/testllama.py
@@ -21,8 +21,11 @@ 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=["."]), "4")
+ self.assertEqual(model("2 + 2 = ", maxlength=10, seed=0, stop=["."])[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?"}]
self.assertIsNotNone(model(messages, maxlength=10, seed=0, stop=["."]))
+
+ # Test streaming
+ self.assertEqual(" ".join(x for x in model("2 + 2 = ", maxlength=10, stream=True, seed=0, stop=["."]))[0], "4")
diff --git a/test/python/testpipeline/testllm.py b/test/python/testpipeline/testllm.py
index 2b272bcd..54a6b4e9 100644
--- a/test/python/testpipeline/testllm.py
+++ b/test/python/testpipeline/testllm.py
@@ -60,10 +60,26 @@ class TestLLM(unittest.TestCase):
# Test that text is generated
self.assertIsNotNone(model(start))
+ def testMaxLength(self):
+ """
+ Test max length
+ """
+
+ model = LLM("sshleifer/tiny-gpt2")
+ self.assertIsNotNone(model("Hello, how are", maxlength=10))
+
def testNotImplemented(self):
"""
Test exceptions for non-implemented methods
"""
generation = Generation()
- self.assertRaises(NotImplementedError, generation.execute, None, None)
+ self.assertRaises(NotImplementedError, generation.stream, None, None, None)
+
+ def testStream(self):
+ """
+ Test streaming generation
+ """
+
+ model = LLM("sshleifer/tiny-gpt2")
+ self.assertIsInstance(" ".join(x for x in model("Hello, how are", stream=True)), str)
diff --git a/test/python/testpipeline/testextractor.py b/test/python/testpipeline/testrag.py
similarity index 57%
rename from test/python/testpipeline/testextractor.py
rename to test/python/testpipeline/testrag.py
index 28545fc1..40c3ee4a 100644
--- a/test/python/testpipeline/testextractor.py
+++ b/test/python/testpipeline/testrag.py
@@ -1,23 +1,23 @@
"""
-Extractor module tests
+RAG module tests
"""
import platform
import unittest
from txtai.embeddings import Embeddings
-from txtai.pipeline import Extractor, Questions, Similarity
+from txtai.pipeline import Questions, RAG, Similarity
-class TestExtractor(unittest.TestCase):
+class TestRAG(unittest.TestCase):
"""
- Extractor tests.
+ RAG tests.
"""
@classmethod
def setUpClass(cls):
"""
- Create single extractor instance.
+ Create single rag instance.
"""
cls.data = [
@@ -38,8 +38,8 @@ class TestExtractor(unittest.TestCase):
# Create embeddings model, backed by sentence-transformers & transformers
cls.embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})
- # Create extractor instance
- cls.extractor = Extractor(cls.embeddings, "distilbert-base-cased-distilled-squad")
+ # Create rag instance
+ cls.rag = RAG(cls.embeddings, "distilbert-base-cased-distilled-squad")
@classmethod
def tearDownClass(cls):
@@ -58,7 +58,7 @@ class TestExtractor(unittest.TestCase):
questions = ["What team won the game?", "What was score?"]
# pylint: disable=C3001
- execute = lambda query: self.extractor([(question, query, question, False) for question in questions], self.data)
+ execute = lambda query: self.rag([(question, query, question, False) for question in questions], self.data)
answers = execute("Red Sox - Blue Jays")
self.assertEqual("Blue Jays", answers[0][1])
@@ -67,27 +67,15 @@ class TestExtractor(unittest.TestCase):
# Ad-hoc questions
question = "What hockey team won?"
- answers = self.extractor([(question, question, question, False)], self.data)
+ answers = self.rag([(question, question, question, False)], self.data)
self.assertEqual("Flyers", answers[0][1])
def testEmptyQuery(self):
"""
- Test an empty extractor queries list
+ Test an empty queries list
"""
- self.assertEqual(self.extractor.query(None, None), [])
-
- def testGeneration(self):
- """
- Test support for generator models
- """
-
- extractor = Extractor(self.embeddings, "sshleifer/tiny-gpt2")
-
- question = "How many home runs?"
-
- answers = extractor([(question, question, question, False)], self.data)
- self.assertIsNotNone(answers)
+ self.assertEqual(self.rag.query(None, None), [])
def testNoAnswer(self):
"""
@@ -96,11 +84,11 @@ class TestExtractor(unittest.TestCase):
question = ""
- answers = self.extractor([(question, question, question, False)], self.data)
+ answers = self.rag([(question, question, question, False)], self.data)
self.assertIsNone(answers[0][1])
question = "abcdef"
- answers = self.extractor([(question, question, question, False)], self.data)
+ answers = self.rag([(question, question, question, False)], self.data)
self.assertIsNone(answers[0][1])
@unittest.skipIf(platform.system() == "Darwin", "Quantized models not supported on macOS")
@@ -109,11 +97,11 @@ class TestExtractor(unittest.TestCase):
Test qa extraction backed by a quantized model
"""
- extractor = Extractor(self.embeddings, "distilbert-base-cased-distilled-squad", True)
+ rag = RAG(self.embeddings, "distilbert-base-cased-distilled-squad", True)
question = "How many home runs?"
- answers = extractor([(question, question, question, True)], self.data)
+ answers = rag([(question, question, question, True)], self.data)
self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
def testOutputs(self):
@@ -124,58 +112,79 @@ class TestExtractor(unittest.TestCase):
question = "How many home runs?"
# Test flatten to list of answers
- extractor = Extractor(self.embeddings, "distilbert-base-cased-distilled-squad", output="flatten")
- answers = extractor([(question, question, question, True)], self.data)
+ rag = RAG(self.embeddings, "distilbert-base-cased-distilled-squad", output="flatten")
+ answers = rag([(question, question, question, True)], self.data)
self.assertTrue(answers[0].startswith("Giants hit 3 HRs"))
# Test reference field
- extractor = Extractor(self.embeddings, "distilbert-base-cased-distilled-squad", output="reference")
- answers = extractor([(question, question, question, True)], self.data)
+ rag = RAG(self.embeddings, "distilbert-base-cased-distilled-squad", output="reference")
+ answers = rag([(question, question, question, True)], self.data)
self.assertTrue(self.data[answers[0][2]].startswith("Giants hit 3 HRs"))
- def testSearch(self):
+ def testPrompt(self):
"""
- Test qa extraction with an embeddings search for context
+ Test a user prompt with templating
"""
embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": True})
embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
- extractor = Extractor(embeddings, "distilbert-base-cased-distilled-squad")
+ rag = RAG(
+ embeddings,
+ "google/flan-t5-small",
+ template="""
+ Answer the following question and return a number.
+ Question: {question}
+ Context:{context}""",
+ output="flatten",
+ )
- question = "How many home runs?"
-
- answers = extractor([(question, question, question, True)])
- self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
+ self.assertEqual(rag("How many HRs"), "3")
- def testSequences(self):
+ def testPromptTemplates(self):
"""
- Test extraction with prompts and a Seq2Seq model
+ Test system and user prompt templates
"""
- extractor = Extractor(self.embeddings, "google/flan-t5-small")
+ rag = RAG(
+ self.embeddings,
+ "sshleifer/tiny-gpt2",
+ system="You are a friendly assistant",
+ template="""
+ Answer the following question and return a number.
+ Question: {question}
+ Context:{context}""",
+ )
- # Prompt template, context appended by extractor
- prompt = """
- Answer the following question and return a number.
- Question: How many HRs?
- Context:
+ prompts = rag.prompts(["How many HRs?"], [self.data])[0]
+ self.assertEqual([x["role"] for x in prompts], ["system", "user"])
+
+ def testSearch(self):
+ """
+ Test qa extraction with an embeddings search for context
"""
- answers = extractor([("prompt", prompt, prompt, False)], self.data)
- self.assertEqual(answers[0][1], "3")
+ embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": True})
+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ rag = RAG(embeddings, "distilbert-base-cased-distilled-squad")
+
+ question = "How many home runs?"
+
+ answers = rag([(question, question, question, True)])
+ self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
def testSimilarity(self):
"""
Test qa extraction using a Similarity pipeline to build context
"""
- # Create extractor instance
- extractor = Extractor(Similarity("prajjwal1/bert-medium-mnli"), Questions("distilbert-base-cased-distilled-squad"))
+ # Create rag instance
+ rag = RAG(Similarity("prajjwal1/bert-medium-mnli"), Questions("distilbert-base-cased-distilled-squad"))
question = "How many home runs?"
- answers = extractor([(question, "HRs", question, True)], self.data)
+ answers = rag([(question, "HRs", question, True)], self.data)
self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
def testSnippet(self):
@@ -185,7 +194,7 @@ class TestExtractor(unittest.TestCase):
question = "How many home runs?"
- answers = self.extractor([(question, question, question, True)], self.data)
+ answers = self.rag([(question, question, question, True)], self.data)
self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
def testSnippetEmpty(self):
@@ -193,14 +202,14 @@ class TestExtractor(unittest.TestCase):
Test snippet method can handle empty parameters
"""
- self.assertEqual(self.extractor.snippet(None, None), None)
+ self.assertEqual(self.rag.snippets(["name"], [None], [None], [None]), [("name", None)])
def testStringInput(self):
"""
- Test extractor with single string input
+ Test with single string input
"""
- result = self.extractor("How many home runs?", self.data)
+ result = self.rag("How many home runs?", self.data)
self.assertEqual(result["answer"], "3")
def testTasks(self):
@@ -212,5 +221,5 @@ class TestExtractor(unittest.TestCase):
("language-generation", "hf-internal-testing/tiny-random-gpt2"),
("sequence-sequence", "hf-internal-testing/tiny-random-t5"),
]:
- extractor = Extractor(self.embeddings, model, task=task)
- self.assertIsNotNone(extractor)
+ rag = RAG(self.embeddings, model, task=task)
+ self.assertIsNotNone(rag)
diff --git a/test/python/testworkflow.py b/test/python/testworkflow.py
index 1e94679b..845792b4 100644
--- a/test/python/testworkflow.py
+++ b/test/python/testworkflow.py
@@ -21,9 +21,9 @@ from txtai.workflow import (
Task,
ConsoleTask,
ExportTask,
- ExtractorTask,
FileTask,
ImageTask,
+ RAGTask,
RetrieveTask,
StorageTask,
TemplateTask,
@@ -438,23 +438,23 @@ class TestWorkflow(unittest.TestCase):
results = list(workflow([{"text": "prompt"}]))
self.assertEqual(results[0], "This is a prompt")
- def testTemplateExtractor(self):
+ def testTemplateRAG(self):
"""
- Test extractor template task
+ Test rag template task
"""
- # Test extractor outputs
- workflow = Workflow([ExtractorTask(template="This is a {text}")])
+ # Test outputs
+ workflow = Workflow([RAGTask(template="This is a {text}")])
results = list(workflow(["prompt"]))
self.assertEqual(results[0], {"query": "prompt", "question": "This is a prompt"})
- # Test partial extractor outputs
- workflow = Workflow([ExtractorTask(template="This is a {text}")])
+ # Test partial outputs
+ workflow = Workflow([RAGTask(template="This is a {text}")])
results = list(workflow([{"query": "query", "question": "prompt"}]))
self.assertEqual(results[0], {"query": "query", "question": "This is a prompt"})
# Test additional template parameters
- workflow = Workflow([ExtractorTask(template="This is a {text} with another {param}")])
+ workflow = Workflow([RAGTask(template="This is a {text} with another {param}")])
results = list(workflow([{"query": "query", "question": "prompt", "param": "value"}]))
self.assertEqual(results[0], {"query": "query", "question": "This is a prompt with another value", "param": "value"})