Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): stream LLM calls in workers to unblock moonshot/kimi (#42)

warren618b769580389c3
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.py
index aa06f08a4..5935d026d 100644
--- a/agent/src/swarm/runtime.py
+++ b/agent/src/swarm/runtime.py
@@ -9,7 +9,12 @@ from __future__ import annotations
import logging
import threading
-from concurrent.futures import Future, ThreadPoolExecutor, as_completed
+from concurrent.futures import (
+ Future,
+ ThreadPoolExecutor,
+ TimeoutError as FuturesTimeoutError,
+ as_completed,
+)
from datetime import datetime, timezone
from pathlib import Path
from typing import Callable
@@ -340,6 +345,7 @@ class SwarmRuntime:
with ThreadPoolExecutor(max_workers=self._max_workers) as executor:
futures: dict[Future[WorkerResult], str] = {}
+ layer_budget = 0 # seconds — max per-task (retries × timeout) across layer
for tid in layer_task_ids:
task = task_store.load_task(tid)
@@ -378,17 +384,38 @@ class SwarmRuntime:
run_id=run.id,
)
futures[future] = tid
+ per_task_budget = agent_spec.timeout_seconds * (agent_spec.max_retries + 1)
+ layer_budget = max(layer_budget, per_task_budget)
- # Collect results
- for future in as_completed(futures):
- tid = futures[future]
- try:
- results[tid] = future.result()
- except Exception as exc:
- logger.error("Worker for task %s raised exception", tid, exc_info=True)
+ # Collect results with a hard layer-level deadline — defends against
+ # worker threads stuck in C extensions / blocked I/O that bypass the
+ # in-loop timeout check (issue #42).
+ deadline_buffer = 60
+ layer_deadline = layer_budget + deadline_buffer if layer_budget else None
+
+ try:
+ for future in as_completed(futures, timeout=layer_deadline):
+ tid = futures[future]
+ try:
+ results[tid] = future.result()
+ except Exception as exc:
+ logger.error("Worker for task %s raised exception", tid, exc_info=True)
+ results[tid] = WorkerResult(
+ status="failed", summary="",
+ error=str(exc),
+ )
+ except FuturesTimeoutError:
+ for pending, tid in futures.items():
+ if tid in results:
+ continue
+ pending.cancel()
+ logger.error(
+ "Worker for task %s exceeded layer deadline (%ds)",
+ tid, layer_deadline,
+ )
results[tid] = WorkerResult(
- status="failed", summary="",
- error=str(exc),
+ status="timeout", summary="",
+ error=f"Worker exceeded layer deadline of {layer_deadline}s",
)
return results
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 218cdd27e..a82e3ee20 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -322,10 +322,21 @@ def run_worker(
is_last_iteration = iteration == max_iterations - 1
tool_defs = None if is_last_iteration else registry.get_definitions()
- # Call LLM with remaining timeout
+ # Stream the LLM — moonshot/kimi non-streaming invoke is unreliable
+ # (issue #42), and streaming also feeds dashboard live progress.
try:
remaining_timeout = max(10, int(timeout - elapsed))
- response = llm.chat(messages, tools=tool_defs, timeout=remaining_timeout)
+
+ def _on_text_chunk(delta: str) -> None:
+ _emit(event_callback, "worker_text", agent_id, task_id,
+ {"content": delta, "iteration": iteration})
+
+ response = llm.stream_chat(
+ messages,
+ tools=tool_defs,
+ timeout=remaining_timeout,
+ on_text_chunk=_on_text_chunk,
+ )
except Exception as exc:
error_msg = f"LLM call failed at iteration {iteration}: {exc}"
logger.warning(error_msg)
@@ -345,11 +356,6 @@ def run_worker(
total_input_tokens += iter_in
total_output_tokens += iter_out
- # Emit agent thinking text for live streaming
- if response.content and response.content.strip():
- _emit(event_callback, "worker_text", agent_id, task_id,
- {"content": response.content, "iteration": iteration})
-
# Track last meaningful assistant content
if response.content and len(response.content.strip()) > 20:
last_assistant_content = response.content