Coverage for app / services / swarms / tasks.py: 75%

213 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Carrying out one task of a swarm run: one agent's governed turn. 

2 

3The coordinator (``swarms.engine``) decides what a task is asked and how 

4much it may spend, and hands a :class:`TaskJob` to a worker thread; 

5:func:`run_task` carries it out and returns a :class:`TaskOutcome`, plain 

6data the coordinator records. Nothing here touches the run's rows: the 

7worker opens a session of its own, so a slow agent never holds the 

8coordinator's. 

9 

10The call goes through ``evaluation.targets.AgentTarget`` — the governed path 

11evaluations and dashboard tiles already use. The agent answers as itself 

12(its model, knowledge, tools and skill graph); its rules run before and 

13after the call; svc-ai is told the task's lease (``spend_ceiling``), the 

14call's id and the run's workspace; and each call is on the usage ledger the 

15moment it finishes, attributed to the swarm (``UsageEnum.Source.swarm``), so 

16a cost cap judging the next task counts it. 

17""" 

18 

19from __future__ import annotations 

20 

21import logging 

22from dataclasses import dataclass, field, replace 

23from decimal import Decimal 

24from typing import Any 

25from uuid import UUID 

26 

27import httpx 

28from pydantic import BaseModel 

29 

30from app.db.postgres.engine import SessionLocal 

31from app.db.postgres.enums import SwarmEnum, UsageEnum 

32from app.db.postgres.models import Swarm 

33from app.services import ai_client, uploads 

34from app.services import attachments as attachment_service 

35from app.services import usage as usage_service 

36from app.services import workspace as workspace_service 

37from app.services.evaluation.targets import ( 

38 AgentTarget, 

39 Invocation, 

40 TargetResolutionError, 

41 build_target, 

42 invoke_structured, 

43 ledger_identity, 

44) 

45from app.services.swarms import parts 

46from app.util.attachment_wire import AttachedIn 

47 

48logger = logging.getLogger(__name__) 

49 

50#: The ``purpose`` svc-ai records on a swarm task's invocation trace. 

51TRACE_PURPOSE = "swarm" 

52#: …and on a task of a run an evaluation started: the evaluation's. 

53EVALUATION_PURPOSE = "evaluation" 

54 

55 

56@dataclass(frozen=True) 

57class LedgerAs: 

58 """Whose spend a task's calls are, and what they are recorded as: the 

59 swarm's own, as a person dispatched it — or, for a run an evaluation's 

60 cell started, the evaluation's (``engine._ledger_as``), as evaluating 

61 an agent is. ``source_id`` None is the swarm's id for the swarm's own 

62 spend, and no id for any other source.""" 

63 

64 def source(self, swarm_id: Any) -> Any: 

65 if self.source_type == UsageEnum.Source.swarm: 

66 return self.source_id or swarm_id 

67 return self.source_id 

68 

69 source_type: str = UsageEnum.Source.swarm 

70 source_id: str | None = None 

71 execution_type: str = UsageEnum.ExecutionType.swarm 

72 purpose: str = TRACE_PURPOSE 

73 

74 

75@dataclass(frozen=True) 

76class TaskJob: 

77 """Everything one task's call needs, read off the run before it starts.""" 

78 

79 task_id: UUID 

80 run_id: UUID 

81 swarm_id: UUID | None 

82 #: ``SwarmEnum.TaskKind``. 

83 kind: str 

84 user_id: str 

85 agent_id: str 

86 tier: str 

87 cost_profile: str | None 

88 prompt: str 

89 #: The ``ModelOutput`` a structured step fills; None for prose. 

90 schema: type[BaseModel] | None 

91 #: Documents the step reads (the team's work), as svc-ai takes them. 

92 documents: tuple[dict[str, Any], ...] 

93 #: The person's documents, from the workspace's library. 

94 file_ids: tuple[str, ...] 

95 #: What the call may spend (``budget.limit``). 

96 limit: Any 

97 timeout_s: float 

98 may_ask: bool 

99 workspace_key: str | None 

100 invocation_id: str 

101 reference: dict[str, str] = field(default_factory=dict) 

102 #: Read only this part of the person's documents (from 1), as a chain 

103 #: of agents does (``swarms.parts``). 

104 part: int | None = None 

105 #: Whose spend its calls are. 

106 ledger: LedgerAs = field(default_factory=LedgerAs) 

107 #: Of ``file_ids``, those carried from earlier requests of the thread: 

108 #: sent as documents of the conversation so far, not of this request. 

