Skip to content

Registration Methods

Agent registration methods allow you to expose functions, classes, and modules to your agents. These methods control what capabilities agents have access to and how they're presented in the agent's context.

Registration happens on Agent instances - create an agent first, then register capabilities using these methods.

.fn() - Function Registration

Register individual functions as agent capabilities.

agent.fn(
    func: Callable | None = None,
    *,
    name: str | None = None,
    visibility: Literal["high", "medium", "low"] = "high",
    docstring: str | None = None
)

Parameters

Parameter Type Default Description
func Callable | None None Function to register (filled automatically when used as decorator)
name str | None None Override the function name in the agent environment
visibility Literal["high", "medium", "low"] "high" How prominently to show this function in agent context
docstring str | None None Override the function's docstring for the agent
host_fs_access bool False Allow this function to access the host filesystem even when VFS/IsolatedFS is active (see FileSystem docs)
network_access bool False Allow this function to make network connections (see Security - Network Access)

Visibility Levels

Level What Agent Sees Best For
"high" Function signature + full docstring Custom functions or complex APIs where detailed guidance is needed.
"medium" Function signature only Familiar APIs where the agent only needs a reminder of the function's name and parameters.
"low" Available for use but not shown in context Common libraries (e.g., numpy, pandas) that the LLM is already trained on. Saves context space.

Tip: For libraries registered with visibility="low", consider pairing them with a skill. Use agent.skill() to register documentation that the agent reads on-demand. This gives you the best of both worlds: minimal context overhead from low-visibility registration, with detailed usage guidance available when the agent needs it.

from importlib.resources import files

agent.module(my_lib, visibility="low", recursive=True)
agent.skill(files("my_lib") / "skills" / "my_lib" / "SKILL.md")

Usage Patterns

As a Decorator

from agex import Agent

agent = Agent()

@agent.fn
def calculate_square_root(x: float) -> float:
    """Calculate the square root of a number."""
    return x ** 0.5

@agent.fn(visibility="medium")
def helper_function(data: list) -> int:
    """Process data and return count."""
    return len(data)

Direct Registration

import math

# Register existing functions
agent.fn(math.sin)
agent.fn(math.cos, visibility="low")
agent.fn(len, name="count_items")

Custom Docstrings

Useful when the original docstring is too technical or verbose for agents:

@agent.fn(docstring="Add two numbers together quickly")
def add(a: float, b: float) -> float:
    """
    Performs mathematical addition of two floating-point numbers.

    This function implements the standard IEEE 754 floating-point
    addition operation with proper handling of edge cases...
    """
    return a + b

.cls() - Class Registration

Register classes, giving agents access to their attributes and methods.

# Type alias for include/exclude patterns
Pattern = str | list[str] | Callable[[str], bool]

agent.cls(
    cls: type,
    *,
    include: Pattern = "*",
    exclude: Pattern = "_*",
    visibility: Literal["high", "medium", "low"] = "high",
    constructable: bool = True,
    configure: dict[str, MemberSpec] | None = None
)

Parameters

Parameter Type Default Description
cls type Class to register
include Pattern "*" Pattern for members to include
exclude Pattern "_*" Pattern for members to exclude
visibility Literal["high", "medium", "low"] "high" How prominently to show this class
constructable bool True Whether agents can create instances
configure dict[str, MemberSpec] | None None Per-member configuration overrides
host_fs_access bool False Allow this class and its methods to access the host filesystem (see FileSystem docs)
network_access bool False Allow this class and its methods to make network connections (see Security - Network Access)

Usage Patterns

As a Decorator

Use the decorator pattern for classes you are defining in your own code. This is the most common pattern for exposing your application's data structures to an agent.

from dataclasses import dataclass

@agent.cls
@dataclass
class User:
    name: str
    email: str

Direct Registration

Use the direct call pattern to register classes that are imported from external libraries, such as pandas or even the Python standard library.

import pandas as pd

# Register the pandas DataFrame class with specific methods
agent.cls(
    pd.DataFrame,
    include=["head", "tail", "describe", "info"],
    visibility="medium"
)

Include/Exclude Patterns

Pattern types work the same for both .cls() and .module() registration:

  • String (Glob): "get_*", "*" - matches names using shell-style wildcards
  • List of Strings: ["name", "email"] - explicit member names or glob patterns
  • Predicate Function: lambda name: not name.startswith('_') - custom logic

Per-Member Configuration (configure parameter)

Both .cls() and .module() support fine-grained per-member configuration using MemberSpec:

from agex import MemberSpec

# For classes
agent.cls(
    DatabaseService,
    configure={
        "connect": MemberSpec(visibility="high"),     # Promote method
        "config_path": MemberSpec(visibility="low"),  # Demote attribute
        "admin_reset": MemberSpec(visibility="low"),  # Hide dangerous method
    }
)

# For modules (supports dot notation for class members)
agent.module(
    math,
    configure={
        "sin": MemberSpec(visibility="high"),                    # Promote function
        "SomeClass.method": MemberSpec(visibility="low"),        # Configure class member
    }
)

MemberSpec Properties:

  • visibility: Override visibility for this specific member
  • docstring: Custom docstring for the agent (for functions/methods)
  • constructable: Whether class can be instantiated (for classes in modules)

.module() - Module Registration

Register functions, classes, and constants from entire modules.

agent.module(
    module: ModuleType,
    *,
    name: str | None = None,
    include: Pattern = "*",
    exclude: Pattern = ["_*", "*._*"],
    visibility: Literal["high", "medium", "low"] = "medium",
    configure: dict[str, MemberSpec] | None = None,
    recursive: bool = False
)

