AI Agents for Complex Tasks: Capability Limits, Cost, and Security

    Learn how to build AI agents for multi-step research and software engineering tasks, with practical guidance on validation, context caching, reasoning settings, cloud-native architecture, and security boundaries. The article explains where models can take on execution and where human oversight remains essential.

    How LLM Capabilities Are Changing in Complex Tasks

    Large language models are moving beyond answering questions to executing multi-step tasks. They can read data, propose approaches, run code, and revise their work in response to errors. Understanding these capabilities helps developers decide which tasks to delegate and which steps still require human oversight.

    1. Long-Running Scientific Workflows

    Planetary terrain reconstruction illustrates this shift. Elevation data collected through radar observations can have low spatial resolution, with each pixel representing a large area of the surface. Historically, researchers have reconstructed elevation maps for only a small portion of that area, either manually or with conventional algorithms.

    A recent approach is to let a model read the low-resolution data, design and train a generative network, and produce a higher-resolution elevation map. The workflow includes data preprocessing, network design, hyperparameter tuning, and result validation. The model can handle much of this process, but people still need to define the objective, review preprocessing decisions, and inspect the final results.

    To reproduce this type of task, record:

    • Dataset size: the number of samples and the geographic area covered.
    • Resolution: both the original and target resolutions.
    • Evaluation metrics: commonly PSNR and RMSE, with comparisons against conventional interpolation methods.
    • Model details: the model name and version.

    The example discussed here describes an approach rather than providing reproducible experimental data. Reliability depends on noise levels and the availability of ground truth. When ground truth is unavailable, results need validation against independent data or field observations.

    2. Software Engineering and Terminal Execution

    LLM use in software engineering has expanded from completing code snippets to modifying multiple files, running tests, and fixing errors. A developer describes the objective in natural language, and the model breaks down the task, edits code, runs tests, and iterates based on the results.

    This workflow depends on adequate test coverage. Without tests, the model cannot determine whether its changes are correct. Command execution should be restricted to an isolated test environment, with no direct access to production databases or production credentials. A human should review the code before it is merged.

    3. Token Costs and Compute Control

    Context Caching

    Long-running agent tasks repeatedly send historical context. If every request is billed at the standard input rate, costs can grow quickly as the number of turns increases. Context caching reduces repeated-input costs by allowing previously processed prefixes to be read at a lower rate.

    Cache pricing varies considerably across providers. Some models charge substantially less for cached input than for standard input, but the applicable discount must be checked against the provider’s official pricing. Verify current prices before use and record the date of the lookup.

    Input cost for a single request can be estimated as:

    1. Input cost per request ≈
    2. Cached input tokens × Cache-read price per token
    3. + Uncached input tokens × Standard input price per token

    The savings depend on several factors:

    • Cache hit rate: unchanged historical context across requests generally produces a higher hit rate.
    • Context length: longer histories can yield greater absolute savings.
    • Request structure: smaller additions in each turn make cache hits more likely.

    Use billing logs to measure the actual number of cached input tokens, then apply the formula. Do not assume a fixed percentage of savings.

    Reasoning Effort Settings

    Some models allow developers to adjust reasoning effort. Simple instructions, such as format conversion or field extraction, can use a lower setting to reduce output token usage. Tasks that require substantial reasoning, such as solution design or error diagnosis, should use a higher setting.

    Parameter names and supported values differ by platform. Consult the official documentation for the model and API you use.

    4. A Cloud-Native Agent Architecture

    An agent that processes scientific data typically has four layers:

    1. Data layer: Store raw data in object storage—for example, astronomical observation data or code repository snapshots in Baidu AI Cloud BOS. Organize data into buckets by category and configure access permissions.
    2. Execution layer: Run model-generated code in containers or serverless functions. Isolate the execution environment from external networks and restrict the storage paths it can access.
    3. Orchestration layer: Manage task decomposition, caching, retries, and timeouts.
    4. Audit layer: Record every model call, code execution, and data access to support later investigation.

    The following illustrative code shows basic patterns for caching, timeouts, retries, and redaction. Its API fields and parameter names are placeholders; use the relevant API documentation for actual implementation details.

    1. # Illustrative code: consult the platform's official API documentation
    2. # for actual parameter names and interfaces.
    3. import logging
    4. import re
    5. import time
    6. logger = logging.getLogger("research_agent")
    7. class ResearchAgent:
    8. def __init__(self, llm_client, storage_client,
    9. max_retries=3, timeout_s=60, cache_ttl_s=3600):
    10. self.llm = llm_client
    11. self.storage = storage_client
    12. self.max_retries = max_retries
    13. self.timeout_s = timeout_s
    14. self.cache_ttl_s = cache_ttl_s
    15. self.cache_id = None
    16. self.cache_created_at = None
    17. def _cache_expired(self):
    18. if self.cache_id is None:
    19. return True
    20. return time.time() - self.cache_created_at > self.cache_ttl_s
    21. def _call_with_retry(self, payload):
    22. for attempt in range(1, self.max_retries + 1):
    23. try:
    24. return self.llm.chat(payload, timeout=self.timeout_s)
    25. except TimeoutError:
    26. logger.warning("Request timed out, attempt %d", attempt)
    27. except ConnectionError:
    28. logger.warning("Network error, attempt %d", attempt)
    29. if attempt < self.max_retries:
    30. time.sleep(2 ** attempt)
    31. raise RuntimeError("Model call failed: maximum retries reached")
    32. @staticmethod
    33. def _desensitize(text):
    34. # Illustrative only: define rules by data classification,
    35. # covering credentials, personal information, and internal addresses.
    36. text = re.sub(r"(password|token)=\S+", r"\1=***", text)
    37. return text
    38. def load_data_context(self, storage_path):
    39. raw = self.storage.get_object(storage_path)
    40. safe_text = self._desensitize(raw)
    41. resp = self._call_with_retry({
    42. "prompt": (
    43. "You are a research assistant. Analyze the following "
    44. f"observation data:\n{safe_text}"
    45. ),
    46. "enable_cache": True,
    47. "thinking_level": "LOW",
    48. })
    49. self.cache_id = resp.get("cache_id")
    50. self.cache_created_at = time.time()
    51. return resp.get("analysis")
    52. def execute_refinement(self, instruction):
    53. if self._cache_expired():
    54. raise RuntimeError("Cache has expired; reload the data context")
    55. resp = self._call_with_retry({
    56. "prompt": instruction,
    57. "cache_id": self.cache_id,
    58. "thinking_level": "HIGH",
    59. })
    60. return resp.get("result")

    Several details matter here. When the cache expires, reload the context rather than silently using stale cached data. Retry only timeout and network failures, not failures caused by invalid permissions or parameters. The redaction rules are illustrative; production rules should follow data classifications and undergo security-team review.

    5. Security and Compliance

    Because agents can execute code, their security boundaries must be defined in advance. Review the following:

    • Is the execution environment isolated from external networks, with outbound access restricted to an allowlist?
    • Do cloud accounts and service accounts follow the principle of least privilege?
    • Are credentials stored in environment variables or a secrets management service rather than embedded in code?
    • Are production and test data separated, with the model restricted to test data?
    • Does data use comply with privacy requirements and authorization agreements?
    • Is model-generated code reviewed by a human before merging or deployment?

    6. Recommendations for Developers

    1. Define task boundaries first. Specify the objective, inputs, outputs, and acceptance criteria before allowing the agent to execute.
    2. Make each step verifiable. Provide tests or validation metrics that produce clear failure signals.
    3. Manage costs with actual usage data. Measure cache hit rates and token usage from billing logs, then choose caching strategies and reasoning settings accordingly.
    4. Build security into the architecture. Decide on sandboxing, permissions, and auditing during design, rather than adding them just before launch.

    LLMs are becoming more capable at long-running, multi-step tasks, but their effectiveness depends on the task, data quality, and engineering design. Start with a small-scale evaluation in your own environment, then expand usage gradually.