Multi-Model Parallel Programming: Task Splitting, an Adapter Layer, and Cost Accounting

    When developers use multiple large language models side by side, the hard questions are usually not "which model is best" but "which step goes to which model, what happens when a call fails, and where the money is going." This article walks through four steps: deciding how to split tasks, building a runnable adapter layer, calculating costs with a formula, and checking the result against a checklist covering safety, availability, and budget.

    1. Which Tasks Are Worth Splitting Across Models

    Multi-model parallelism only makes sense when a task can be broken into pieces with clear boundaries and independently verifiable results. Models differ mainly in three dimensions: reasoning depth, response speed, and unit cost—and the division of labor should be designed around those differences.

    The table below shows one common arrangement. Replace the specific models with your own benchmark results.

    Task type Required capability Invocation pattern Human review point
    Requirements analysis and solution design Logical reasoning, organizing business rules Serial: produce a design first, then split into tasks Check whether interface boundaries and business rules are missing
    Boilerplate code and real-time completion Fast responses, low per-call cost Single model, real-time calls Run unit tests
    Complex algorithms and core modules Strong reasoning, long context Serial: generate over multiple rounds Compare against test cases and performance benchmarks
    Code review Sensitivity to code defects Parallel: multiple models review independently Decide whether to adopt each finding
    API documentation generation Summarization, standards-compliant output Serial pipeline Verify parameter names, types, and return values item by item

    Cross-validation lowers the chance that a wrong suggestion gets adopted outright, but it does not eliminate hallucinations. Two models can make the same mistake, so every suggestion still needs to pass tests, static analysis, or human judgment.

    Three scenarios are a poor fit for splitting. First, when requirements are not yet settled, having multiple models modify the same design causes changes to overwrite each other and becomes hard to trace. Second, cross-file refactoring: without shared context, models produce conflicting edits. Third, tasks involving large amounts of customer data must pass a data security review before anything is sent out.

    How to Benchmark Model Capability

    Don’t rely on marketing material when choosing a model. Prepare a fixed test set that covers your team’s real scenarios. For example, extract 20 function-implementation problems from past requirements, prepare 5 code snippets with hidden defects for review testing, and 3 API documents for summarization testing.

    Run every model against the same set and record four metrics: pass rate, first-token latency and total runtime, token consumption per task, and the number of false positives and false negatives in review tasks. Read the results per task type—a model that is good at code generation is not necessarily good at code review.

    Re-run the benchmark after every model version update, or quarterly, and record results in the same spreadsheet so you can compare over time. Write down decision criteria in advance. For example, if a task type’s pass rate drops below 80%, or per-task cost exceeds twice the budget, stop assigning that task to the model. Set thresholds according to your team’s own tolerance.

    2. How to Write a Unified Adapter Layer

    A unified interface is only the first step. Real calls also have to handle timeouts, retries, rate limiting, fallback, and credentials. The following code depends only on the Python standard library and runs as-is. Swap the URL and request format in JsonHttpAdapter for those in your provider’s documentation, set the corresponding environment variables, and it is ready to use.

    1. import email.utils
    2. import json
    3. import logging
    4. import os
    5. import random
    6. import threading
    7. import time
    8. import urllib.error
    9. import urllib.request
    10. from abc import ABC, abstractmethod
    11. from datetime import datetime, timezone
    12. from typing import Optional, Sequence
    13. logger = logging.getLogger("model_adapter")
    14. BASE_BACKOFF_S = 1.0
    15. MAX_BACKOFF_S = 20.0
    16. class RetryableError(Exception):
    17. """Retryable failures: timeouts, connection errors, 408, 429, or 5xx."""
    18. def __init__(self, message: str, retry_after: Optional[float] = None):
    19. super().__init__(message)
    20. self.retry_after = retry_after
    21. class FatalError(Exception):
    22. """Errors that should not be retried, such as bad parameters or auth failures."""
    23. class ModelError(Exception):
    24. """The call ultimately failed; the caller decides whether to fall back or report an error."""
    25. class ConcurrencyLimiter:
    26. """Caps the number of in-flight requests within a single process. For multi-instance deployments, a shared counter is required."""
    27. def __init__(self, max_concurrency: int):
    28. self._sem = threading.BoundedSemaphore(max_concurrency)
    29. def __enter__(self):
    30. self._sem.acquire()
    31. return self
    32. def __exit__(self, exc_type, exc, tb):
    33. self._sem.release()
    34. return False
    35. def parse_retry_after(value: Optional[str]) -> Optional[float]:
    36. """Parse the Retry-After header; supports both seconds and HTTP-date formats."""
    37. if not value:
    38. return None
    39. value = value.strip()
    40. try:
    41. return max(0.0, float(value))
    42. except ValueError:
    43. pass
    44. try:
    45. when = email.utils.parsedate_to_datetime(value)
    46. except (TypeError, ValueError):
    47. return None
    48. if when.tzinfo is None:
    49. when = when.replace(tzinfo=timezone.utc)
    50. return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
    51. def classify_http_error(status: int, retry_after_header: Optional[str] = None) -> Exception:
    52. if status in (408, 429) or status >= 500:
    53. return RetryableError(f"HTTP {status}", parse_retry_after(retry_after_header))
    54. return FatalError(f"HTTP {status}")
    55. def backoff_delay(attempt: int, retry_after: Optional[float] = None) -> float:
    56. if retry_after is not None:
    57. return min(retry_after, MAX_BACKOFF_S)
    58. cap = min(BASE_BACKOFF_S * (2 ** attempt), MAX_BACKOFF_S)
    59. return random.uniform(0, cap) # full jitter
    60. class BaseModelAdapter(ABC):
    61. def __init__(self, name: str, timeout_s: float = 30.0, max_retries: int = 2,
    62. limiter: Optional[ConcurrencyLimiter] = None, sleep=time.sleep):
    63. self.name = name
    64. self.timeout_s = timeout_s
    65. self.max_retries = max_retries
    66. self.limiter = limiter or ConcurrencyLimiter(4)
    67. self._sleep = sleep
    68. @abstractmethod
    69. def _call(self, prompt: str, timeout_s: float) -> str:
    70. """Subclasses implement the real call and must pass timeout_s to the HTTP client for enforcement."""
    71. def generate(self, prompt: str) -> str:
    72. last_error: Optional[Exception] = None
    73. for attempt in range(self.max_retries + 1):
    74. try:
    75. with self.limiter:
    76. return self._call(prompt, self.timeout_s)
    77. except FatalError as err:
    78. logger.error("model=%s non-retryable error: %s", self.name, err)
    79. raise ModelError(f"{self.name} hit a non-retryable error: {err}") from err
    80. except RetryableError as err:
    81. last_error = err
    82. if attempt == self.max_retries:
    83. break
    84. delay = backoff_delay(attempt, err.retry_after)
    85. logger.warning("model=%s waiting %.2f seconds before retry %d: %s",
    86. self.name, delay, attempt + 1, err)
    87. self._sleep(delay)
    88. raise ModelError(f"{self.name} still failed after {self.max_retries} retries: {last_error}") from last_error
    89. class JsonHttpAdapter(BaseModelAdapter):
    90. """Example implementation: calls a model endpoint over HTTP that returns JSON."""
    91. def __init__(self, name: str, url: str, api_key_env: str, **kwargs):
    92. super().__init__(name, **kwargs)
    93. self.url = url
    94. self._api_key_env = api_key_env
    95. def _call(self, prompt: str, timeout_s: float) -> str:
    96. api_key = os.environ.get(self._api_key_env)
    97. if not api_key:
    98. raise FatalError(f"environment variable {self._api_key_env} is not set")
    99. body = json.dumps({"prompt": prompt}).encode("utf-8")
    100. req = urllib.request.Request(
    101. self.url,
    102. data=body,
    103. method="POST",
    104. headers={
    105. "Content-Type": "application/json",
    106. "Authorization": f"Bearer {api_key}",
    107. },
    108. )
    109. try:
    110. with urllib.request.urlopen(req, timeout=timeout_s) as resp:
    111. data = json.loads(resp.read().decode("utf-8"))
    112. return data["text"]
    113. except urllib.error.HTTPError as err:
    114. raise classify_http_error(err.code, err.headers.get("Retry-After")) from err
    115. except OSError as err: # includes URLError, connection failures, and read timeouts
    116. raise RetryableError(f"network or timeout error: {err}") from err
    117. except (KeyError, ValueError) as err: # unexpected response structure or JSON parse failure
    118. raise FatalError(f"unexpected response format: {err}") from err
    119. class ModelRouter:
    120. """Tries models in order; falls back to the next one when the previous fails."""
    121. def __init__(self, adapters: Sequence[BaseModelAdapter]):
    122. if not adapters:
    123. raise ValueError("at least one model adapter is required")
    124. self.adapters = list(adapters)
    125. def generate(self, prompt: str) -> tuple[str, str]:
    126. failures = []
    127. for adapter in self.adapters:
    128. try:
    129. return adapter.name, adapter.generate(prompt)
    130. except ModelError as err:
    131. failures.append(str(err))
    132. logger.warning("falling back to the next model, reason: %s", err)
    133. raise ModelError("all models failed: " + "; ".join(failures))
    134. if __name__ == "__main__":
    135. logging.basicConfig(level=logging.INFO)
    136. primary = JsonHttpAdapter(
    137. "model-a", "https://api.example.com/v1/generate", "MODEL_A_API_KEY", timeout_s=30)
    138. backup = JsonHttpAdapter(
    139. "model-b", "https://api.example.net/v1/generate", "MODEL_B_API_KEY", timeout_s=20)
    140. router = ModelRouter([primary, backup])
    141. try:
    142. used_model, text = router.generate("Write a unit test draft for the order module")
    143. print(used_model, text)
    144. except ModelError as err:
    145. print("call failed:", err)

    A few design points in the code deserve explanation:

    • Timeouts: timeout_s must be passed to the HTTP client so the client enforces it during connection and read phases. Timing only from the outside cannot interrupt a request that has already been sent.
    • Retries: only RetryableError is retried, covering timeouts, connection failures, 408, 429, and 5xx. FatalError cases such as bad parameters or authentication failures fail immediately—retrying them only wastes quota.
    • Backoff: prefer the wait time the provider specifies in the Retry-After header, which may be either seconds or an HTTP date. When the header is absent, use exponential backoff with full jitter to prevent many clients from retrying simultaneously.
    • Rate limiting: ConcurrencyLimiter only caps concurrency within a single process. When deployed across multiple instances, each instance has its own limit and the totals multiply. In that case, you need a distributed shared counter, such as one backed by Redis,