Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Support stripthink in streaming LLM responses, closes #981

davidmezzetti594145840f67
diff --git a/src/python/txtai/pipeline/llm/generation.py b/src/python/txtai/pipeline/llm/generation.py
index bb2b23b3..562f59d9 100644
--- a/src/python/txtai/pipeline/llm/generation.py
+++ b/src/python/txtai/pipeline/llm/generation.py
@@ -63,7 +63,7 @@ class Generation:
# Streaming generation
if stream:
- return results
+ return self.cleanstream(results) if stripthink else results
# Clean generated text
results = [self.clean(texts[x], result, stripthink) for x, result in enumerate(results)]
@@ -121,13 +121,47 @@ class Generation:
# Replace thinking text, if necessary
if stripthink:
- text = re.sub(r"(?s)<think>.+?</think>", "", text)
- text = text.split("<|channel|>final<|message|>", 1)
- text = text[1] if len(text) > 1 else text[0]
+ text = self.cleanthink(text)
# Apply text cleaning rules
return text.replace("$=", "<=").strip()
+ def cleanstream(self, results):
+ """
+ Cleans thinking tokens from streaming results and streams the remaining results.
+
+ Args:
+ results: results stream
+ """
+
+ # Consume "thinking" tokens
+ text, buffer = None, ""
+ for chunk in results:
+ buffer += chunk
+ text = self.cleanthink(buffer)
+ if text != buffer:
+ break
+
+ # Yield remaining tokens
+ yield from text
+ yield from results
+
+ def cleanthink(self, text):
+ """
+ Clean thinking tokens from text.
+
+ Args:
+ text: input text
+
+ Returns:
+ text with thinking tokens removed
+ """
+
+ text = re.sub(r"(?s)<think>.+?</think>", "", text)
+ text = text.split("<|channel|>final<|message|>", 1)
+ text = text[1] if len(text) > 1 else text[0]
+ return text
+
def response(self, result):
"""
Parses response content from the result. This supports both standard and streaming
diff --git a/test/python/testpipeline/testllm/testllm.py b/test/python/testpipeline/testllm/testllm.py
index 7d220b9b..5ae31a28 100644
--- a/test/python/testpipeline/testllm/testllm.py
+++ b/test/python/testpipeline/testllm/testllm.py
@@ -130,6 +130,25 @@ class TestLLM(unittest.TestCase):
model.generator.execute = method
self.assertEqual(model("Hello, how are", stripthink=True), "you")
+ def testStripThinkStream(self):
+ """
+ Test stripthink parameter with streaming output
+ """
+
+ # pylint: disable=W0613
+ def execute1(*args, **kwargs):
+ yield from "<think>test</think>you"
+
+ def execute2(*args, **kwargs):
+ yield from "<|channel|>final<|message|>you"
+
+ model = LLM("hf-internal-testing/tiny-random-LlamaForCausalLM")
+
+ for method in [execute1, execute2]:
+ # Override execute method
+ model.generator.execute = method
+ self.assertEqual("".join(model("Hello, how are", stripthink=True, stream=True)), "you")
+
def testVision(self):
"""
Test vision LLM