Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Neuml Txtai Agent Init

From Leeroopedia


Knowledge Sources
Domains NLP, Agent
Last Updated 2026-02-09 00:00 GMT

Overview

Concrete tool for configuring and constructing an autonomous AI agent that combines LLM reasoning with tool use, provided by the txtai library.

Description

Agent.__init__ is the constructor for the txtai Agent class. It accepts a prompt template, a memory size, and an open set of keyword arguments, and assembles a fully configured agent backed by a smolagents CodeAgent or ToolCallingAgent.

The constructor performs the following steps:

  1. Backward compatibility: If max_iterations is present in kwargs, it is renamed to max_steps to match the current smolagents API.
  2. Instructions processing: If an "instructions" key is present, it is processed by the instructions method. If the value is a file path (e.g., agents.md), the file is read and prefixed with a preamble. Otherwise, the string is used as-is.
  3. Process creation: ProcessFactory.create(kwargs) is called, which:
    • Pops "method" to determine the agent backend (CodeAgent for "code", ToolCallingAgent otherwise).
    • Pops "model" or "llm" and wraps it in a PipelineModel.
    • Pops "tools" and passes it through ToolFactory.create.
    • Constructs the smolagents agent with the remaining kwargs (e.g., max_steps).
  4. Tool dictionary: self.tools is set to the process's tool dictionary for external introspection.
  5. Memory initialisation: If memory is a positive integer, a collections.deque(maxlen=memory) is created. Otherwise, self.memory is None.

Usage

Use Agent.__init__ whenever you need to create a new autonomous agent. Configuration can be passed programmatically as keyword arguments or loaded from a YAML/JSON file and unpacked. The constructor is the only setup step required before calling the agent with a query.

Code Reference

Source Location

  • Repository: txtai
  • File: src/python/txtai/agent/base.py
  • Lines: 24-50

Signature

class Agent:
    def __init__(self, template=None, memory=None, **kwargs):
        # Backwards compatibility
        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

        # Agent memory
        self.memory = deque(maxlen=memory) if memory else None
        self.template = template

Import

from txtai.agent import Agent

I/O Contract

Inputs

Name Type Required Description
template str No Jinja2 template string with {{ text }} and {{ memory }} placeholders. Controls prompt rendering. None uses the built-in default template.
memory int No Number of prior (request, response) pairs to retain. None disables memory.
method str No Agent execution method: "code" for CodeAgent (generates Python) or "toolcalling" / None for ToolCallingAgent (structured tool calls).
model / llm str or dict Yes Model path string or configuration dict for the LLM. Wrapped in PipelineModel.
tools list No List of tool specifications (see ToolFactory.create for accepted formats).
max_steps int No Maximum reasoning-action iterations before forcing a final answer.
instructions str No System-level instructions string or path to an agents.md file.

Outputs

Name Type Description
instance Agent Configured Agent instance with self.process (smolagents agent), self.tools (dict), self.memory (deque or None), and self.template (str or None).

Usage Examples

Basic Example

from txtai.agent import Agent

# Minimal agent with tool-calling method
agent = Agent(
    model="huggingface-hub/Meta-Llama-3-8B-Instruct",
    tools=["websearch"],
    max_steps=5,
)

With Memory and Custom Template

from txtai.agent import Agent

agent = Agent(
    template="""Answer the following question: {{ text }}
{% if memory %}
Prior conversation:
{{ memory }}
{% endif %}
""",
    memory=3,
    model="huggingface-hub/Meta-Llama-3-8B-Instruct",
    tools=["websearch", "python"],
    method="code",
    max_steps=10,
    instructions="Always provide citations for factual claims.",
)

With Custom Functions and Embeddings

from txtai.agent import Agent
from txtai.embeddings import Embeddings

embeddings = Embeddings(path="sentence-transformers/all-MiniLM-L6-v2")
embeddings.index([{"id": "0", "text": "The speed of light is 299,792,458 m/s."}])

def unit_convert(value, from_unit, to_unit):
    """Convert between units."""
    conversions = {("m/s", "km/h"): 3.6}
    return value * conversions.get((from_unit, to_unit), 1)

agent = Agent(
    model="huggingface-hub/Meta-Llama-3-8B-Instruct",
    tools=[
        {
            "name": "physics_facts",
            "description": "Search physics knowledge base",
            "target": embeddings,
        },
        {
            "name": "unit_convert",
            "description": "Convert a value between measurement units",
            "inputs": {
                "value": {"type": "number", "description": "Numeric value to convert"},
                "from_unit": {"type": "string", "description": "Source unit"},
                "to_unit": {"type": "string", "description": "Target unit"},
            },
            "target": unit_convert,
        },
    ],
    memory=5,
    max_steps=8,
)

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment