Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Initial version of agents framework #804

davidmezzetti6a71db5f4928
diff --git a/Makefile b/Makefile
index 853c2801..de649854 100644
--- a/Makefile
+++ b/Makefile
@@ -32,6 +32,7 @@ test:
# Run tests while calculating code coverage
coverage:
+ coverage run -m unittest discover -v -k testagent -s ${TEST_DIR}
coverage run -m unittest discover -v -k testann -s ${TEST_DIR}
coverage run -m unittest discover -v -k testapi -s ${TEST_DIR}
coverage run -m unittest discover -v -k testapp -s ${TEST_DIR}
diff --git a/src/python/txtai/__init__.py b/src/python/txtai/__init__.py
index 70eaade0..5c520192 100644
--- a/src/python/txtai/__init__.py
+++ b/src/python/txtai/__init__.py
@@ -5,9 +5,11 @@ Base imports
import logging
# Top-level imports
+from .agent import Agent
from .app import Application
from .embeddings import Embeddings
from .pipeline import LLM, RAG
+from .workflow import Workflow
# Configure logging per standard Python library recommendations
logger = logging.getLogger(__name__)
diff --git a/src/python/txtai/agent/__init__.py b/src/python/txtai/agent/__init__.py
new file mode 100644
index 00000000..09d64e06
--- /dev/null
+++ b/src/python/txtai/agent/__init__.py
@@ -0,0 +1,8 @@
+"""
+Agent imports
+"""
+
+from .base import Agent
+from .engine import LLMEngine
+from .factory import ProcessFactory
+from .tool import *
diff --git a/src/python/txtai/agent/base.py b/src/python/txtai/agent/base.py
new file mode 100644
index 00000000..dc9afbeb
--- /dev/null
+++ b/src/python/txtai/agent/base.py
@@ -0,0 +1,50 @@
+"""
+Agent module
+"""
+
+from .factory import ProcessFactory
+
+
+class Agent:
+ """
+ An agent automatically creates workflows to answer multi-faceted user requests. Agents iteratively prompt and/or interface with tools to
+ step through a process and ultimately come to an answer for a request.
+
+ Agents excel at complex tasks where multiple tools and/or methods are required. They incorporate a level of randomness similar to different
+ people working on the same task. When the request is simple and/or there is a rule-based process, other methods such as RAG and Workflows
+ should be explored.
+ """
+
+ def __init__(self, **kwargs):
+ """
+ Creates a new Agent.
+
+ Args:
+ kwargs: arguments to pass to the underlying Agent backend and LLM pipeline instance
+ """
+
+ # Create agent process runner
+ self.process = ProcessFactory.create(kwargs)
+
+ # Tools dictionary
+ self.tools = self.process.toolbox.tools
+
+ def __call__(self, text, maxlength=8192, stream=False, **kwargs):
+ """
+ Runs an agent loop.
+
+ Args:
+ text: instructions to run
+ maxlength: maximum sequence length
+ stream: stream response if True, defaults to False
+ kwargs: additional keyword arguments
+
+ Returns:
+ result
+ """
+
+ # Process parameters
+ self.process.llm_engine.parameters(maxlength)
+
+ # Run agent loop
+ return self.process.run(text, stream=stream, **kwargs)
diff --git a/src/python/txtai/agent/engine.py b/src/python/txtai/agent/engine.py
new file mode 100644
index 00000000..c1f45dcb
--- /dev/null
+++ b/src/python/txtai/agent/engine.py
@@ -0,0 +1,63 @@
+"""
+Engine module
+"""
+
+from transformers.agents import llm_engine
+
+from ..pipeline import LLM
+
+
+class LLMEngine:
+ """
+ Engine backed by a txtai LLM pipeline.
+ """
+
+ def __init__(self, path=None, method=None, **kwargs):
+ """
+ Creates a new LLM engine.
+
+ Args:
+ path: model path or instance
+ method: llm model framework, infers from path if not provided
+ kwargs: model keyword arguments
+ """
+
+ self.llm = path if isinstance(path, LLM) else LLM(path, method, **kwargs)
+ self.maxlength = 8192
+
+ def __call__(self, messages, stop_sequences=None, **kwargs):
+ """
+ Runs LLM inference. This method signature must match the Transformers Agents specification.
+
+ Args:
+ messages: list of messages to run
+ stop_sequences: optional list of stop sequences
+ kwargs: additional keyword arguments
+
+ Returns:
+ result
+ """
+
+ # Get clean message list
+ messages = llm_engine.get_clean_message_list(messages, role_conversions=llm_engine.llama_role_conversions)
+
+ # Get LLM output
+ response = self.llm(messages, maxlength=self.maxlength, stop=stop_sequences, **kwargs)
+
+ # Remove stop sequences from LLM output
+ if stop_sequences is not None:
+ for stop in stop_sequences:
+ if response[-len(stop) :] == stop:
+ response = response[: -len(stop)]
+
+ return response
+
+ def parameters(self, maxlength):
+ """
+ Set LLM inference parameters.
+
+ Args:
+ maxlength: maximum sequence length
+ """
+
+ self.maxlength = maxlength
diff --git a/src/python/txtai/agent/factory.py b/src/python/txtai/agent/factory.py
new file mode 100644
index 00000000..66bbb590
--- /dev/null
+++ b/src/python/txtai/agent/factory.py
@@ -0,0 +1,41 @@
+"""
+Factory module
+"""
+
+from transformers.agents import CodeAgent, ReactCodeAgent, ReactJsonAgent
+
+from .engine import LLMEngine
+from .tool import ToolFactory
+
+
+class ProcessFactory:
+ """
+ Methods to create agent processes.
+ """
+
+ @staticmethod
+ def create(config):
+ """
+ Create an agent process runner. The agent process runner takes a list of tools and an LLM
+ and executes an agent process flow.
+
+ Args:
+ config: agent configuration
+
+ Returns:
+ agent process runner
+ """
+
+ constructor = ReactJsonAgent
+ method = config.pop("method", None)
+ if method == "code":
+ constructor = CodeAgent
+ elif method == "reactcode":
+ constructor = ReactCodeAgent
+
+ # Create LLMEngine
+ llm = config.pop("llm")
+ llm = LLMEngine(**llm) if isinstance(llm, dict) else LLMEngine(llm)
+
+ # Create the agent process
+ return constructor(tools=ToolFactory.create(config), llm_engine=llm, **config)
diff --git a/src/python/txtai/agent/tool/__init__.py b/src/python/txtai/agent/tool/__init__.py
new file mode 100644
index 00000000..cec23e0a
--- /dev/null
+++ b/src/python/txtai/agent/tool/__init__.py
@@ -0,0 +1,7 @@
+"""
+Tool imports
+"""
+
+from .embeddings import EmbeddingsTool
+from .factory import ToolFactory
+from .function import FunctionTool
diff --git a/src/python/txtai/agent/tool/embeddings.py b/src/python/txtai/agent/tool/embeddings.py
new file mode 100644
index 00000000..41d6e89c
--- /dev/null
+++ b/src/python/txtai/agent/tool/embeddings.py
@@ -0,0 +1,69 @@
+"""
+Embeddings module
+"""
+
+from transformers.agents import Tool
+
+from ...embeddings import Embeddings
+
+
+class EmbeddingsTool(Tool):
+ """
+ Tool to execute an Embeddings search.
+ """
+
+ def __init__(self, config):
+ """
+ Creates a new EmbeddingsTool.
+
+ Args:
+ config: embeddings tool configuration
+ """
+
+ # Tool parameters
+ self.name = config["name"]
+ self.description = f"""{config['description']}. Results are returned as a list of dict elements.
+Each result has keys 'id', 'text', 'score'."""
+
+ # Input and output descriptions
+ self.inputs = {"query": {"type": "string", "description": "The search query to perform."}}
+ self.output_type = "any"
+
+ # Load embeddings instance
+ self.embeddings = self.load(config)
+
+ # Validate parameters and initialize tool
+ super().__init__()
+
+ # pylint: disable=W0221
+ def forward(self, query):
+ """
+ Runs a search.
+
+ Args:
+ query: input query
+
+ Returns:
+ search results
+ """
+
+ return self.embeddings.search(query, 5)
+
+ def load(self, config):
+ """
+ Loads an embeddings instance from config.
+
+ Args:
+ config: embeddings tool configuration
+
+ Returns:
+ Embeddings
+ """
+
+ if "target" in config:
+ return config["target"]
+
+ embeddings = Embeddings()
+ embeddings.load(**config)
+
+ return embeddings
diff --git a/src/python/txtai/agent/tool/factory.py b/src/python/txtai/agent/tool/factory.py
new file mode 100644
index 00000000..3ef49356
--- /dev/null
+++ b/src/python/txtai/agent/tool/factory.py
@@ -0,0 +1,119 @@
+"""
+Factory module
+"""
+
+import inspect
+
+from types import FunctionType, MethodType
+
+from transformers.agents import DuckDuckGoSearchTool, Tool, tool as CreateTool
+from transformers.utils import chat_template_utils, TypeHintParsingException
+
+from ...embeddings import Embeddings
+from .embeddings import EmbeddingsTool
+from .function import FunctionTool
+
+
+class ToolFactory:
+ """
+ Methods to create tools.
+ """
+
+ # Default tools from Transformers Agents
+ DEFAULTS = {"websearch": DuckDuckGoSearchTool()}
+
+ @staticmethod
+ def create(config):
+ """
+ Creates a new list of tools. This method iterates of the `tools` configuration option and creates a Tool instance
+ for each entry. This supports the following:
+
+ - Transformers Tool instance
+ - Dictionary with `name`, `description`, `inputs`, `output` and `target` function configuration
+ - String with a tool alias name
+
+ Returns:
+ list of tools
+ """
+
+ tools = []
+ for tool in config.pop("tools", []):
+ # Create tool from function and it's documentation
+ if not isinstance(tool, Tool) and (isinstance(tool, (FunctionType, MethodType)) or hasattr(tool, "__call__")):
+ tool = ToolFactory.createtool(tool)
+
+ # Create tool from input dictionary
+ elif isinstance(tool, dict):
+ # Get target function
+ target = tool.get("target")
+
+ # Create tool from input dictionary
+ tool = (
+ EmbeddingsTool(tool)
+ if isinstance(target, Embeddings) or any(x in tool for x in ["container", "path"])
+ else ToolFactory.createtool(target, tool)
+ )
+
+ # Get default tool, if applicable
+ elif isinstance(tool, str) and tool in ToolFactory.DEFAULTS:
+ tool = ToolFactory.DEFAULTS[tool]
+
+ # Add tool
+ tools.append(tool)
+
+ return tools
+
+ @staticmethod
+ def createtool(target, config=None):
+ """
+ Creates a new Tool.
+
+ Args:
+ target: target object or function
+ config: optional tool configuration
+
+ Returns:
+ Tool
+ """
+
+ try:
+ # Try to create using CreateTool function - this fails when no annotations are available
+ return CreateTool(target)
+ except (TypeHintParsingException, TypeError):
+ return ToolFactory.fromdocs(target, config if config else {})
+
+ @staticmethod
+ def fromdocs(target, config):
+ """
+ Creates a tool from method documentation.
+
+ Args:
+ target: target object or function
+ config: tool configuration
+
+ Returns:
+ Tool
+ """
+
+ name = target.__class__.__name__ if hasattr(target, "__call__") else target.__name__
+ target = target.__call__ if hasattr(target, "__call__") else target
+
+ doc = inspect.getdoc(target).strip()
+ description, parameters, _ = chat_template_utils.parse_google_format_docstring(doc)
+
+ # Get list of required parameters
+ signature = inspect.signature(target)
+ inputs = {}
+ for pname, param in signature.parameters.items():
+ if param.default == inspect.Parameter.empty and pname in parameters:
+ inputs[pname] = {"type": "any", "description": parameters[pname]}
+
+ # Create function tool
+ return FunctionTool(
+ {
+ "name": config.get("name", name.lower()),
+ "description": config.get("description", description),
+ "inputs": config.get("inputs", inputs),
+ "target": config.get("target", target),
+ }
+ )
diff --git a/src/python/txtai/agent/tool/function.py b/src/python/txtai/agent/tool/function.py
new file mode 100644
index 00000000..9b17421f
--- /dev/null
+++ b/src/python/txtai/agent/tool/function.py
@@ -0,0 +1,42 @@
+"""
+Function imports
+"""
+
+from transformers.agents import Tool
+
+
+class FunctionTool(Tool):
+ """
+ Creates a FunctionTool. A FunctionTool takes descriptive configuration and injects it along with a target function
+ into an LLM prompt.
+ """
+
+ # pylint: disable=W0231
+ def __init__(self, config):
+ """
+ Creates a FunctionTool.
+
+ Args:
+ config: `name`, `description`, `inputs`, `output` and `target` configuration
+ """
+
+ # Tool parameters
+ self.name = config["name"]
+ self.description = config["description"]
+ self.inputs = config["inputs"]
+ self.output_type = config.get("output", config.get("output_type", "any"))
+ self.target = config["target"]
+
+ def forward(self, *args, **kwargs):
+ """
+ Runs target function.
+
+ Args:
+ args: positional args
+ kwargs: keyword args
+
+ Returns:
+ result
+ """
+
+ return self.target(*args, **kwargs)
diff --git a/src/python/txtai/pipeline/llm/generation.py b/src/python/txtai/pipeline/llm/generation.py
index b7a0eed9..179acefe 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, stream, **kwargs):
+ def __call__(self, text, maxlength, stream, stop, **kwargs):
"""
Generates text. Supports the following input formats:
@@ -35,6 +35,7 @@ class Generation:
text: text|list
maxlength: maximum sequence length
stream: stream response if True, defaults to False
+ stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
@@ -50,7 +51,7 @@ class Generation:
texts = [formatter.format(self.template, text=x) for x in texts]
# Run pipeline
- results = self.execute(texts, maxlength, stream, **kwargs)
+ results = self.execute(texts, maxlength, stream, stop, **kwargs)
# Streaming generation
if stream:
@@ -62,7 +63,7 @@ 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, stream, **kwargs):
+ def execute(self, texts, maxlength, stream, stop, **kwargs):
"""
Runs a list of prompts through a generative model.
@@ -70,6 +71,7 @@ class Generation:
texts: list of prompts to run
maxlength: maximum sequence length
stream: stream response if True, defaults to False
+ stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
@@ -78,10 +80,10 @@ class Generation:
# Streaming generation
if stream:
- return self.stream(texts, maxlength, stream, **kwargs)
+ return self.stream(texts, maxlength, stream, stop, **kwargs)
# Full response as content elements
- return list(self.stream(texts, maxlength, stream, **kwargs))
+ return self.stream(texts, maxlength, stream, stop, **kwargs)
def clean(self, prompt, result):
"""
@@ -131,7 +133,7 @@ class Generation:
yield (text.lstrip() if not streamed else text)
streamed = True
- def stream(self, texts, maxlength, stream, **kwargs):
+ def stream(self, texts, maxlength, stream, stop, **kwargs):
"""
Streams LLM responses.
@@ -139,6 +141,7 @@ class Generation:
texts: list of prompts to run
maxlength: maximum sequence length
stream: stream response if True, defaults to False
+ stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
diff --git a/src/python/txtai/pipeline/llm/huggingface.py b/src/python/txtai/pipeline/llm/huggingface.py
index 5a86804a..c2769800 100644
--- a/src/python/txtai/pipeline/llm/huggingface.py
+++ b/src/python/txtai/pipeline/llm/huggingface.py
@@ -25,8 +25,8 @@ class HFGeneration(Generation):
# Create HuggingFace LLM pipeline
self.llm = HFLLM(path, **kwargs)
- def stream(self, texts, maxlength, stream, **kwargs):
- yield from self.llm(texts, maxlength=maxlength, stream=stream, **kwargs)
+ def stream(self, texts, maxlength, stream, stop, **kwargs):
+ yield from self.llm(texts, maxlength=maxlength, stream=stream, stop=stop, **kwargs)
class HFLLM(HFPipeline):
@@ -41,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, stream=False, **kwargs):
+ def __call__(self, text, prefix=None, maxlength=512, workers=0, stream=False, stop=None, **kwargs):
"""
Generates text. Supports the following input formats:
@@ -54,6 +54,7 @@ class HFLLM(HFPipeline):
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
+ stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
@@ -68,27 +69,28 @@ class HFLLM(HFPipeline):
texts = [f"{prefix}{x}" for x in texts]
# Combine all keyword arguments
- kwargs = self.parameters(maxlength, workers, **kwargs)
+ kwargs = self.parameters(maxlength, workers, stop, **kwargs)
# Stream response
if stream:
- return StreamingResponse(self.pipeline, texts, **kwargs)()
+ return StreamingResponse(self.pipeline, texts, stop, **kwargs)()
# Run pipeline
- results = self.pipeline(texts, **kwargs)
+ results = self.pipeline(texts, stop_strings=stop, **kwargs)
# Extract generated text
results = [self.extract(result) for result in results]
return results[0] if isinstance(text, str) else results
- def parameters(self, maxlength, workers, **kwargs):
+ def parameters(self, maxlength, workers, stop, **kwargs):
"""
Builds a combined parameter dictionary.
Args:
maxlength: maximum sequence length
workers: number of concurrent workers to use for processing data, defaults to None
+ stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
@@ -115,6 +117,10 @@ class HFLLM(HFPipeline):
self.pipeline.tokenizer.pad_token_id = tokenid
self.pipeline.tokenizer.padding_side = "left"
+ # Set tokenizer when stop strings is set
+ if stop:
+ defaults["tokenizer"] = self.pipeline.tokenizer
+
return {**defaults, **kwargs}
def extract(self, result):
@@ -180,10 +186,11 @@ class StreamingResponse:
Generate text as a streaming response.
"""
- def __init__(self, pipeline, texts, **kwargs):
+ def __init__(self, pipeline, texts, stop, **kwargs):
# Create streamer
self.stream = TextIteratorStreamer(pipeline.tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=5)
kwargs["streamer"] = self.stream
+ kwargs["stop_strings"] = stop
# Create thread
self.thread = Thread(target=pipeline, args=[texts], kwargs=kwargs)
diff --git a/src/python/txtai/pipeline/llm/litellm.py b/src/python/txtai/pipeline/llm/litellm.py
index 1408b632..25db01b7 100644
--- a/src/python/txtai/pipeline/llm/litellm.py
+++ b/src/python/txtai/pipeline/llm/litellm.py
@@ -54,7 +54,7 @@ class LiteLLM(Generation):
# 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):
+ def stream(self, texts, maxlength, stream, stop, **kwargs):
for text in texts:
# LLM API call
result = api.completion(
@@ -62,6 +62,7 @@ class LiteLLM(Generation):
messages=[{"content": text, "role": "prompt"}] if isinstance(text, str) else text,
max_tokens=maxlength,
stream=stream,
+ stop=stop,
**{**self.kwargs, **kwargs}
)
diff --git a/src/python/txtai/pipeline/llm/llama.py b/src/python/txtai/pipeline/llm/llama.py
index f1e4130e..841958a8 100644
--- a/src/python/txtai/pipeline/llm/llama.py
+++ b/src/python/txtai/pipeline/llm/llama.py
@@ -51,9 +51,13 @@ class LlamaCpp(Generation):
# Create llama.cpp instance
self.llm = Llama(path, n_ctx=0, verbose=kwargs.pop("verbose", False), **kwargs)
- def stream(self, texts, maxlength, stream, **kwargs):
+ def stream(self, texts, maxlength, stream, stop, **kwargs):
for text in texts:
- yield from self.messages(text, maxlength, stream, **kwargs) if isinstance(text, list) else self.prompt(text, maxlength, stream, **kwargs)
+ yield from (
+ self.messages(text, maxlength, stream, stop, **kwargs)
+ if isinstance(text, list)
+ else self.prompt(text, maxlength, stream, stop, **kwargs)
+ )
def download(self, path):
"""
@@ -75,7 +79,7 @@ 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, stream, **kwargs):
+ def messages(self, messages, maxlength, stream, stop, **kwargs):
"""
Processes a list of messages.
@@ -83,6 +87,7 @@ class LlamaCpp(Generation):
messages: list of dictionaries with `role` and `content` key-values
maxlength: maximum sequence length
stream: stream response if True, defaults to False
+ stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
@@ -90,12 +95,12 @@ class LlamaCpp(Generation):
"""
# LLM call with messages
- result = self.llm.create_chat_completion(messages=messages, max_tokens=maxlength, stream=stream, **kwargs)
+ result = self.llm.create_chat_completion(messages=messages, max_tokens=maxlength, stream=stream, stop=stop, **kwargs)
# Stream response
yield from self.response(result if stream else [result])
- def prompt(self, text, maxlength, stream, **kwargs):
+ def prompt(self, text, maxlength, stream, stop, **kwargs):
"""
Processes a prompt.
@@ -103,6 +108,7 @@ class LlamaCpp(Generation):
prompt: prompt text
maxlength: maximum sequence length
stream: stream response if True, defaults to False
+ stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
@@ -110,7 +116,7 @@ class LlamaCpp(Generation):
"""
# LLM call with prompt
- result = self.llm(text, max_tokens=maxlength, stream=stream, **kwargs)
+ result = self.llm(text, max_tokens=maxlength, stream=stream, stop=stop, **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 460c7d49..22779b2c 100644
--- a/src/python/txtai/pipeline/llm/llm.py
+++ b/src/python/txtai/pipeline/llm/llm.py
@@ -38,7 +38,7 @@ class LLM(Pipeline):
# Generation instance
self.generator = GenerationFactory.create(path, method, **kwargs)
- def __call__(self, text, maxlength=512, stream=False, **kwargs):
+ def __call__(self, text, maxlength=512, stream=False, stop=None, **kwargs):
"""
Generates text. Supports the following input formats:
@@ -49,6 +49,7 @@ class LLM(Pipeline):
text: text|list
maxlength: maximum sequence length
stream: stream response if True, defaults to False
+ stop: list of stop strings, defaults to None
kwargs: additional generation keyword arguments
Returns:
@@ -59,4 +60,4 @@ class LLM(Pipeline):
logger.debug(text)
# Run LLM generation
- return self.generator(text, maxlength, stream, **kwargs)
+ return self.generator(text, maxlength, stream, stop, **kwargs)
diff --git a/test/python/testagent.py b/test/python/testagent.py
new file mode 100644
index 00000000..6a193a8b
--- /dev/null
+++ b/test/python/testagent.py
@@ -0,0 +1,105 @@
+"""
+Agent module tests
+"""
+
+import os
+import tempfile
+import unittest
+
+from datetime import datetime
+
+from transformers.agents import CodeAgent, ReactCodeAgent
+
+from txtai.agent import Agent
+from txtai.embeddings import Embeddings
+
+
+class TestAgent(unittest.TestCase):
+ """
+ Agent tests.
+ """
+
+ def testExecute(self):
+ """
+ Test executing main agent loop
+ """
+
+ agent = Agent(llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)
+
+ # Patch LLM to generate answer
+ agent.process.llm_engine.llm = lambda *args, **kwargs: 'Action:\n{"action": "final_answer", "action_input": "Hi"}<end_action>'
+
+ self.assertEqual(agent("Hello"), "Hi")
+
+ def testMethod(self):
+ """
+ Test agent process methods
+ """
+
+ 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
+ """
+
+ def today(iso):
+ """
+ Gets the current date and time
+
+ Args:
+ iso: date will be converted to iso format if True
+
+ Returns:
+ current date and time
+ """
+
+ return datetime.today().isoformat() if iso else datetime.today()
+
+ today = {"name": "today", "description": "Gets the current date and time", "target": today}
+
+ def current() -> str:
+ """
+ Gets the current date and time
+
+ Returns:
+ current date and time
+ """
+
+ return datetime.today().isoformat()
+
+ agent = Agent(tools=[today, current, "websearch"], llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)
+
+ self.assertIsNotNone(agent)
+ self.assertIsInstance(agent.tools["today"](True), str)
+
+ def testToolsEmbeddings(self):
+ """
+ Test adding Embeddings as a tool
+ """
+
+ embeddings = Embeddings()
+ embeddings.index(["test"])
+
+ # Generate temp file path and save
+ index = os.path.join(tempfile.gettempdir(), "embeddings.agent")
+ embeddings.save(index)
+
+ embeddings1 = {
+ "name": "embeddings1",
+ "description": "Searches a test database",
+ "target": embeddings,
+ }
+
+ 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)
+
+ self.assertIsNotNone(agent)
+ self.assertIsInstance(agent.tools["embeddings1"]("test"), list)
diff --git a/test/python/testpipeline/testllm/testllm.py b/test/python/testpipeline/testllm/testllm.py
index 0a1e878d..05753c47 100644
--- a/test/python/testpipeline/testllm/testllm.py
+++ b/test/python/testpipeline/testllm/testllm.py
@@ -82,7 +82,15 @@ class TestLLM(unittest.TestCase):
"""
generation = Generation()
- self.assertRaises(NotImplementedError, generation.stream, None, None, None)
+ self.assertRaises(NotImplementedError, generation.stream, None, None, None, None)
+
+ def testStop(self):
+ """
+ Test stop strings
+ """
+
+ model = LLM("sshleifer/tiny-gpt2")
+ self.assertIsNotNone(model("Hello, how are", stop=["you"]))
def testStream(self):
"""