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 support for agents.md and skill.md. Closes #1014. Closes #1015

davidmezzetti3a46f51f2522
diff --git a/README.md b/README.md
index a494e7d5..090a041b 100644
--- a/README.md
+++ b/README.md
@@ -134,7 +134,7 @@ Agents connect embeddings, pipelines, workflows and other agents together to aut
![agent](https://raw.githubusercontent.com/neuml/txtai/master/docs/images/agent.png)
-txtai agents are built on top of the [smolagents](https://github.com/huggingface/smolagents) framework. This supports all LLMs txtai supports (Hugging Face, llama.cpp, OpenAI / Claude / AWS Bedrock via LiteLLM).
+txtai agents are built on top of the [smolagents](https://github.com/huggingface/smolagents) framework. This supports all LLMs txtai supports (Hugging Face, llama.cpp, OpenAI / Claude / AWS Bedrock via LiteLLM). Agent prompting with [`agents.md`](https://github.com/agentsmd/agents.md) and [`skill.md`](https://agentskills.io/specification) are also supported.
Check out this [Agent Quickstart Example](https://github.com/neuml/txtai/blob/master/examples/agent_quickstart.py). Additional examples are listed below.
diff --git a/docs/agent/configuration.md b/docs/agent/configuration.md
index 0d4f05c5..0d89c30c 100644
--- a/docs/agent/configuration.md
+++ b/docs/agent/configuration.md
@@ -81,15 +81,26 @@ Embeddings indexes have built-in support. Provide the following dictionary confi
### tool
-A tool instance can be provided. Additionally, the following strings load tools directly.
+The following shortcut strings load tools directly. Passing a Tool instance is also supported.
| Tool | Description |
|:------------|:----------------------------------------------------------|
-| http.* | HTTP Path to a Model Context Protocol (MCP) server |
+| http.* | HTTP Path to a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro) server |
| python | Runs a Python action |
+| *.md | Loads a [`skill.md`](https://agentskills.io/specification) file
| websearch | Runs a websearch using the built-in websearch tool |
| webview | Extracts content from a web page |
+## instructions
+
+```yaml
+instructions: string|path
+```
+
+Supports loading an `agents.md` file. Can be provided directly as a string or as a path to a file.
+
+[Read more about agents.md here](https://github.com/agentsmd/agents.md)
+
## method
```yaml
diff --git a/docs/agent/index.md b/docs/agent/index.md
index d5be6e15..4495cbcb 100644
--- a/docs/agent/index.md
+++ b/docs/agent/index.md
@@ -5,6 +5,8 @@
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.
+Agent prompting with [`agents.md`](https://github.com/agentsmd/agents.md) and [`skill.md`](https://agentskills.io/specification) are also supported. [Read the configuration](./configuration/#tool) for more on how to setup those up.
+
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.
diff --git a/docs/usecases.md b/docs/usecases.md
index 4e845c6e..b5d2dd07 100644
--- a/docs/usecases.md
+++ b/docs/usecases.md
@@ -42,7 +42,7 @@ Agents connect embeddings, pipelines, workflows and other agents together to aut
![agent](images/agent.png)
-txtai agents are built on top of the [smolagents](https://github.com/huggingface/smolagents) framework. This supports all LLMs txtai supports (Hugging Face, llama.cpp, OpenAI / Claude / AWS Bedrock via LiteLLM).
+txtai agents are built on top of the [smolagents](https://github.com/huggingface/smolagents) framework. This supports all LLMs txtai supports (Hugging Face, llama.cpp, OpenAI / Claude / AWS Bedrock via LiteLLM). Agent prompting with [`agents.md`](https://github.com/agentsmd/agents.md) and [`skill.md`](https://agentskills.io/specification) are also supported.
Check out this [Agent Quickstart Example](https://github.com/neuml/txtai/blob/master/examples/agent_quickstart.py). Additional examples are listed below.
diff --git a/setup.py b/setup.py
index b087b529..dd1b0e90 100644
--- a/setup.py
+++ b/setup.py
@@ -27,7 +27,7 @@ extras["dev"] = [
"pylint",
]
-extras["agent"] = ["mcpadapt>=0.1.0", "smolagents>=1.23"]
+extras["agent"] = ["jinja2>=3.1.6", "mcpadapt>=0.1.0", "smolagents>=1.23"]
extras["ann"] = [
"annoy>=1.16.3",
diff --git a/src/python/txtai/agent/base.py b/src/python/txtai/agent/base.py
index defc82f3..5d6e9aa4 100644
--- a/src/python/txtai/agent/base.py
+++ b/src/python/txtai/agent/base.py
@@ -2,6 +2,12 @@
Agent module
"""
+import os
+
+from collections import deque
+
+from jinja2 import Template
+
from .factory import ProcessFactory
@@ -15,11 +21,13 @@ class Agent:
should be explored.
"""
- def __init__(self, **kwargs):
+ def __init__(self, template=None, memory=None, **kwargs):
"""
Creates a new Agent.
Args:
+ template: optional prompt jinja template, must include {{ text }} and {{ memory }} placeholders
+ memory: number of prior outputs to keep as "memory", defaults to None for no memory
kwargs: arguments to pass to the underlying Agent backend and LLM pipeline instance
"""
@@ -27,13 +35,21 @@ class Agent:
if "max_iterations" in kwargs:
kwargs["max_steps"] = kwargs.pop("max_iterations")
+ # Custom instructions
+ if "instructions" in kwargs:
+ kwargs["instructions"] = self.instructions(kwargs)
+
# Create agent process runner
self.process = ProcessFactory.create(kwargs)
# Tools dictionary
self.tools = self.process.tools
- def __call__(self, text, maxlength=8192, stream=False, **kwargs):
+ # Agent memory
+ self.memory = deque(maxlen=memory) if memory else None
+ self.template = template
+
+ def __call__(self, text, maxlength=8192, stream=False, reset=False, **kwargs):
"""
Runs an agent loop.
@@ -41,6 +57,7 @@ class Agent:
text: instructions to run
maxlength: maximum sequence length
stream: stream response if True, defaults to False
+ reset: clears previously stored memory if True, defaults to False
kwargs: additional keyword arguments
Returns:
@@ -50,5 +67,73 @@ class Agent:
# Process parameters
self.process.model.parameters(maxlength)
+ # Clear memory, if reset flag set
+ if reset and self.memory:
+ self.memory.clear()
+
# Run agent loop
- return self.process.run(text, stream=stream, **kwargs)
+ output = self.process.run(self.prompt(text), stream=stream, **kwargs)
+
+ # Add output to memory, if necessary
+ if self.memory is not None:
+ self.memory.append((text, output))
+
+ return output
+
+ def prompt(self, text):
+ """
+ Generates the full agent prompt using the input instructions. Adds in agent memory
+ if available.
+
+ Args:
+ text: instructions to run
+
+ Returns:
+ formatted instructions
+ """
+
+ template = (
+ self.template
+ if self.template
+ else """{{ text }}
+{% if memory %}
+Research carefully before answering. This is what you've currently learned. Only review if
+it's relevant to the current topic above.
+
+{{ memory }}
+
+{% endif %}
+"""
+ )
+
+ # pylint: disable=E1133
+ memory = []
+ if self.memory:
+ # Add memory context
+ for request, output in self.memory:
+ memory.append(f"Input: {request}\nOutput: {output}")
+
+ memory = "\n\n".join(memory)
+
+ # Command template with memory
+ return Template(template).render(text=text, memory=memory)
+
+ def instructions(self, config):
+ """
+ Reads and formats custom instructions. Supports agents.md files.
+
+ Args:
+ config: agent configuration
+
+ Returns:
+ agent instructions, if any
+ """
+
+ # Check if this is a file path (i.e. agents.md)
+ path = config.pop("instructions", None)
+ if path and os.path.isfile(path):
+ with open(path, encoding="utf-8") as f:
+ # Read entire file
+ return f"Below is a set of general instructions to follow:\n\n{f.read()}"
+
+ return path
diff --git a/src/python/txtai/agent/tool/factory.py b/src/python/txtai/agent/tool/factory.py
index bb57eddc..12fdc8f3 100644
--- a/src/python/txtai/agent/tool/factory.py
+++ b/src/python/txtai/agent/tool/factory.py
@@ -15,6 +15,7 @@ from transformers.utils import chat_template_utils, TypeHintParsingException
from ...embeddings import Embeddings
from .embeddings import EmbeddingsTool
from .function import FunctionTool
+from .skill import SkillTool
class ToolFactory:
@@ -66,6 +67,10 @@ class ToolFactory:
tools.extend(mcpadapt.core.MCPAdapt({"url": tool}, SmolAgentsAdapter()).tools())
tool = None
+ # Load skill.md files
+ elif isinstance(tool, str) and tool.endswith(".md"):
+ tool = SkillTool(tool)
+
# Add tool
if tool:
tools.append(tool)
diff --git a/src/python/txtai/agent/tool/skill.py b/src/python/txtai/agent/tool/skill.py
new file mode 100644
index 00000000..2290a8cf
--- /dev/null
+++ b/src/python/txtai/agent/tool/skill.py
@@ -0,0 +1,78 @@
+"""
+Skill imports
+"""
+
+import yaml
+
+from smolagents import Tool
+
+
+class SkillTool(Tool):
+ """
+ Creates a SkillTool. A SkillTool loads a skill.md file.
+ """
+
+ # pylint: disable=W0231
+ def __init__(self, path):
+ """
+ Creates a SkillTool.
+
+ Args:
+ path: skill file path
+ """
+
+ # Load skill.md
+ metadata, content = self.load(path)
+
+ # Tool parameters
+ self.name = metadata["name"]
+ self.description = metadata["description"]
+ self.inputs = {"request": {"type": "string", "description": "The user requested action"}}
+ self.output_type = "any"
+ self.target = content
+
+ # Validate parameters and initialize tool
+ super().__init__()
+
+ # pylint: disable=W0221
+ def forward(self, request):
+ """
+ Searchs the skill markdown for the best answer.
+
+ Args:
+ request: user request
+
+ Returns:
+ result
+ """
+
+ return f"""Given the request {request}, find the best answer using the content below.
+
+{self.target}
+"""
+
+ def load(self, path):
+ """
+ Loads a skill.md file.
+
+ Args:
+ path: path to skill.md
+
+ Returns:
+ metadata, content
+ """
+
+ # Read file content
+ with open(path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Stores frontmatter metadata, if any
+ metadata = {}
+
+ # Split by "---"" to separate frontmatter and markdown
+ if content.startswith("---"):
+ _, frontmatter, content = content.split("---", 2)
+ metadata = yaml.safe_load(frontmatter)
+
+ # Return parsed metadata and content
+ return metadata, content
diff --git a/test/python/testagent.py b/test/python/testagent.py
index 5f4c9918..2476ccc4 100644
--- a/test/python/testagent.py
+++ b/test/python/testagent.py
@@ -15,6 +15,20 @@ from smolagents import CodeAgent, PythonInterpreterTool
from txtai.agent import Agent
from txtai.embeddings import Embeddings
+# agents.md content
+AGENTS = """
+Basic instructions here
+"""
+
+# Sample skill.md content
+SKILL = """---
+name: hello
+description: says hello world
+---
+
+Says hello world
+"""
+
class TestAgent(unittest.TestCase):
"""
@@ -33,6 +47,45 @@ class TestAgent(unittest.TestCase):
self.assertEqual(agent("Hello"), "Hi")
+ def testInstructions(self):
+ """
+ Test loading an agents.md file
+ """
+
+ # Test loading instructions from file
+ agents = os.path.join(tempfile.gettempdir(), "agents.md")
+ with open(agents, "w", encoding="utf-8") as output:
+ output.write(AGENTS)
+
+ agent = Agent(instructions=agents, llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)
+ agent.process.model.llm = lambda *args, **kwargs: 'Action:\n{"name": "final_answer", "arguments": "Hi"}'
+ self.assertEqual(agent("Hello"), "Hi")
+
+ # Test loading from memory
+ agent = Agent(instructions=AGENTS, llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)
+ agent.process.model.llm = lambda *args, **kwargs: 'Action:\n{"name": "final_answer", "arguments": "Hi"}'
+ self.assertEqual(agent("Hello"), "Hi")
+
+ def testMemory(self):
+ """
+ Test agent memory
+ """
+
+ agent = Agent(llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_steps=1, memory=5)
+
+ # Patch LLM to generate answer
+ agent.process.model.llm = lambda *args, **kwargs: 'Action:\n{"name": "final_answer", "arguments": "Hi"}'
+
+ self.assertEqual(agent("Hello"), "Hi")
+ self.assertEqual(agent("Hello"), "Hi")
+
+ # Test that results are stored in memory
+ self.assertEqual(len(agent.memory), 2)
+
+ # Test resetting memory
+ self.assertEqual(agent("Hello", reset=True), "Hi")
+ self.assertEqual(len(agent.memory), 1)
+
def testMethod(self):
"""
Test agent process methods
@@ -41,6 +94,19 @@ class TestAgent(unittest.TestCase):
agent = Agent(method="code", llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)
self.assertIsInstance(agent.process, CodeAgent)
+ def testSkill(self):
+ """
+ Test running a skill from a skill.md file
+ """
+
+ skill = os.path.join(tempfile.gettempdir(), "skill.md")
+ with open(skill, "w", encoding="utf-8") as output:
+ output.write(SKILL)
+
+ agent = Agent(tools=[skill], llm="hf-internal-testing/tiny-random-LlamaForCausalLM", max_iterations=1)
+
+ self.assertIsInstance(agent.tools["hello"]("say hello"), str)
+
def testToolsBasic(self):
"""
Test adding basic function tools