Agent Framework Design: Integrating Multimodal Inputs and Subagent Orchestration

    This article explains how an agent framework can use a unified scheduling layer to handle mixed text, image, and file inputs, orchestrate subagents with callback-based result delivery, run independent tool calls concurrently, maintain persistent terminal sessions, adapt to different model gateways, and keep dependencies lean. It also provides implementation patterns and a deployment checklist for reliability and maintainability.

    1. Why Agent Frameworks Need a Unified Scheduling Layer

    Early agent applications mostly handled a single round of dialogue. As tasks grow longer, a single model can no longer easily perform information retrieval, code modification, file analysis, and result synthesis at the same time. Engineering practice has therefore gradually adopted a layered structure: the upper layer understands the goal, decomposes tasks, and controls the workflow, while the lower layer invokes different execution units on demand, such as code assistants, search tools, or specialized analysis modules.

    This layering brings two direct benefits. First, execution units can be replaced without rewriting the main workflow for every capability. Second, the upper layer can observe task state in a unified way, including progress, failure reasons, and resource consumption. When designing the scheduling layer, the core issue is boundary definition: which decisions the scheduling layer makes, which decisions execution units make autonomously, and what protocol the two sides use to exchange information.

    2. Multimodal Input: From Plain Text to Mixed Image-Text Context

    Users often provide screenshots, documents, and text explanations together in real work. A framework usually needs three steps to handle this type of input.

    1. Type identification and preprocessing: determine the attachment type, check and compress image dimensions, and encode or summarize files.
    2. Unified message structure: place text, image references, and file references into the same message array, with each segment carrying an explicit type marker.
    3. Context budget control: images in historical messages continue to consume request size. Without an upper limit, requests after multiple turns can easily exceed the limits of the model or gateway.

    Example (pseudocode):

    1. MAX_IMAGE_EDGE = 2048
    2. MAX_HISTORY_PAYLOAD = 8 * 1024 * 1024 # bytes, example value
    3. def build_message(parts):
    4. content = []
    5. for part in parts:
    6. if part.kind == "image":
    7. img = resize_if_needed(part.data, MAX_IMAGE_EDGE)
    8. content.append({"type": "image", "data": encode(img)})
    9. elif part.kind == "text":
    10. content.append({"type": "text", "text": part.text})
    11. return content
    12. def trim_history(messages):
    13. # Remove images from the oldest historical messages until total payload is below the limit
    14. while payload_size(messages) > MAX_HISTORY_PAYLOAD:
    15. drop_oldest_image(messages)
    16. return messages

    The key point in this handling is that request failures are often caused not by the model itself but by payload overruns. Building size and cumulative payload constraints into the framework is more reliable than investigating after an error occurs.

    3. Subagent Orchestration: Task Decomposition and Result Return

    Subagents are suitable for subtasks with clear boundaries, such as “retrieve three documents and list the differences” or “modify a module and run tests.” The orchestration layer needs to design three things: the format of task descriptions, the permission scope of subagents, and the return mechanism after completion.

    The return mechanism is especially critical. If a subagent only writes results to shared storage, the parent task must poll, which wastes resources and increases latency. A more robust approach is for the subagent to actively emit a callback event after completion, so the scheduling layer wakes the waiting parent task and attaches structured results.

    Example (pseudocode):

    1. class Orchestrator:
    2. def run(self, goal):
    3. plan = self.planner.split(goal) # split into subtasks
    4. handles = [self.spawn(task) for task in plan]
    5. for h in handles:
    6. h.on_complete(self.resume_parent) # callback on completion; no polling
    7. return self.summarizer.merge(self.wait_all(handles))
    8. def spawn(self, task):
    9. return SubAgent(
    10. role=task.role,
    11. tools=task.allowed_tools, # least privilege
    12. timeout=task.timeout,
    13. ).start(task.prompt)

    Two additional points matter in design. First, each subagent should receive only the tools needed to complete its task, avoiding permission spread. Second, timeouts and failures need explicit result types so the parent task can distinguish among “not completed,” “failed,” and “empty result.”

    4. Concurrent Tool Calls and Long-Chain Task Efficiency

    Long-chain tasks often contain multiple independent retrieval or read operations. If all are executed serially, total time equals the sum of each step. If these operations have no dependencies, they can be executed concurrently, and total time approaches the slowest step.

    Concurrency requires supporting controls:

    • Concurrency limit: cap the number of simultaneous requests to avoid triggering external service rate limits.
    • Timeout and retry: when a single request fails, retry only that request without affecting other results.
    • Result merging: organize results by original order or task ID to keep downstream reasoning input stable.

    Example (pseudocode):

    1. def parallel_search(queries, limit=5):
    2. results = {}
    3. with ConcurrencyPool(limit) as pool:
    4. futures = {pool.submit(search, q): q for q in queries}
    5. for f in completed(futures):
    6. q = futures[f]
    7. results[q] = f.result_or_error()
    8. return [results[q] for q in queries]

    5. Persistent Sessions in Local Terminals

    When an agent executes commands locally, it often needs to preserve environment state, such as the current directory, environment variables, and activated virtual environments. If every command starts a new process, state between steps is lost, and task chains can easily fail.

    The persistent-session approach is to maintain a long-lived terminal process for each task, send commands through the same input channel, and split output by markers. This design differs in detail across operating systems. For cross-platform implementation, process management, encoding handling, and timeout detection should be encapsulated behind a unified interface so business code does not directly depend on platform-specific features.

    For security, the permissions of a persistent session must match the task scope. It is recommended to set a working-directory allowlist for sessions and log every command and its output for auditing and traceability.

    6. Gateway Compatibility and Reasoning Content Return

    In enterprise environments, model requests often pass through self-hosted gateways or proxies. Different gateways have different requirements for request fields: some do not accept certain optional fields, and some impose additional constraints on message structure. A framework should:

    1. Abstract request formats into an adapter layer, with one mapping rule per gateway;
    2. Return a summary of the raw response for unknown errors to support diagnosis;
    3. When canceling streaming generation, preserve the partial content already displayed and carry it into follow-up questions or forked sessions to avoid context breaks.

    Returning reasoning content also requires care. If the return path is missing fields, reasoning continuity in later turns can be affected. Tests should cover three scenarios: “mid-generation cancellation,” “forked sessions,” and “gateway switching.”

    7. Dependency Trimming and Installation Experience

    Agent frameworks often depend on multiple runtimes and tools at the same time, and installation package size grows quickly. Common approaches to trimming dependencies include installing optional modules on demand, placing heavy components in separate configuration packages, and downloading nonessential resources only on first startup.

    Automatically opening a browser after the local service starts is also a common design for lowering the barrier to use. Implementations should allow users to disable this behavior through a parameter and automatically skip it in headless environments.

    8. Implementation Checklist

    • Image and history payload limits are set, with tests covering over-limit scenarios.
    • Subagent tool permissions are minimized per task.
    • Subtask completion wakes the parent task through a callback rather than polling.
    • Concurrent requests have limits, timeouts, and independent retries.
    • Terminal sessions have working-directory restrictions and command auditing.
    • The gateway adapter layer has independent unit tests and error summary output.
    • Edge cases such as canceled generation, forked sessions, and gateway switching are included in regression tests.

    Checking each item on this list helps reduce regressions when introducing new capabilities and makes it easier for teams to align on design conventions.