merge.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """Pure partitioning, result splicing, and rendering for mixed tool-call batches.
  2. Correlate all remote results by original call position, never wire ``index``.
  3. """
  4. from __future__ import annotations
  5. from dataclasses import dataclass
  6. from typing import Any, Mapping, Optional, Sequence
  7. from tools.connectors.gateway.errors import render_connection_required
  8. from tools.connectors.gateway.names import parse_connector_name
  9. from tools.connectors.turn import connection_surface
  10. __all__ = [
  11. "Partition",
  12. "PlannedCall",
  13. "assemble_results",
  14. "fill_remote_failure",
  15. "partition_calls",
  16. "render_remote_entry",
  17. "splice_remote_results",
  18. ]
  19. # Codes the user resolves by connecting the app; both carry the card or link.
  20. _CONNECTION_CODES = frozenset({"CONNECTION_REQUIRED", "CONNECTION_EXPIRED"})
  21. @dataclass(frozen=True)
  22. class PlannedCall:
  23. position: int
  24. name: str
  25. connector: str
  26. tool: str
  27. arguments: dict[str, Any]
  28. @dataclass(frozen=True)
  29. class Partition:
  30. local: tuple[tuple[int, Mapping[str, Any]], ...]
  31. # Gateway request and response slots preserve this order.
  32. remote: tuple[PlannedCall, ...]
  33. errors: tuple[dict[str, Any], ...]
  34. def partition_calls(calls: Sequence[Any]) -> Partition:
  35. """Treat malformed input as per-entry errors so sibling calls still run."""
  36. local: list[tuple[int, Mapping[str, Any]]] = []
  37. remote: list[PlannedCall] = []
  38. errors: list[dict[str, Any]] = []
  39. for position, call in enumerate(_as_sequence(calls)):
  40. name = call.get("name") if isinstance(call, Mapping) else None
  41. parsed = parse_connector_name(name)
  42. if parsed is not None:
  43. arguments = call.get("arguments")
  44. remote.append(
  45. PlannedCall(
  46. position=position,
  47. name=parsed.raw,
  48. connector=parsed.connector,
  49. tool=parsed.tool,
  50. arguments=dict(arguments) if isinstance(arguments, Mapping) else {},
  51. )
  52. )
  53. continue
  54. if isinstance(name, str) and name.startswith("connectors__"):
  55. errors.append(
  56. _error_entry(
  57. position,
  58. name,
  59. code="TOOL_NOT_FOUND",
  60. message=(
  61. "Malformed connector tool name; expected "
  62. "connectors__<connector>__{tool}."
  63. ),
  64. )
  65. )
  66. continue
  67. local.append((position, call if isinstance(call, Mapping) else {}))
  68. return Partition(local=tuple(local), remote=tuple(remote), errors=tuple(errors))
  69. def render_remote_entry(planned: PlannedCall, remote: Mapping[str, Any]) -> dict[str, Any]:
  70. """Use the shared connection shape so links render consistently.
  71. The model sees code, message, connector and the gateway's hint, plus ``family`` when the gateway
  72. classified the failure. Transport details (status, request id) stay in the logs."""
  73. error = remote.get("error") if isinstance(remote, Mapping) else None
  74. account = _opt_str(remote.get("account")) if isinstance(remote, Mapping) else None
  75. if not isinstance(error, Mapping):
  76. data = remote.get("data") if isinstance(remote, Mapping) else None
  77. entry = _with_account({"index": planned.position, "name": planned.name, "response": data}, account)
  78. # Message metadata, never model content: dispatch lifts it off before the result is rendered.
  79. if isinstance(remote, Mapping) and remote.get("data_use"):
  80. entry["data_use"] = list(remote["data_use"])
  81. return entry
  82. code = str(error.get("code") or "PROVIDER_ERROR")
  83. message = str(error.get("message") or "The gateway reported an error.")
  84. if code in _CONNECTION_CODES:
  85. payload = render_connection_required(
  86. connector=_opt_str(error.get("connector")) or planned.connector,
  87. message=message,
  88. connect_url=_opt_str(error.get("connect_url")),
  89. hint=_opt_str(error.get("hint")),
  90. surface=connection_surface(),
  91. code=code,
  92. )
  93. # The account the link repairs or waits on; with no connect_url the user already holds its link.
  94. connection_id = _opt_str(error.get("connection_id"))
  95. if connection_id:
  96. payload["connection_id"] = connection_id
  97. else:
  98. payload = {"code": code, "message": message}
  99. connector = _opt_str(error.get("connector"))
  100. if connector:
  101. payload["connector"] = connector
  102. hint = _opt_str(error.get("hint"))
  103. if hint:
  104. payload["hint"] = hint
  105. family = _opt_str(error.get("family"))
  106. if family:
  107. payload["family"] = family
  108. return _with_account({"index": planned.position, "name": planned.name, "error": payload}, account)
  109. def _with_account(entry: dict[str, Any], account: Optional[str]) -> dict[str, Any]:
  110. if account:
  111. entry["account"] = account
  112. return entry
  113. def splice_remote_results(
  114. planned: Sequence[PlannedCall],
  115. remote_results: Optional[Sequence[Any]],
  116. ) -> list[dict[str, Any]]:
  117. """Correlate results by request slot; missing slots become per-entry errors."""
  118. results = _as_sequence(remote_results)
  119. entries: list[dict[str, Any]] = []
  120. for slot, plan in enumerate(_as_sequence(planned)):
  121. if slot < len(results) and isinstance(results[slot], Mapping):
  122. entries.append(render_remote_entry(plan, results[slot]))
  123. else:
  124. entries.append(
  125. _error_entry(
  126. plan.position,
  127. plan.name,
  128. code="PROVIDER_ERROR",
  129. message="The gateway returned no result for this call.",
  130. )
  131. )
  132. return entries
  133. def fill_remote_failure(
  134. planned: Sequence[PlannedCall],
  135. message: str,
  136. *,
  137. code: str = "PROVIDER_ERROR",
  138. ) -> list[dict[str, Any]]:
  139. return [
  140. _error_entry(plan.position, plan.name, code=code, message=message)
  141. for plan in planned
  142. ]
  143. def assemble_results(
  144. total: int,
  145. *entry_groups: Sequence[Mapping[str, Any]],
  146. ) -> dict[str, Any]:
  147. """Preserve call order and fill unclaimed slots with per-entry errors."""
  148. try:
  149. slot_count = max(0, int(total))
  150. except (TypeError, ValueError):
  151. slot_count = 0
  152. slots: list[Optional[dict[str, Any]]] = [None] * slot_count
  153. for group in entry_groups:
  154. for entry in _as_sequence(group):
  155. if not isinstance(entry, Mapping):
  156. continue
  157. index = entry.get("index")
  158. if isinstance(index, int) and 0 <= index < len(slots) and slots[index] is None:
  159. slots[index] = dict(entry)
  160. merged: list[dict[str, Any]] = []
  161. for position, entry in enumerate(slots):
  162. if entry is None:
  163. entry = _error_entry(
  164. position,
  165. "",
  166. code="PROVIDER_ERROR",
  167. message="No result was produced for this call.",
  168. )
  169. merged.append(entry)
  170. error_count = sum(1 for entry in merged if "error" in entry)
  171. return {
  172. "results": merged,
  173. "success_count": len(merged) - error_count,
  174. "error_count": error_count,
  175. "total_count": len(merged),
  176. }
  177. def _error_entry(position: int, name: str, *, code: str, message: str) -> dict[str, Any]:
  178. return {
  179. "index": position,
  180. "name": name,
  181. "error": {"code": code, "message": message},
  182. }
  183. def _as_sequence(value: Any) -> Sequence[Any]:
  184. """Reject strings so malformed calls do not become character entries."""
  185. if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
  186. return value
  187. return ()
  188. def _opt_str(value: Any) -> Optional[str]:
  189. if isinstance(value, str) and value:
  190. return value
  191. return None