109 carried_file_ids: tuple[str, ...] = () 

110 

111 

112@dataclass 

113class TaskOutcome: 

114 """What one task's call came to.""" 

115 

116 output: str = "" 

117 #: A structured step's reply, validated, as JSON. 

118 value: dict[str, Any] | None = None 

119 #: The questions the agent asked instead of answering. 

120 questions: list[dict[str, Any]] | None = None 

121 error: str | None = None 

122 blocked: bool = False 

123 #: Its lease ran out mid-call. 

124 stopped: bool = False 

125 withheld: bool = False 

126 cost_usd: Decimal | None = None 

127 spent_usd: Decimal = Decimal(0) 

128 llm_calls: int = 0 

129 unpriced_calls: int = 0 

130 input_tokens: int = 0 

131 output_tokens: int = 0 

132 latency_ms: int = 0 

133 rule_events: list[dict[str, Any]] = field(default_factory=list) 

134 #: Things the reader should know that are not failures. 

135 notes: list[str] = field(default_factory=list) 

136 #: The step was asked to fill a schema: with no ``value``, it failed. 

137 structured: bool = False 

138 #: Its call ran out of time (``ai_client.AIServiceTimeout``). 

139 timed_out: bool = False 

140 #: Its call failed for a reason that may pass — svc-ai unreachable, or 

141 #: failing on its side — so it is worth one more try. 

142 transient: bool = False 

143 #: What a failed call raised, by class: for the log, never shown. 

144 failure_kind: str | None = None 

145 #: The sources its answer cites, each with the ``marker`` its text cites 

146 #: it by — kept on the task, and handed on with its text to the steps 

147 #: that read it, so they cite the sources themselves. 

148 citations: list[dict[str, Any]] | None = None 

149 

150 @classmethod 

151 def of( 

152 cls, 

153 invocations: list[Invocation], 

154 *, 

155 value: dict[str, Any] | None = None, 

156 failure: str | None = None, 

157 notes: list[str] | None = None, 

158 ) -> TaskOutcome: 

159 """The outcome of a step's calls — one, or a structured step's two.""" 

160 last = invocations[-1] 

161 outcome = cls(notes=list(notes or [])) 

162 costs = [] 

163 for invocation in invocations: 

164 usage = invocation.usage 

165 outcome.latency_ms += int(invocation.latency_ms or 0) 

166 outcome.rule_events.extend(invocation.rule_events or []) 

167 if getattr(usage, "measured", False): 

168 outcome.llm_calls += usage.calls 

169 outcome.unpriced_calls += usage.unpriced_calls 

170 outcome.input_tokens += usage.input_tokens 

171 outcome.output_tokens += usage.output_tokens 

172 outcome.spent_usd += usage.enforcement_usd() 

173 if usage.cost_usd is not None: 

174 costs.append(Decimal(str(usage.cost_usd))) 

175 else: 

176 outcome.input_tokens += int(invocation.input_tokens or 0) 

177 outcome.output_tokens += int(invocation.output_tokens or 0) 

178 outcome.cost_usd = sum(costs, Decimal(0)) if costs else None 

179 outcome.withheld = bool(getattr(last, "withheld", False)) 

180 if not last.ok: 

181 outcome.error = last.shown_error 

182 outcome.blocked = last.blocked 

183 outcome.stopped = isinstance(last.raised, ai_client.SpendLimitReached) 

184 outcome.timed_out = isinstance(last.raised, ai_client.AIServiceTimeout) 

185 outcome.transient = transient(last.raised) 

186 if last.raised is not None: 

187 outcome.failure_kind = type(last.raised).__name__ 

188 return outcome 

189 if last.clarification: 

190 outcome.questions = list(last.clarification) 

191 return outcome 

192 outcome.output = last.output or "" 

193 outcome.value = value 

194 outcome.citations = getattr(last, "citations", None) 

195 if failure: 

196 outcome.error = f"The reply did not fit what was asked: {failure}" 

197 return outcome 

198 

199 

200def transient(raised: BaseException | None) -> bool: 

201 """Whether a call that raised ``raised`` may succeed if made again: 

202 svc-ai could not be reached, or failed on its side (5xx). A refusal, a 

203 block, a timeout or a request svc-ai rejected would fail the same way.""" 

204 if not isinstance(raised, ai_client.AIServiceError) or isinstance( 

205 raised, 

206 ( 

207 ai_client.ModelRefusedError, 

208 ai_client.AIServiceTimeout, 

209 ai_client.RuleBlockedError, 

210 ), 

211 ): 

