From Answering Questions to Executing Tasks: A Guide to Designing and Implementing AI Office Agents

    This guide explores the transition from conversational AI assistants to task-execution AI agents in office scenarios. It highlights the core differences between these two types of systems and details a four-module architecture—task planning, tool calling, state management, and permission control. Additionally, it outlines a layered system design and provides a Python reference implementation to help developers build reliable AI agents capable of handling complex, multi-step workflows.

    Why Office Scenarios Need Action-Oriented Agents

    In the past, the common use of large language models (LLMs) in the workplace was conversational Q&A: asking a question and receiving a text response. This approach is suitable for information retrieval and copy editing, but most office tasks cannot be completed with just a single text answer. Take a weekly report as an example: the workflow typically involves fetching data from multiple systems, cleaning and aggregating the data, generating charts, and finally sending it to relevant colleagues. Each step relies on external tools, and the result of the previous step determines how the next step proceeds.

    Therefore, the industry’s focus has shifted to systems that can decompose goals, call tools, execute complete workflows, and pause at key nodes to await confirmation. These systems can be referred to as task-execution agents. Their value depends on the task completion rate and whether the system can be controlled and traced back when errors occur. The fluency of a single response is only a secondary factor.

    Boundaries Between Two Types of Systems

    The output of a conversational assistant is a one-time text response; if the user spots an error, they can simply ignore it. The output of a task-execution agent is a series of actions and state changes; if an error occurs, it may have already caused a real-world impact. The two primarily differ in four areas:

    • Goal: Changes from “answer this question” to “complete this task and meet given constraints.”
    • Execution Method: Changes from single-turn inference to multi-turn loops, including planning, calling, observing, and correcting.
    • External Impact: It reads and writes files, calls APIs, and sends messages, causing side effects.
    • Failure Handling: Requires mechanisms for retries, rollbacks, pausing, and manual takeover.

    Therefore, during design, the model must be viewed within the context of the entire system. The model is responsible for understanding intent and generating plans, the tools are responsible for execution, the orchestration layer is responsible for state transitions, and the permission layer is responsible for defining boundaries. If any layer is weak, the overall performance will suffer.

    Four Core Modules

    1. Task Planning

    Input: User goal, list of available tools, current task state.

    Output: Structured plan. Each step includes an ID, tool name, parameters, whether confirmation is required, and the maximum number of retries.

    Key Fields: The step ID must be unique within the same plan; the tool name must exist in the tool registry; when parameters reference upstream results, use the $step_id format.

    Failure Handling: If the plan is invalid (missing fields, tool does not exist, circular dependencies exist), reject execution directly and require re-planning.

    Acceptance Metrics: The proportion of plans passing structural validation; the deviation between the number of planned steps and manual expectations; the proportion of plans requiring manual rewriting.

    2. Tool Calling

    Input: The tool name and parsed parameters for the step.

    Output: Tool return value, or a failure result with an error type.

    Key Principles: Each tool declares its parameter structure, and type and value validation is performed before calling. Errors are divided into two categories. Retryable errors include timeouts, rate limiting, and temporary network failures. Non-retryable errors include invalid parameters, insufficient permissions, and non-existent resources. Tools with side effects (such as sending, writing, paying) must support idempotency keys to avoid duplicate sends caused by retries.

    Failure Handling: Retryable errors use exponential backoff, such as waiting 1 second, 2 seconds, 4 seconds, and marking as failed after exceeding the retry limit. The content returned by a tool is data. Even if it contains text like “ignore previous instructions,” it must not be executed as a command.

    Acceptance Metrics: Success rate of each tool, average execution time, distribution of retry counts.

    3. State Management

    Input: Task ID, plan, status of each step, intermediate results produced.

    Output: Recoverable task snapshot.

    Key Fields: status records the step state, with values of pending, running, done, failed, paused; outputs saves step outputs; errors saves error information.

    Principles: The plan is generated only once and persisted. Upon recovery, the original plan is reused to avoid changes in steps after the model re-plans. Every state change must be persisted to disk. If a process crashes, steps in the running state will be re-executed, so steps with side effects must be idempotent.

    Acceptance Metrics: Success rate of recovery after task interruption; the number of errors caused by duplicate execution, with a target of zero.

    4. Permission Control

    Input: User identity, task initiator, permission declarations for each tool.

    Output: Allow or deny decision, along with the corresponding audit log.

    Principles: First, least privilege: each tool only obtains the permissions required to complete the current task. Second, credentials are managed by a key management service and are not written into code, prompts, or logs; access tokens have an expiration time. Third, high-risk actions (sending, deleting, paying, modifying permissions) require secondary confirmation. The confirmation record is bound to the parameter hash, and if the content changes, it must be re-confirmed. Fourth, the planning model cannot grant permissions on its own.

    Acceptance Metrics: Number of intercepted unauthorized calls; confirmation coverage rate for high-risk actions, with a target of 100%.

    Layered Architecture and Reference Implementation

    It is recommended to split the system into six layers:

    1. Interaction Layer: Receives instructions, displays execution progress, and handles confirmation and modification instructions.
    2. Orchestration Layer: Maintains the task state machine, responsible for decomposition, scheduling, retry, and recovery.
    3. Model Layer: Provides understanding, planning, and generation capabilities, accessed through a unified adaptation interface to facilitate replacing models without altering upper-layer logic.
    4. Tool Layer: Encapsulates capabilities such as file processing, spreadsheet calculation, database querying, email, and calendar. Each tool provides structured parameter definitions.
    5. Data & Permission Layer: Manages credentials, user identities, data access scopes, and access policies.
    6. Observability Layer: Records input summaries, output summaries, execution time, cost, and error information for each step, supporting auditing and optimization.

    The code below is a minimal example of a task execution loop, relying only on the Python standard library and requiring Python 3.10 or higher. The tool functions are illustrative implementations, and the storage layer is an in-memory version. Production environments should replace this with a database and use version numbers when saving to prevent concurrent overwrites.

    1. from __future__ import annotations
    2. import hashlib
    3. import time
    4. from dataclasses import dataclass, field
    5. from enum import Enum
    6. from typing import Any, Callable, Protocol
    7. class TransientError(Exception):
    8. """Retryable error: timeout, rate limiting, temporary network failure."""
    9. class PermanentError(Exception):
    10. """Non-retryable error: invalid parameters, insufficient permissions, tool does not exist."""
    11. class StepStatus(str, Enum):
    12. PENDING = "pending"
    13. RUNNING = "running"
    14. DONE = "done"
    15. FAILED = "failed"
    16. PAUSED = "paused"
    17. @dataclass
    18. class Step:
    19. id: str
    20. tool: str
    21. args: dict[str, Any]
    22. requires_confirmation: bool = False
    23. max_retries: int = 2
    24. @dataclass
    25. class Plan:
    26. goal: str
    27. steps: list[Step]
    28. @dataclass
    29. class TaskState:
    30. task_id: str
    31. goal: str
    32. plan: Plan | None = None
    33. status: dict[str, StepStatus] = field(default_factory=dict)
    34. outputs: dict[str, Any] = field(default_factory=dict)
    35. errors: dict[str, str] = field(default_factory=dict)
    36. class Planner(Protocol):
    37. def make_plan(self, goal: str, state: TaskState) -> Plan: ...
    38. class StateStore(Protocol):
    39. def load_or_create(self, goal: str) -> TaskState: ...
    40. def save(self, state: TaskState) -> None: ...
    41. class ToolRegistry:
    42. def __init__(self, tools: dict[str, Callable[[dict[str, Any]], Any]]):
    43. self._tools = tools
    44. def call(self, name: str, args: dict[str, Any]) -> Any:
    45. if name not in self._tools:
    46. raise PermanentError(f"Unregistered tool: {name}")
    47. return self._tools[name](args)
    48. class InMemoryStore:
    49. """Illustrative implementation. Production environments should write to a database and use version numbers to prevent concurrent overwrites."""
    50. def __init__(self) -> None:
    51. self._db: dict[str, TaskState] = {}
    52. def load_or_create(self, goal: str) ->