Building AI Agents with Self-Awareness and Skill-Based Tool Access
Learn how to build capable AI agents by combining LLMs with tools, memory, and control loops. This article covers skill-based tool access, agent self-awareness, multimodal input pipelines, and the safety boundaries needed for high-risk operations and self-modifying systems.
From Talking to Doing: The Basic Anatomy of an AI Agent
A conversational LLM on its own can only generate text based on training data and context. It cannot read live data, modify files, send messages, or trigger external services. An agent fills these gaps with four components:
- Model: Understands intent, plans steps, and generates tool-call parameters.
- Tools: Encapsulate access to external systems, such as file read/write, network requests, and messaging.
- State and memory: Store conversation context, task progress, and user preferences.
- Control loop: Repeatedly executes “observe, decide, call a tool, read the result” until the task is complete or a stop condition is triggered.
The key engineering shift is closing the loop. The model’s output is no longer just text for the user—it can become a constrained action, and the action’s result feeds back into the model’s context. The reliability of this loop depends on clear boundaries at every step, which is the guiding theme of the designs below.
Two Approaches to Tool Access: Protocol-Based and Skill-Based
Protocol-Based Access
The protocol-based approach gives every tool a unified, structured description—name, purpose, parameter types, and return format. The model sees these descriptions on each request and generates calls accordingly. The advantage is standardized interfaces that interoperate across different clients and tools.
It has three main drawbacks. First, tool definitions continuously consume the context window; as the number of tools grows, less space remains for the actual task. Second, tools have no natural way to compose, so multi-step operations often require the model to stitch results across multiple round trips—a long, error-prone chain. Third, debugging is hard: a failed call makes it difficult to distinguish parameter issues from permission or server-side issues.
Skill-Based Access
The skill-based approach packages a capability as a discoverable directory containing documentation, an entry script, and dependency declarations. The agent first reads a short directory description and only loads the full documentation and entry point when a task requires it.
This mirrors how command-line tools work. Training corpora contain abundant CLI examples, so models are familiar with the “text in, text out, combine via pipes” pattern. Designing capabilities as small, focused commands that the agent chains with pipes or scripts is usually more stable than exposing many complex interfaces at once.
The following code shows the basic idea of on-demand skill discovery:
from dataclasses import dataclass, fieldfrom pathlib import Pathimport json@dataclassclass Skill:name: strdescription: strentry: Pathrequires: list[str] = field(default_factory=list)class SkillRegistry:"""Scans the skill directory, keeping only lightweight metadata.Full documentation is loaded at call time."""def __init__(self, root: Path):self.root = rootself._skills: dict[str, Skill] = {}def scan(self) -> None:for manifest_path in self.root.glob("*/manifest.json"):data = json.loads(manifest_path.read_text(encoding="utf-8"))skill = Skill(name=data["name"],description=data["description"],entry=manifest_path.parent / data["entry"],requires=data.get("requires", []),)self._skills[skill.name] = skilldef catalog(self) -> list[dict]:"""Returns a compact catalog for context injection:only names and one-line descriptions."""return [{"name": s.name, "description": s.description}for s in self._skills.values()]def get(self, name: str) -> Skill:if name not in self._skills:raise KeyError(f"Unregistered skill: {name}")return self._skills[name]
The key idea is a two-layer information split: only the catalog lives in context, while full documentation and entry points are loaded on demand. Even with dozens of skills, the context overhead stays manageable.
Comparing the Two Approaches
| Dimension | Protocol-Based | Skill-Based |
|---|---|---|
| Context usage | Grows linearly with tool count | Compact catalog, on-demand loading |
| Multi-step composition | Relies on multiple model round trips | Can be done locally via scripts or pipes |
| Debugging | Requires cross-layer investigation | Each entry point runs standalone |
| Standardization | High; easy cross-system interoperability | Depends on directory conventions; requires team-wide standards |
| Permission control | Usually managed centrally on the server | Must be validated at each entry point |
The two approaches are not mutually exclusive. Use protocol-based access for external standard interfaces, and skill-based packaging for high-frequency internal tasks. The core criterion: expose the minimum content to the model that is still sufficient to complete the task.
Making the Agent Understand Itself: Implementing Self-Awareness
In an engineering context, self-awareness means the agent can access information about its own runtime state, such as:
- The model identifier and version currently in use;
- The operating system and runtime version;
- The directory containing the source code;
- The locations of documentation and configuration files;
- The current list of available tools and skills.
This information serves three practical purposes. First, when troubleshooting, the agent can read the runtime environment description before diagnosing a problem, reducing blind guessing. Second, when users ask about system capabilities, the agent can answer from a real inventory, lowering the risk of hallucinated features. Third, the agent can consult its own documentation, shortening the path that would otherwise require human intervention.
When implementing this, generate a read-only runtime manifest at startup rather than letting the agent piece together information on the fly:
import osimport platformfrom datetime import datetime, timezonefrom pathlib import Pathfrom types import MappingProxyTypedef build_runtime_manifest(model_id: str,source_dir: Path,docs_dir: Path,tool_names: list[str],) -> MappingProxyType:manifest = {"model": model_id,"os": platform.system(),"python": platform.python_version(),"source_dir": str(source_dir),"docs_dir": str(docs_dir),"tools": sorted(tool_names),"started_at": datetime.now(timezone.utc).isoformat(),"pid": os.getpid(),}# Read-only view to prevent accidental modification at runtimereturn MappingProxyType(manifest)
The boundaries of self-awareness also need to be explicit. An agent may read information about itself, but modifying core configuration, switching models, or changing permissions should be done by humans or controlled processes.
Handling Multimodal Input Pipelines
Agents often receive voice messages through instant messaging channels. From arrival to reply, a voice message typically passes through these stages:
- Reception and validation: Check file format, size, and sender identity.
- Speech-to-text: Call a speech recognition service to generate text and record the confidence score.
- Intent understanding: The model determines the user’s goal from the transcript and asks for clarification when needed.
- Execution and feedback: Invoke the relevant skill and convert the result into a reply.
- Logging and audit: Save the inputs, outputs, and latency of each stage.
Every stage should have clear timeout and failure policies. If speech recognition fails, the system should prompt the user to resend rather than handing empty text to the model. When transcript confidence is low, the system should first have the user confirm key details such as time, amount, and recipient.
Chaining multiple model capabilities into a pipeline means users only need to send one message—but the risk is that an error in one stage amplifies downstream. Logs must therefore pinpoint the exact stage where a failure occurred.
Safety Boundaries for Self-Modifying Systems
Some agents can read and modify their own source code to fix defects or add skills. This is highly efficient but demands strict boundaries. Recommended principles:
- Version control first: Make all changes on separate branches with complete commit history, so any change can be reverted.
- Testing gates: Require unit tests and integration tests on critical paths before merging.
- Human review: Code changes involving permissions, network access, or data storage must be human-reviewed before merging.
- Sandboxed execution: Run new versions in an isolated environment for a period and confirm normal behavior before promoting to production.
One bottom line must hold: an agent should never be able to modify its own review rules or bypass its own tests. Otherwise, the safety mechanism itself becomes a modifiable object.
Confirmation Mechanisms for High-Risk Operations
Operations like deleting files, sending messages, deploying services, and changing permissions are hard to reverse once executed. The recommended practice is an explicit confirmation step:
HIGH_RISK_ACTIONS = {"delete_file", "send_message", "deploy", "change_permission"}def execute_action(action: str, params: dict, confirmed_by_user: bool) -> str:if action in HIGH_RISK_ACTIONS and not confirmed_by_user:return f"Action {action} requires user confirmation and has been paused. Please confirm before execution."return run_action(action, params) # run_action is the actual execution function, omitted here
The confirmation prompt should include a complete description of the target, such as the file path, recipient, or target environment. If the actual target at execution time differs from what the user confirmed, the system must stop and re-confirm.
Credentials, Permissions, and Naming Resources
Least Privilege and Credential Storage
When an agent accesses external services, assign each tool its own least-privilege credentials. Credentials should never be written into code or logs; inject them via environment variables or issue and rotate them through a dedicated secrets management service.
Logs also need redaction. Tool-call records may keep parameter names and execution results, but tokens, passwords, and personal information should be replaced with placeholders.
Project Naming and Account Squatting Risks
When an open-source project or product gains traction quickly, its name, package name, and social media accounts are often squatted by third parties. This causes brand confusion and may lead users to download counterfeit versions.
At project kickoff, take these measures:
- Check and claim matching accounts on major code hosting platforms, package registries, and social platforms early;
- Run a trademark search to avoid conflicts with existing registered trademarks;
- Maintain unified official domains and distribution channels, and publish them in the documentation;
- Use two-person account management to avoid losing control if a single account is compromised.
Implications for Application Design
Because agents understand user context and execute actions directly, some feature-oriented apps may see their entry points replaced by conversation. Information lookup, reminders, and simple form-filling are the most vulnerable scenarios.
On the other hand, high-frequency interaction, complex visualization, and compliance-heavy scenarios still need dedicated interfaces and systems. The criteria come down to three questions: Can the task be clearly described in natural language? Does the result need visual presentation? Does the operation require strict audit trails and approvals?
The realistic conclusion is that “some applications will become capability modules of agents,” not that “most applications will disappear.”
Adoption Recommendations
When introducing agent systems to a team, proceed in this order:
- Pilot in low-risk scenarios, such as internal knowledge Q&A or log analysis, avoiding direct access to production data.
- List tools and define permissions, granting each tool only the minimum access needed for its task.
- Build an evaluation set covering normal requests, edge-case inputs, and malicious inputs, and rerun it after every model or prompt change.
- Invest in observability, logging the inputs, outputs, latency, and failure reasons of every tool call.
- Establish human confirmation and rollback mechanisms, ensuring high-risk operations can be blocked and erroneous changes can be reverted.
An agent’s value depends on the quality of its engineering constraints. The more capable the agent, the more it needs clear boundaries, traceable records, and reliable rollback.