212 return False 

213 cause = raised.__cause__ 

214 if isinstance(cause, httpx.HTTPStatusError): 

215 return cause.response.status_code >= 500 

216 return isinstance(cause, httpx.RequestError) 

217 

218 

219def run_task(job: TaskJob) -> TaskOutcome: 

220 """Carry out ``job`` on a session of its own. Never raises: a failure is 

221 an outcome the coordinator records.""" 

222 db = SessionLocal() 

223 try: 

224 outcome = _run(db, job) 

225 except Exception: # a task's failure is the run's to record 

226 logger.exception("Swarm task %s crashed", job.task_id) 

227 return TaskOutcome(error="The task could not be carried out.") 

228 finally: 

229 db.close() 

230 if outcome.error and not outcome.blocked: 

231 # The person reads ``error``; this says which task, and what was 

232 # raised, where an operator looks. 

233 logger.warning( 

234 "Swarm task %s of run %s (%s) failed: %s", 

235 job.task_id, 

236 job.run_id, 

237 job.kind, 

238 outcome.failure_kind or outcome.error, 

239 ) 

240 return outcome 

241 

242 

243def _run(db: Any, job: TaskJob) -> TaskOutcome: 

244 swarm = db.get(Swarm, job.swarm_id) if job.swarm_id else None 

245 if swarm is None: 

246 return TaskOutcome(error="The swarm was deleted while it ran.") 

247 # Who an organisation's or project's swarm runs as: whoever dispatched 

248 # it (``targets._actor_of``), not whoever created it. 

249 swarm.run_by_user_id = job.user_id 

250 notes: list[str] = [] 

251 try: 

252 target = _target(db, swarm, job, notes) 

253 except TargetResolutionError as exc: 

254 return TaskOutcome(error=str(exc)) 

255 library = _library(db, job) 

256 value = None 

257 if job.part is not None: 

258 part = parts.part_of(library, job.part) 

259 if part is None: 

260 return TaskOutcome( 

261 error="The documents could not be read, or hold no such part." 

262 ) 

263 library, value = [part.spec()], {"part": job.part, "parts": part.count} 

264 documents = [*job.documents, *library] 

265 with ai_client.in_workspace(job.workspace_key or "personal"): 

266 if job.schema is not None: 

267 result = invoke_structured( 

268 target, 

269 job.prompt, 

270 "", 

271 job.schema, 

272 attachments=documents or None, 

273 invocation_id=job.invocation_id, 

274 ) 

275 outcome = TaskOutcome.of( 

276 result.invocations, 

277 value=result.value.model_dump(mode="json") if result.value else None, 

278 failure=None if result.value is not None else result.failure, 

279 notes=notes, 

280 ) 

281 outcome.structured = True 

282 return outcome 

283 invocation = target.invoke( 

284 job.prompt, 

285 "", 

286 None, 

287 attachments=documents or None, 

288 invocation_id=job.invocation_id, 

289 ) 

290 return TaskOutcome.of([invocation], value=value, notes=notes) 

291 

292 

293def _target(db: Any, swarm: Swarm, job: TaskJob, notes: list[str]) -> AgentTarget: 

294 """The task's agent as a governed target: at its level's model and 

295 effort, attributed to the swarm, held to the task's lease.""" 

296 spec: dict[str, Any] = {"type": "agent", "agent_id": job.agent_id} 

297 if job.cost_profile: 

298 spec["cost_profile"] = job.cost_profile 

299 target = build_target(spec, db, owner=swarm) 

300 if job.tier == SwarmEnum.Tier.lighter: 

301 choice = target.lighter_model_choice() 

302 if choice.model is not None and choice.model.get("id"): 

303 target = build_target( 

304 {**spec, "model_id": str(choice.model["id"])}, db, owner=swarm 

305 ) 

306 else: 

307 notes.append( 

308 f"{target.label} has no lighter model ({choice.text}); it " 

309 "worked on its own." 

310 ) 

311 target.attribute( 

312 purpose=job.ledger.purpose, 

313 execution_type=job.ledger.execution_type, 

314 reference=job.reference, 

315 attended=job.may_ask, 

316 ) 

317 target.timeout = job.timeout_s 

318 limit = job.limit 

319 target.spend_ceiling = lambda: limit 

320 target.on_call = _ledger_as_it_goes(swarm, job) 

321 return target 

322 

323 

324def _library(db: Any, job: TaskJob) -> list[dict[str, Any]]: 

