💡 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
Migrate to smolagents, closes #890
davidmezzettib18854f788a0
diff --git a/docs/agent/configuration.md b/docs/agent/configuration.mdindex 31810b29..44193195 100644--- a/docs/agent/configuration.md+++ b/docs/agent/configuration.md@@ -2,7 +2,7 @@An agent takes two main arguments, an LLM and a list of tools.-The txtai agent framework is built with [Transformers Agents](https://huggingface.co/docs/transformers/en/agents). Additional options can be passed in the `Agent` constructor.+The txtai agent framework is built with [smolagents](https://github.com/huggingface/smolagents). Additional options can be passed in the `Agent` constructor.```pythonfrom datetime import datetime@@ -77,18 +77,20 @@ Embeddings indexes have built-in support. Provide the following dictionary confi| description | embeddings index description || **kwargs | Parameters to pass to [embeddings.load](../../embeddings/methods/#txtai.embeddings.Embeddings.load) |-### transformers+### tool-A Transformers tool instance can be provided. Additionally, the following strings load tools directly from Transformers.+A tool instance can be provided. Additionally, the following strings load tools directly.| Tool | Description ||:------------|:----------------------------------------------------------|-| websearch | Runs a websearch using built-in Transformers Agent tool |+| websearch | Runs a websearch using the built-in websearch tool |## method```yaml-method: reactjson|reactcode|code+method: code|tool```-Sets the agent method. Defaults to `reactjson`. [Read more on this here](https://huggingface.co/docs/transformers/en/agents#types-of-agents).+Sets the agent method. Supports either a `code` or `tool` calling agent (default). A code agent generates Python code and executes that. A tool calling agent generates JSON blocks and calls the agents within those blocks.++[Read more on this here](https://huggingface.co/docs/smolagents/v1.13.0/en/guided_tour#codeagent-and-toolcallingagent).diff --git a/examples/67_Whats_new_in_txtai_8_0.ipynb b/examples/67_Whats_new_in_txtai_8_0.ipynbindex 6d67fd32..8fdc2904 100644--- a/examples/67_Whats_new_in_txtai_8_0.ipynb+++ b/examples/67_Whats_new_in_txtai_8_0.ipynb@@ -42,7 +42,7 @@"outputs": [],"source": ["%%capture\n",- "!pip install git+https://github.com/neuml/txtai autoawq model2vec"+ "!pip install git+https://github.com/neuml/txtai#egg=txtai[agent] autoawq model2vec"]},{diff --git a/examples/68_Analyzing_Hugging_Face_Posts_with_Graphs_and_Agents.ipynb b/examples/68_Analyzing_Hugging_Face_Posts_with_Graphs_and_Agents.ipynbindex f5e86ba8..350df241 100644--- a/examples/68_Analyzing_Hugging_Face_Posts_with_Graphs_and_Agents.ipynb+++ b/examples/68_Analyzing_Hugging_Face_Posts_with_Graphs_and_Agents.ipynb@@ -36,7 +36,7 @@"outputs": [],"source": ["%%capture\n",- "!pip install git+https://github.com/neuml/txtai#egg=txtai[graph] datasets autoawq"+ "!pip install git+https://github.com/neuml/txtai#egg=txtai[agent,graph] datasets autoawq"]},{@@ -815,7 +815,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.9.20"+ "version": "3.10.16"}},"nbformat": 4,diff --git a/examples/69_Granting_autonomy_to_agents.ipynb b/examples/69_Granting_autonomy_to_agents.ipynbindex bc0d2fc3..dc783617 100644--- a/examples/69_Granting_autonomy_to_agents.ipynb+++ b/examples/69_Granting_autonomy_to_agents.ipynb@@ -33,7 +33,7 @@"outputs": [],"source": ["%%capture\n",- "!pip install git+https://github.com/neuml/txtai#egg=txtai[graph] autoawq"+ "!pip install git+https://github.com/neuml/txtai#egg=txtai[agent,graph] autoawq"]},{diff --git a/examples/71_Analyzing_LinkedIn_Company_Posts_with_Graphs_and_Agents.ipynb b/examples/71_Analyzing_LinkedIn_Company_Posts_with_Graphs_and_Agents.ipynbindex 11fea522..a780924d 100644--- a/examples/71_Analyzing_LinkedIn_Company_Posts_with_Graphs_and_Agents.ipynb+++ b/examples/71_Analyzing_LinkedIn_Company_Posts_with_Graphs_and_Agents.ipynb@@ -24,12 +24,12 @@},{"cell_type": "code",- "execution_count": 1,+ "execution_count": null,"metadata": {},"outputs": [],"source": ["%%capture\n",- "!pip install git+https://github.com/neuml/txtai#egg=txtai[graph] datasets autoawq autoawq-kernels"+ "!pip install git+https://github.com/neuml/txtai#egg=txtai[agent,graph] datasets autoawq autoawq-kernels"]},{diff --git a/examples/72_Parsing_the_stars_with_txtai.ipynb b/examples/72_Parsing_the_stars_with_txtai.ipynbindex dbe3f285..35b13049 100644--- a/examples/72_Parsing_the_stars_with_txtai.ipynb+++ b/examples/72_Parsing_the_stars_with_txtai.ipynb@@ -31,7 +31,7 @@"outputs": [],"source": ["%%capture\n",- "!pip install git+https://github.com/neuml/txtai#egg=txtai[graph,pipeline-text] datasets autoawq autoawq-kernels"+ "!pip install git+https://github.com/neuml/txtai#egg=txtai[agent,graph,pipeline-text] datasets autoawq autoawq-kernels"]},{diff --git a/setup.py b/setup.pyindex 1035c708..70100581 100644--- a/setup.py+++ b/setup.py@@ -27,6 +27,8 @@ extras["dev"] = ["pylint",]+extras["agent"] = ["smolagents>=1.13"]+extras["ann"] = ["annoy>=1.16.3","hnswlib>=0.5.0",@@ -116,7 +118,8 @@ extras["workflow"] = [extras["similarity"] = extras["ann"] + extras["vectors"]extras["all"] = (- extras["api"]+ extras["agent"]+ + extras["api"]+ extras["cloud"]+ extras["console"]+ extras["database"]diff --git a/src/python/txtai/agent/__init__.py b/src/python/txtai/agent/__init__.pyindex 09d64e06..96919655 100644--- a/src/python/txtai/agent/__init__.py+++ b/src/python/txtai/agent/__init__.py@@ -2,7 +2,11 @@Agent imports"""-from .base import Agent-from .engine import LLMEngine-from .factory import ProcessFactory-from .tool import *+# Conditional import+try:+ from .base import Agent+ from .factory import ProcessFactory+ from .model import PipelineModel+ from .tool import *+except ImportError:+ from .placeholder import Agentdiff --git a/src/python/txtai/agent/base.py b/src/python/txtai/agent/base.pyindex dc9afbeb..defc82f3 100644--- a/src/python/txtai/agent/base.py+++ b/src/python/txtai/agent/base.py@@ -23,11 +23,15 @@ class Agent:kwargs: arguments to pass to the underlying Agent backend and LLM pipeline instance"""+ # Ensure backwards compatibility+ if "max_iterations" in kwargs:+ kwargs["max_steps"] = kwargs.pop("max_iterations")+# Create agent process runnerself.process = ProcessFactory.create(kwargs)# Tools dictionary- self.tools = self.process.toolbox.tools+ self.tools = self.process.toolsdef __call__(self, text, maxlength=8192, stream=False, **kwargs):"""@@ -44,7 +48,7 @@ class Agent:"""# Process parameters- self.process.llm_engine.parameters(maxlength)+ self.process.model.parameters(maxlength)# Run agent loopreturn self.process.run(text, stream=stream, **kwargs)diff --git a/src/python/txtai/agent/factory.py b/src/python/txtai/agent/factory.pyindex 66bbb590..c631466f 100644--- a/src/python/txtai/agent/factory.py+++ b/src/python/txtai/agent/factory.py@@ -2,9 +2,9 @@Factory module"""-from transformers.agents import CodeAgent, ReactCodeAgent, ReactJsonAgent+from smolagents import CodeAgent, ToolCallingAgent-from .engine import LLMEngine+from .model import PipelineModelfrom .tool import ToolFactory@@ -26,16 +26,14 @@ class ProcessFactory:agent process runner"""- constructor = ReactJsonAgent+ constructor = ToolCallingAgentmethod = config.pop("method", None)if method == "code":constructor = CodeAgent- elif method == "reactcode":- constructor = ReactCodeAgent- # Create LLMEngine+ # Create model backed by LLM pipelinellm = config.pop("llm")- llm = LLMEngine(**llm) if isinstance(llm, dict) else LLMEngine(llm)+ llm = PipelineModel(**llm) if isinstance(llm, dict) else PipelineModel(llm)# Create the agent process- return constructor(tools=ToolFactory.create(config), llm_engine=llm, **config)+ return constructor(tools=ToolFactory.create(config), model=llm, **config)diff --git a/src/python/txtai/agent/engine.py b/src/python/txtai/agent/model.pysimilarity index 58%rename from src/python/txtai/agent/engine.pyrename to src/python/txtai/agent/model.pyindex d73342e2..405167b7 100644--- a/src/python/txtai/agent/engine.py+++ b/src/python/txtai/agent/model.py@@ -1,22 +1,25 @@"""-Engine module+Model module"""+import re+from enum import Enum-from transformers.agents import llm_engine+from smolagents import ChatMessage, Model, get_clean_message_list, tool_role_conversions+from smolagents.models import get_tool_call_from_text, remove_stop_sequencesfrom ..pipeline import LLM-class LLMEngine:+class PipelineModel(Model):"""- Engine backed by a txtai LLM pipeline.+ Model backed by a LLM pipeline."""def __init__(self, path=None, method=None, **kwargs):"""- Creates a new LLM engine.+ Creates a new LLM model.Args:path: model path or instance@@ -27,7 +30,13 @@ class LLMEngine:self.llm = path if isinstance(path, LLM) else LLM(path, method, **kwargs)self.maxlength = 8192- def __call__(self, messages, stop_sequences=None, **kwargs):+ # Set base class parameters+ self.model_id = self.llm.generator.path++ # Call parent constructor+ super().__init__(flatten_messages_as_text=not self.llm.isvision(), **kwargs)++ def __call__(self, messages, stop_sequences=None, grammar=None, tools_to_call_from=None, **kwargs):"""Runs LLM inference. This method signature must match the Transformers Agents specification.@@ -48,11 +57,20 @@ class LLMEngine:# Remove stop sequences from LLM outputif stop_sequences is not None:- for stop in stop_sequences:- if response[-len(stop) :] == stop:- response = response[: -len(stop)]+ response = remove_stop_sequences(response, stop_sequences)++ # Load response into a chat message+ message = ChatMessage(role="assistant", content=response)++ # Extract first tool action, if necessary+ if tools_to_call_from:+ message.tool_calls = [+ get_tool_call_from_text(+ re.sub(r".*?Action:(.*?\n\}).*", r"\1", response, flags=re.DOTALL), self.tool_name_key, self.tool_arguments_key+ )+ ]- return response+ return messagedef parameters(self, maxlength):"""@@ -76,7 +94,7 @@ class LLMEngine:"""# Get clean message list- messages = llm_engine.get_clean_message_list(messages, role_conversions=llm_engine.llama_role_conversions)+ messages = get_clean_message_list(messages, role_conversions=tool_role_conversions, flatten_messages_as_text=self.flatten_messages_as_text)# Ensure all roles are strings and not enums for compability across LLM frameworksfor message in messages:diff --git a/src/python/txtai/agent/placeholder.py b/src/python/txtai/agent/placeholder.pynew file mode 100644index 00000000..5897a38d--- /dev/null+++ b/src/python/txtai/agent/placeholder.py@@ -0,0 +1,16 @@+"""+Placeholder module+"""+++class Agent:+ """+ Agent placeholder stub for when smolagents isn't installed+ """++ def __init__(self, *args, **kwargs):+ """+ Raises an exception that smolagents isn't installed.+ """++ raise ImportError('smolagents is not available - install "agent" extra to enable')diff --git a/src/python/txtai/agent/tool/embeddings.py b/src/python/txtai/agent/tool/embeddings.pyindex 41d6e89c..c0a75321 100644--- a/src/python/txtai/agent/tool/embeddings.py+++ b/src/python/txtai/agent/tool/embeddings.py@@ -2,7 +2,7 @@Embeddings module"""-from transformers.agents import Tool+from smolagents import Toolfrom ...embeddings import Embeddingsdiff --git a/src/python/txtai/agent/tool/factory.py b/src/python/txtai/agent/tool/factory.pyindex 3eb570ff..190d9f4a 100644--- a/src/python/txtai/agent/tool/factory.py+++ b/src/python/txtai/agent/tool/factory.py@@ -6,7 +6,7 @@ import inspectfrom types import FunctionType, MethodType-from transformers.agents import DuckDuckGoSearchTool, Tool, tool as CreateTool+from smolagents import DuckDuckGoSearchTool, Tool, tool as CreateToolfrom transformers.utils import chat_template_utils, TypeHintParsingExceptionfrom ...embeddings import Embeddings@@ -19,7 +19,7 @@ class ToolFactory:Methods to create tools."""- # Default tools from Transformers Agents+ # Default toolkitDEFAULTS = {"websearch": DuckDuckGoSearchTool()}@staticmethod@@ -28,7 +28,7 @@ class ToolFactory:Creates a new list of tools. This method iterates of the `tools` configuration option and creates a Tool instancefor each entry. This supports the following:- - Transformers Tool instance+ - Tool instance- Dictionary with `name`, `description`, `inputs`, `output` and `target` function configuration- String with a tool alias namediff --git a/src/python/txtai/agent/tool/function.py b/src/python/txtai/agent/tool/function.pyindex 9b17421f..5083e4bf 100644--- a/src/python/txtai/agent/tool/function.py+++ b/src/python/txtai/agent/tool/function.py@@ -2,7 +2,7 @@Function imports"""-from transformers.agents import Tool+from smolagents import Toolclass FunctionTool(Tool):@@ -27,6 +27,13 @@ class FunctionTool(Tool):self.output_type = config.get("output", config.get("output_type", "any"))self.target = config["target"]+ # pylint: disable=C0103+ # Skip forward signature validation+ self.skip_forward_signature_validation = True++ # Validate parameters and initialize tool+ super().__init__()+def forward(self, *args, **kwargs):"""Runs target function.diff --git a/src/python/txtai/pipeline/llm/generation.py b/src/python/txtai/pipeline/llm/generation.pyindex 885ed431..9067f38c 100644--- a/src/python/txtai/pipeline/llm/generation.py+++ b/src/python/txtai/pipeline/llm/generation.py@@ -68,6 +68,16 @@ class Generation:# Extract results based on inputsreturn results[0] if isinstance(text, str) or isinstance(text[0], dict) else results+ def isvision(self):+ """+ Returns True if this LLM supports vision operations.++ Returns:+ True if this is a vision model+ """++ return False+def execute(self, texts, maxlength, stream, stop, **kwargs):"""Runs a list of prompts through a generative model.diff --git a/src/python/txtai/pipeline/llm/huggingface.py b/src/python/txtai/pipeline/llm/huggingface.pyindex ccead9ab..09c5f7bf 100644--- a/src/python/txtai/pipeline/llm/huggingface.py+++ b/src/python/txtai/pipeline/llm/huggingface.py@@ -4,7 +4,7 @@ Hugging Face modulefrom threading import Thread-from transformers import TextIteratorStreamer+from transformers import AutoModelForImageTextToText, TextIteratorStreamerfrom ...models import Models@@ -25,6 +25,9 @@ class HFGeneration(Generation):# Create HuggingFace LLM pipelineself.llm = HFLLM(path, **kwargs)+ def isvision(self):+ return isinstance(self.llm.pipeline.model, AutoModelForImageTextToText)+def stream(self, texts, maxlength, stream, stop, **kwargs):yield from self.llm(texts, maxlength=maxlength, stream=stream, stop=stop, **kwargs)diff --git a/src/python/txtai/pipeline/llm/llm.py b/src/python/txtai/pipeline/llm/llm.pyindex 98350f99..a347bd4c 100644--- a/src/python/txtai/pipeline/llm/llm.py+++ b/src/python/txtai/pipeline/llm/llm.py@@ -62,3 +62,13 @@ class LLM(Pipeline):# Run LLM generationreturn self.generator(text, maxlength, stream, stop, defaultrole, **kwargs)++ def isvision(self):+ """+ Returns True if this LLM supports vision operations.++ Returns:+ True if this is a vision model+ """++ return self.generator.isvision()diff --git a/test/python/testagent.py b/test/python/testagent.pyindex 872585fc..4247c3ac 100644--- a/test/python/testagent.py+++ b/test/python/testagent.py@@ -8,7 +8,7 @@ import unittestfrom datetime import datetime-from transformers.agents import CodeAgent, ReactCodeAgent+from smolagents import CodeAgentfrom txtai.agent import Agentfrom txtai.embeddings import Embeddings@@ -24,10 +24,10 @@ class TestAgent(unittest.TestCase):Test executing main agent loop"""- agent = Agent(llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)+ agent = Agent(llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_steps=1)# Patch LLM to generate answer- agent.process.llm_engine.llm = lambda *args, **kwargs: 'Action:\n{"action": "final_answer", "action_input": "Hi"}<end_action>'+ agent.process.model.llm = lambda *args, **kwargs: 'Action:\n{"name": "final_answer", "arguments": "Hi"}'self.assertEqual(agent("Hello"), "Hi")@@ -37,13 +37,8 @@ class TestAgent(unittest.TestCase):"""agent = Agent(method="code", llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)-self.assertIsInstance(agent.process, CodeAgent)- agent = Agent(method="reactcode", llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)-- self.assertIsInstance(agent.process, ReactCodeAgent)-def testToolsBasic(self):"""Test adding basic function tools@@ -69,7 +64,7 @@ class TestAgent(unittest.TestCase):today = {"name": "today", "description": "Gets the current date and time", "target": DateTime()}- def current(iso) -> str:+ def current(iso: str) -> str:"""Gets the current date and time@@ -82,7 +77,7 @@ class TestAgent(unittest.TestCase):return datetime.today().isoformat() if iso else datetime.today()- agent = Agent(tools=[today, current, "websearch"], llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)+ agent = Agent(tools=[today, current, "websearch"], llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_steps=1)self.assertIsNotNone(agent)self.assertIsInstance(agent.tools["today"](True), str)@@ -108,7 +103,7 @@ class TestAgent(unittest.TestCase):embeddings2 = {"name": "embeddings2", "description": "Searches a test database", "path": index}- agent = Agent(tools=[embeddings1, embeddings2], llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)+ agent = Agent(tools=[embeddings1, embeddings2], llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_steps=1)self.assertIsNotNone(agent)self.assertIsInstance(agent.tools["embeddings1"]("test"), list)diff --git a/test/python/testapi/testapiagent.py b/test/python/testapi/testapiagent.pyindex d791b780..6ea7c46c 100644--- a/test/python/testapi/testapiagent.py+++ b/test/python/testapi/testapiagent.py@@ -52,7 +52,7 @@ class TestAgent(unittest.TestCase):# Patch LLM to generate answeragent = application.get().agents["test"]- agent.process.llm_engine.llm = lambda *args, **kwargs: 'Action:\n{"action": "final_answer", "action_input": "Hi"}<end_action>'+ agent.process.model.llm = lambda *args, **kwargs: 'Action:\n{"name": "final_answer", "arguments": "Hi"}'return clientdiff --git a/test/python/testapi/testopenai.py b/test/python/testapi/testopenai.pyindex f25db225..66b4616d 100644--- a/test/python/testapi/testopenai.py+++ b/test/python/testapi/testopenai.py@@ -79,7 +79,7 @@ class TestOpenAI(unittest.TestCase):# Patch LLM to generate answeragent = application.get().agents["hello"]- agent.process.llm_engine.llm = lambda *args, **kwargs: 'Action:\n{"action": "final_answer", "action_input": "Hi"}<end_action>'+ agent.process.model.llm = lambda *args, **kwargs: 'Action:\n{"name": "final_answer", "arguments": "Hi"}'return clientdiff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 11f637d8..84c7551f 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -51,6 +51,7 @@ class TestOptional(unittest.TestCase):"scipy","sentence_transformers","sklearn.decomposition",+ "smolagents","sounddevice","soundfile","sqlalchemy",@@ -90,6 +91,16 @@ class TestOptional(unittest.TestCase):else:del sys.modules[key]+ def testAgent(self):+ """+ Test missing agent dependencies+ """++ from txtai.agent import Agent++ with self.assertRaises(ImportError):+ Agent(llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_steps=1)+def testANN(self):"""Test missing ANN dependenciesdiff --git a/test/python/testpipeline/testllm/testlitellm.py b/test/python/testpipeline/testllm/testlitellm.pyindex 90ff80fb..ee52e60c 100644--- a/test/python/testpipeline/testllm/testlitellm.py+++ b/test/python/testpipeline/testllm/testlitellm.py@@ -82,3 +82,6 @@ class TestLiteLLM(unittest.TestCase):# Test streamingself.assertEqual(" ".join(x for x in model("The sky is", stream=True)), "blue")++ # Test vision+ self.assertEqual(model.isvision(), False)