Parameters

Parameter Type Default Description
module ModuleType Module or object to register
name str | None None Name in agent environment (required for non-modules)
include Pattern "*" Pattern for members to include
exclude Pattern ["_*", "*._*"] Pattern for members to exclude
visibility Literal["high", "medium", "low"] "medium" Default visibility for registered items
configure dict[str, MemberSpec] | None None Per-member configuration overrides
recursive bool False If True, recursively register all sub-modules of the given module.
host_fs_access bool False Allow all functions/classes in this module to access the host filesystem (see FileSystem docs)
network_access bool False Allow all functions/classes in this module to make network connections (see Security - Network Access)

A Note on Instance Registration

While .module() is typically used for Python modules, it can also register the methods of a class instance. This is done to maintain a consistent API based on a key design principle:

  • agent.fn() registers a single callable.
  • agent.module() registers a namespace containing multiple callables.

From this perspective, an instance (a collection of methods) is treated similarly to a module (a collection of functions).

However, because instances do not have an intrinsic __name__ attribute like modules do, you must provide the name parameter when registering an instance. This gives the agent a handle to refer to the object in its code.

# Registering an instance requires the 'name' parameter
db_connection = sqlite3.connect(":memory:")
agent.module(db_connection, name="db", include=["execute", "commit"])

Recursive Registration

For large libraries with many sub-modules (like pandas or numpy), registering each component individually is tedious. By setting recursive=True, agex will automatically discover and register all public sub-modules within a package.

This is the recommended way to register large, trusted libraries. It uses the same include, exclude, and visibility settings for all discovered sub-modules.

import pandas as pd

# Automatically register all of pandas, excluding file I/O methods
agent.module(
    pd,
    recursive=True,
    visibility="low",
    exclude=["_*", "*._*", "read_*", "*.to_*"]
)

Note: The recursive option is only valid for modules, not for class instances.

Recursive Modules and view(agent)

With recursive=True, agents can resolve nested members at runtime (e.g., routing.shortest_path). However, view(agent) only shows top-level members and explicitly configured dotted members — it does not enumerate entire subpackages.

To make key nested functions visible in view(agent), promote them via configure:

import osmnx as ox
from agex import Agent, MemberSpec

agent = Agent()
agent.module(
    ox,
    visibility="low",
    recursive=True,
    configure={
        "geocoder.geocode": MemberSpec(visibility="high"),
        "routing.shortest_path": MemberSpec(visibility="high"),
    },
)

Alternatively, register submodules directly: agent.module(ox.routing, include=["shortest_path"], visibility="high")

Usage Examples

import math, random, sqlite3
import numpy as np
import pandas as pd

# Standard library - broad registration with low visibility
agent.module(math, visibility="low")
agent.module(random, include=["choice", "randint", "shuffle"])

# Third-party libraries  
agent.module(np, include="*", exclude=["_*", "test*"], visibility="low")
agent.module(pd, include=["DataFrame", "Series", "read_csv"])

# Class member targeting with dot notation
agent.module(requests, include=["Session", "Session.get", "Session.post"])

# Instance registration (requires name parameter)
db = sqlite3.connect("data.db")
agent.module(db, name="db", include=["execute", "commit", "close"])

.skill() - Skill Registration

Register documentation files that teach agents how to use specific libraries or accomplish specific tasks. Skills are mounted read-only at /skills/<name>/SKILL.md and listed in the agent's system message.

agent.skill(source: bytes | Path-like)

Parameters

Parameter Type Description
source bytes \| Path-like Skill content as raw bytes, or a Path / importlib.resources Traversable to read from

How It Works

  1. Registration: Call agent.skill() one or more times to collect skill files
  2. Mounting: At task execution, skills are mounted as a read-only overlay at /skills/ — no VFS writes, no state commits
  3. System Message: Skill names and descriptions (from YAML frontmatter) are listed in the system message
  4. On-Demand: The agent reads the full skill content via cat /skills/<name>/SKILL.md only when needed

SKILL.md Format

Each skill is a Markdown file with optional YAML frontmatter:

---
name: my-library
description: Short description of what this skill covers
---

# my-library

Detailed instructions, examples, and patterns for the agent...
Field Required Description
name No Display name (defaults to parent directory name or filename stem)
description No One-line description shown in the skill listing

Usage Examples

from pathlib import Path
from importlib.resources import files
from agex import Agent

agent = Agent()

# From a package resource (recommended for libraries)
agent.skill(files("calgebra") / "skills" / "calgebra" / "SKILL.md")
agent.skill(files("calgebra") / "skills" / "gcal" / "SKILL.md")

# From a local file
agent.skill(Path("./my-custom-skill.md"))

# From raw bytes (useful for dynamic/generated skills)
agent.skill(b"""---
name: my-tool
description: How to use my-tool effectively
---

# my-tool

Call `my_tool.run()` with a config dict...
""")

Pairing Skills with Low-Visibility Modules

Skills work especially well alongside visibility="low" registrations. The module is available but hidden from context, while the skill provides detailed guidance on-demand:

import calgebra
from importlib.resources import files

# Register with low visibility (agent knows it, but no context overhead)
agent.module(calgebra, visibility="low", recursive=True)

# Pair with a skill (detailed docs, read on-demand)
agent.skill(files("calgebra") / "skills" / "calgebra" / "SKILL.md")

Next Steps

  • Agent Creation: See Agent for Agent class documentation
  • Task Definition: See Task for defining agent behavior using @agent.task
  • State Management: See State for persistent memory in agent tasks
  • Debugging: See View for inspecting registered capabilities