325 """The person's documents, as the run's workspace holds them now. One 

326 deleted since the run began is left out; one not read yet is too — 

327 the run does not wait for it.""" 

328 if not job.file_ids: 

329 return [] 

330 ws = ( 

331 workspace_service.from_key(db, job.workspace_key) 

332 if job.workspace_key 

333 else workspace_service.Workspace( 

334 workspace_service.WorkspaceKind.personal, UUID(job.user_id) 

335 ) 

336 ) 

337 try: 

338 docs = attachment_service.turn_attachments(db, job.file_ids, ws) 

339 except (uploads.DocumentsNotReady, attachment_service.TooManyDocuments): 

340 logger.warning("Swarm task %s could not read its documents", job.task_id) 

341 return [] 

342 carried = set(job.carried_file_ids) 

343 return attachment_service.wire( 

344 [ 

345 replace(doc, attached_in=AttachedIn.earlier) if doc.id in carried else doc 

346 for doc in docs 

347 ] 

348 ) 

349 

350 

351def _ledger_as_it_goes(swarm: Swarm, job: TaskJob): 

352 """Put each of the task's calls on the usage ledger as it finishes, in a 

353 transaction of its own — the money is spent whether or not the run's 

354 rows are written — attributed to the swarm, scoped to the agent, as the 

355 person who dispatched the run.""" 

356 owner_project_id = swarm.owner_project_id 

357 owner_organisation_id = swarm.owner_organisation_id 

358 source_id = job.ledger.source(swarm.id) 

359 

360 def ledger(target: Any, invocation: Invocation) -> None: 

361 if invocation.blocked or invocation.ledgered: 

362 return 

363 session = SessionLocal() 

364 try: 

365 scope_type, scope_id, model_info = ledger_identity(target, invocation) 

366 row = usage_service.record_usage( 

367 session, 

368 owner_user_id=job.user_id, 

369 execution_type=job.ledger.execution_type, 

370 scope_type=scope_type, 

371 scope_id=scope_id, 

372 owner_project_id=owner_project_id, 

373 owner_organisation_id=owner_organisation_id, 

374 ai_model_id=model_info.get("id") if model_info else None, 

375 input_tokens=invocation.input_tokens, 

376 output_tokens=invocation.output_tokens, 

377 model_info=model_info or None, 

378 latency_ms=invocation.latency_ms, 

379 outcome=( 

380 UsageEnum.Outcome.ok if invocation.ok else UsageEnum.Outcome.error 

381 ), 

382 # The swarm is what the person built and sent — or the 

383 # evaluation that sent it: the agent is only who did this 

384 # piece. 

385 source_type=job.ledger.source_type, 

386 source_id=source_id, 

387 measured=invocation.usage, 

388 invocation_id=invocation.invocation_id, 

389 ) 

390 if row is not None: 

391 session.commit() 

392 invocation.ledgered = True 

393 except Exception: # the ledger never fails a task 

394 logger.exception("Could not ledger a swarm task's call") 

395 session.rollback() 

396 finally: 

397 session.close() 

398 

399 return ledger 

400 

401 

402def ledger_interrupted( 

403 db: Any, 

404 *, 

405 swarm: Swarm | None, 

406 user_id: Any, 

407 agent_id: Any, 

408 invocation_id: Any, 

409 ledger: LedgerAs | None = None, 

410) -> Any: 

411 """Ledger what a call cut off by a restart spent, read from svc-ai's 

412 trace of it (``ai_client.reconcile_turn_usage``): the money was spent 

413 though no answer came back. Returns the usage, or None when svc-ai has 

414 no record. Added to ``db``'s transaction.""" 

415 used = ai_client.reconcile_turn_usage(None, invocation_id, user_id, legs=1) 

416 if used is None or not getattr(used, "measured", False): 

417 return None 

418 ledger = ledger or LedgerAs() 

419 usage_service.record_usage( 

420 db, 

421 owner_user_id=user_id, 

422 execution_type=ledger.execution_type, 

423 scope_type="agent", 

424 scope_id=agent_id, 

425 owner_project_id=getattr(swarm, "owner_project_id", None), 

426 owner_organisation_id=getattr(swarm, "owner_organisation_id", None), 

427 outcome=UsageEnum.Outcome.error, 

428 source_type=ledger.source_type, 

429 source_id=ledger.source(getattr(swarm, "id", None)), 

430 measured=used, 

431 invocation_id=invocation_id, 

432 ) 

433 return used