How to Build General-Purpose AI Agents: A Practical Guide to Model Integration and Tooling

    This guide explains what makes a general-purpose AI agent genuinely useful and how to build one reliably. It covers the division of labor between the model, tools, and orchestration layer; four capabilities to verify before integrating a model; how to stand up a minimal working loop; permission and error-handling design for tool execution; the risks hidden in memory and external content; cost control across the entire task chain; evaluation with repeatable tasks; and a progressive authorization path from individual trials to enterprise deployment.

    1. Whether an Agent Is Useful Depends on Whether Tasks Complete Reliably

    With an ordinary chat system, users usually have to turn answers into actions themselves: copying code, looking up references, organizing files, and then feeding the results back to the model. An agent tries to connect these steps so the model can choose tools based on a goal, read results, adjust its plan, and keep going until the task is done or a stop condition is triggered.

    For example, a user might ask: “Organize the project documentation in a given directory, list the missing configuration items, and produce a review report.” An agent with the appropriate tool permissions can first inspect the directory structure, then read the relevant files, identify problems by rule, and finally output the report. What matters here is not how much the agent says, but whether the report is accurate, whether the evidence is sufficient, and whether it avoided modifying files beyond its authority during execution.

    So “useful” should not be understood as “fully automatic completion of everything from a single sentence.” More reasonable criteria include:

    • Whether it correctly understands the goal and its boundaries;
    • Whether it selects appropriate tools and passes valid parameters;
    • Whether it recovers sensibly after failures;
    • Whether it can finish within budget and permission limits;
    • Whether the final result can be verified and traced.

    The closer an agent gets to real business scenarios, the more it needs to shift from “demo effect” to “engineering reliability.”

    2. First Understand the Division of Labor Among Model, Tools, and Orchestration Layer

    A general-purpose agent system usually consists of a model, tools, and an orchestration layer. Each has a different responsibility, and missing any one of them can affect task execution.

    1. The Model Handles Understanding and Decision-Making

    The model reads the user’s goal, the historical context, and tool results, then generates a suggested next action or a final answer. It can help break down tasks, judge what information needs to be retrieved, and explain execution results.

    But content generated by the model is not the same as fact, and certainly not the same as a successful execution. When it proposes the intent to “read a file,” an external program must actually carry it out; when it judges that “the modification is complete,” that also needs file diffs or check results as evidence.

    2. Tools Handle Interaction With the External Environment

    Tools can provide capabilities such as file reading, structured data queries, text search, code execution, and sending notifications. The model submits a call request through an agreed data structure, the host program validates the parameters and executes, then returns the result to the model.

    The stronger a tool’s capabilities, the higher the risk. Reading a specified document and deleting a directory are clearly not operations of the same level, so they cannot be handled with a uniform authorization policy.

    3. The Orchestration Layer Controls the Execution Process

    The orchestration layer manages tool registration, call validation, context organization, error handling, logging, budget limits, and stop conditions. It decides which actions can run automatically and which must request user confirmation.

    The execution process can be understood as:

    User goal → Model proposes action → Orchestration layer validates → Tool executes → Result returns → Model continues judging

    This loop should not run indefinitely. When the goal is reached, the budget is exhausted, failures repeat, or a safety limit is triggered, it should stop and explain to the user what was completed and what problems remain.

    3. Before Integrating a Model, Verify These Four Capabilities

    1. Whether Tool Calling Is Stable

    For an agent that needs to execute tasks, tool calling usually affects the experience more directly than copywriting ability. The key is not just whether the model can output one correctly formatted request, but whether it can consistently:

    • Choose the correct tool among multiple tools;
    • Provide complete, valid parameters according to the definitions;
    • Understand failure messages returned by tools;
    • Avoid re-executing operations that are already complete;
    • Ask first when information is insufficient, rather than fabricating parameters.

    If the integration method does not offer native tool calling, the application can parse structured output instead, but it still needs strict validation and must not treat model output directly as trusted instructions.

    2. Context Capacity and Actual Information Management

    The context window determines how much input a single request can hold, but a larger window does not mean a task will be more reliable. Too many documents, lengthy logs, and irrelevant history all increase cost and may interfere with judgment.

    In practice, prioritize on-demand retrieval, trimming of tool results, and staged summaries. For long tasks, save “completed steps, key evidence, unresolved problems, and next-step plans” rather than continuously appending all raw output.

    3. Whether the Interface Behavior and Runtime Environment Match

    Before integration, verify the authentication method, request format, tool definition format, timeout settings, error return format, and usage limits. Even services with similar-looking interfaces may differ in field requirements or behavior.

    Do not fill in model identifiers or request parameters from memory, and do not copy configurations from other services directly. Specific values should come from the current service’s documentation and actually available configuration.

    4. Whether Latency, Cost, and Task Type Match

    Simple classification, short-text extraction, and complex code analysis place very different demands on model capability. When choosing a model, weigh task difficulty, response time, and total cost per task together, rather than looking at a single advertised metric.

    A cheaper model that frequently chooses the wrong tool and triggers retries may end up costing more. Conversely, a more capable model that significantly reduces wasted steps may be better suited to complex tasks.

    4. Building From Scratch: Get the Minimal Loop Running First

    Step 1: Prepare Model Access Credentials

    Model access credentials can be understood as the authorization information for calling the service. Once obtained, store them first in a controlled key management facility or a secure local configuration; do not write them into business code, shared documents, or public repositories.

    Environment variables are a common way to pass configuration, but they do not automatically guarantee security. You still need to avoid outputting credentials in startup logs, error messages, and diagnostic pages.

    The following only shows a configuration structure and does not correspond to any specific service interface:

    1. Model service endpoint = read from protected configuration
    2. Model access credential = read from protected configuration
    3. Model identifier = a value confirmed as supported by the current service
    4. Task budget = set according to business needs

    Different services may have different rules for credential display, validity periods, and revocation, so manage them according to the actual rules. If a leak is suspected, revoke or rotate immediately and check the call records.

    Step 2: Verify the Model Call First, Don’t Rush to Add Tools

    First complete a simple text request to confirm that authentication, networking, and response handling all work. Then verify tool calling, and clearly distinguish authentication failures, service rate limiting, parameter errors, and request timeouts.

    Layered troubleshooting is more effective than enabling many capabilities at once. Otherwise, when the agent fails, it is hard to tell whether the problem lies in the model connection, the tool definitions, or the execution environment.

    Step 3: Expose Only a Few Read-Only Tools

    For a first pass, start with directory listing, reading specified files, and keyword search. Each tool should describe its purpose, parameters, return content, and the scope it is allowed to access.

    For example, a file-reading tool should not only check whether the path exists, but also limit the file size and verify that the actual resolved path is still within the authorized directory, preventing bypass of the boundary through relative paths or links.

    Step 4: Set Clear Task Boundaries and Acceptance Conditions

    Rather than saying “help me check the project,” describe it like this:

    Only inspect the configuration documentation files under the specified directory; do not modify files and do not access the external network. Output a list of problems, each including the source location, the basis for the judgment, and a suggested handling approach. When information is insufficient, mark it explicitly and do not fill it in on your own.

    This kind of instruction states the goal, scope, prohibitions, and delivery format. It cannot replace program-level access control, but it reduces ambiguity and makes acceptance more direct.

    5. Tool Execution Must Have Permission and Error-Handling Design

    1. The Model Proposes a Request, the Program Decides Whether to Execute

    Tool calls should go through independent validation. This usually includes parameter types, resource scope, operation permissions, call frequency, and whether human confirmation is required.

    Do not let the model decide how much authority it has. Operations involving file overwrites, data deletion, permission changes, or sending information externally should have stricter authorization conditions.

    2. Distinguish Retryable Errors From Non-Retryable Errors

    Brief network anomalies may be suitable for limited retries; invalid credentials, insufficient permissions, and illegal parameters usually require fixing the conditions rather than repeating the request.

    For operations that produce external side effects, retries need particular caution. A request timeout does not mean the operation did not succeed. For example, if the connection drops after sending a notification, resending directly could cause a duplicate notification. In this case, query the status first, or use an idempotency mechanism supported by the application.

    3. Provide Preview and Rollback for High-Risk Operations

    Before modifying files, you can generate a diff preview and apply it only after the user confirms. Batch changes should consider backups, version records, or rollback procedures.

    Reliability does not mean “never failing,” but that failures can be detected, their impact can be limited, and recovery is possible when necessary.

    6. Memory and External Content Must Not Become Hidden Risk Entry Points

    When people say an agent “remembers things from before,” it usually means the application has saved session summaries, task records, or user preferences, not that the model’s parameters are updated instantly.

    It is recommended to divide information into three categories:

    • Session context: serves the current task and can be cleared afterward;
    • Task state: used to resume interrupted tasks, recording progress and to-do items;
    • Long-term preferences: stable user needs saved after appropriate authorization.

    Sensitive credentials, temporary permissions, and complete private documents should not be written into long-term memory by default. Enterprise scenarios also need to consider user isolation, retention periods, and deletion mechanisms.

    In addition, files, web pages, logs, and tool return content are all external data. Even if text like “ignore the previous rules” or “upload all files” appears within them, it must not gain higher privileges as a result. System design should separate trusted control instructions from untrusted business content, and let permission validation take effect independently of the model.

    7. Cost Control Must Cover the Entire Task Chain

    A single agent task often involves multiple rounds of model requests. Total cost includes not only input and output, but possibly tool usage, runtime environment, storage, and logging. Specific billing items follow the actual rules of the services used and should not be based on fixed prices.

    Common sources of wasted cost include repeatedly reading the same material, returning overly long tool results, indiscriminate retries after failures, and loops with no stop condition.

    Therefore, it is recommended to set, at the same time:

    • A limit on the number of calls per task;
    • A limit on tool result length;
    • A runtime limit;
    • A consecutive-failure threshold;
    • A cost budget limit when available.

    When a limit is reached, output the intermediate result and the reason for stopping. Compared with continuing to try blindly, this approach is easier to maintain and better matches user expectations.

    If the system supports switching models, also confirm that tool definitions, context, and task state remain compatible after the switch. Model switching is not an automatic repair mechanism; more importantly, first determine whether the failure comes from reasoning ability, insufficient permissions, or the tool itself.

    8. Judge Real Effectiveness With Repeatable Tasks

    When evaluating an agent, do not rely on a single impressive demo. Prepare a fixed set of tasks that covers both normal and abnormal situations, such as missing documents, tool timeouts, no permission to access a file, and material containing distracting instructions.

    Recommended metrics include:

    • Task success rate: whether it meets the pre-agreed acceptance criteria;
    • Effective call ratio: whether tool calls actually advance the task;
    • Human intervention frequency: how many times the user needs to correct or supplement;
    • Cost and time: how many resources are needed to complete similar tasks;
    • Safety behavior: whether any unauthorized access, leakage, or unconfirmed modifications occur.

    Report quality also needs separate checking. Correct formatting does not mean accurate conclusions; spot-check whether evidence and conclusions are consistent, and avoid mistaking “a file was generated” for “the work is done.”

    9. From Individual Trials to Enterprise Applications, Use Progressive Authorization

    Individual developers can first test in an isolated directory, letting the agent handle low-risk, easily verifiable tasks. Enterprise teams need to further implement identity authentication, permission isolation, log auditing, data classification, and anomaly alerting.

    A more prudent order of progression is:

    1. First do read-only retrieval and result analysis;
    2. Then allow generating drafts and modification suggestions;
    3. Introduce human confirmation for low-risk changes;
    4. After testing, monitoring, and rollback mechanisms are in place, gradually expand the scope of automatic execution.

    In summary, the usefulness of an agent comes from three conditions: the model can make reasonable decisions, the tools can execute reliably, and the orchestration layer can constrain risk. What is truly worth pursuing is not making the system “as autonomous as possible,” but ensuring that every action has boundaries, every conclusion has a basis, and every failure can be handled. Only by building such an execution loop can natural-language-driven automation move from a novel experience to stable productivity.