AI Agents
Overview
The AI Agents module provides a robust, configuration-driven framework for building autonomous agents capable of reasoning and tool execution. It implements the ReAct (Reasoning + Acting) pattern, allowing Large Language Models to interact with external environments, execute tools, and observe results to solve complex, multi-step problems.
Key Features
- ReAct Loop: Orchestrates the "Think -> Act -> Observe" cycle automatically.
- Profile-Based Configuration: Define agent behaviors, system prompts, and toolsets entirely in
settings.tomlwithout changing code. - Tool Abstraction: Decouples the agent from specific tool implementations using a robust
Executorstrategy. - Resilience: Handles tool execution errors gracefully, feeding errors back to the LLM for self-correction.
- Observability: Full tracing of the reasoning chain (thoughts, actions, observations).
- Code Execution Capability: Native integration with the Sandbox module via the
CodeInterpreterTool, allowing agents to securely write and execute Python code to solve mathematical or logical problems.
How It Works
- Initialization: The
AgentFactoryreads a specific "Agent Profile" from configuration. It resolves the required LLM connection via theLLMManagerand prepares theToolExecutor. - Execution Loop (
AgentService.run):- Perceive (Optional): The agent can use the
CognitiveServiceto pre-classify user input before submitting it to the ReAct loop, allowing shortcuts for simple responses (Chat) or direct RAG. - Think: The agent sends the conversation history (plus system prompt) to the LLM.
- Decide: The LLM returns either a final answer or a
ToolCall. - Act: If a tool is called, the
SyncToolExecutorexecutes it safely. - Observe: The tool's output (result or error) is added to the history as a
TOOLrole message. - Repeat: The loop continues until the agent provides a final answer or the
max_iterationslimit is reached.
- Perceive (Optional): The agent can use the
Usage Example
from nala.athomic.ai.agents.factory import AgentFactory
async def run_math_task():
# 1. Create the agent defined in 'math_agent' profile
agent = AgentFactory.create(profile_name="math_agent")
# 2. Run the task
# The agent will automatically call the 'calculator' tool if needed
response = await agent.run("What is the square root of 144 multiplied by 5?")
print(response)
# Output: "The result is 60."
Configuration
Agents are configured under [ai.agents] in settings.toml. You define reusable Profiles.
[default.ai.agents]
enabled = true
default_profile = "default_assistant"
# --- Profile: Math Agent ---
[default.ai.agents.profiles.connections.math_agent]
name = "math_agent"
description = "An agent capable of performing calculations."
system_prompt = "You are a helpful assistant. Use tools for math."
# References a connection defined in [ai.llms]
connection_name = "openai_gpt4"
# Constraints
max_iterations = 10
max_execution_time_seconds = 60
# Allowed Tools (must be registered in ToolRegistry)
tools = ["calculator_tool", "unit_converter"]
API Reference
nala.athomic.ai.agents.service.AgentService
Bases: BaseService
The core runtime service for an AI Agent.
This service implements the ReAct (Reasoning + Acting) loop, orchestrating interactions between the LLM (Reasoning Engine) and the Tool Executor (Acting Engine). It optionally supports state persistence via a CheckpointProtocol, allowing for long-running, resilient conversations.
__init__(settings, llm, executor, checkpointer=None, thread_id=None)
Initializes the AgentService.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
AgentProfileSettings
|
Configuration profile defining agent behavior and constraints. |
required |
llm
|
BaseLLM
|
The Language Model provider instance. |
required |
executor
|
BaseToolExecutor
|
The strategy for executing tool calls. |
required |
checkpointer
|
Optional[CheckpointProtocol]
|
Optional provider for persisting agent state. |
None
|
thread_id
|
Optional[str]
|
Unique identifier for the conversation thread. |
None
|
run(input_message, history=None, **kwargs)
async
Executes the agent loop for a given user input.
Orchestrates the Think-Act-Observe cycle until the agent produces a final response or reaches the iteration limit. Handles state hydration and persistence automatically if configured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_message
|
str
|
The user's query or instruction. |
required |
history
|
Optional[List[ChatMessage]]
|
Optional existing conversation history. If persistence is active, stored history takes precedence. |
None
|
**kwargs
|
Any
|
Additional context or overrides. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The final text response from the agent. |
Raises:
| Type | Description |
|---|---|
ServiceNotReadyError
|
If the service is not started. |
TimeoutError
|
If execution exceeds max_execution_time_seconds. |
AgentMaxIterationsError
|
If the loop limit is reached without conclusion. |
nala.athomic.ai.agents.factory.AgentFactory
Factory responsible for creating fully configured AgentService instances.
Delegates LLM resolution to the central LLMManager and orchestrates the creation of Tool Executors and Persistence Checkpointers based on the application configuration.
create(profile_name=None, thread_id=None)
classmethod
Creates a new AgentService instance based on the specified profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile_name
|
Optional[str]
|
The name of the agent profile to load from settings. Defaults to the application's default profile if None. |
None
|
thread_id
|
Optional[str]
|
Optional session identifier. If provided, state persistence will be enabled for this agent instance (if configured globally). |
None
|
Returns:
| Type | Description |
|---|---|
AgentService
|
A configured and ready-to-use AgentService instance. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If agents are disabled or dependencies (LLM) cannot be resolved. |
ValueError
|
If the requested profile does not exist. |
nala.athomic.ai.agents.executors.base.BaseToolExecutor
Bases: BaseService, ToolExecutorProtocol, ABC
Abstract base class for tool execution strategies.
Manages the lifecycle of tools and standardizes execution error handling. Acts as a Service itself, ensuring all dependent tools are ready when connected.
__init__(tool_registry=None)
Initializes the executor as a service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_registry
|
Optional[ToolRegistry]
|
Registry containing available tools. If None, a default registry instance is created. |
None
|
execute_batch(tool_calls)
abstractmethod
async
Executes a batch of tool calls.
Must be implemented by concrete strategies (e.g., Sync, Async, Parallel).
get_tools_for_agent(tool_names)
Retrieves and validates a list of tools required by an Agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_names
|
List[str]
|
List of tool identifiers requested by the agent profile. |
required |
Returns:
| Type | Description |
|---|---|
List[AIToolProtocol]
|
List of ready-to-use tool instances. |
nala.athomic.config.schemas.ai.agents.AgentProfileSettings
Bases: BaseModel
Configuration for a specific Agent Profile. Defines the behavior, capabilities, and constraints of a single agent type.