worker.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """
  2. engine.worker — Background worker that consumes jobs from the queue.
  3. Usage: python -m agentpaas worker --concurrency 4
  4. """
  5. from __future__ import annotations
  6. import asyncio
  7. import json
  8. import time
  9. from agentpaas.engine.queue import create_queue, Job
  10. from agentpaas.engine.sandbox import Sandbox
  11. from agentpaas.db.session import get_db
  12. from agentpaas.db.models import gen_id, now_utc
  13. from agentpaas.config import settings
  14. async def run_worker(concurrency: int = 4):
  15. """Main worker loop: dequeue jobs and execute them."""
  16. queue = create_queue(settings.redis_url)
  17. sandbox = Sandbox(level=settings.sandbox_level)
  18. worker_id = gen_id("wk_")
  19. print(f"Worker {worker_id} started, concurrency={concurrency}")
  20. semaphore = asyncio.Semaphore(concurrency)
  21. async def process_job(job: Job):
  22. async with semaphore:
  23. db = get_db()
  24. run_id = gen_id("run_")
  25. now = now_utc()
  26. db.execute(
  27. "INSERT INTO runs (id, agent_id, agent_version, tenant_id, job_id, input, status, created_at) "
  28. "VALUES (?, ?, ?, ?, ?, ?, 'running', ?)",
  29. (run_id, job.agent_id, job.agent_version, job.tenant_id, job.id, job.input, now)
  30. )
  31. db.commit()
  32. result = await sandbox.execute(job.config, job.input, settings.default_timeout)
  33. db.execute(
  34. "UPDATE runs SET status=?, output=?, duration_ms=?, steps=?, "
  35. "input_tokens=?, completed_at=? WHERE id=?",
  36. (result.status, result.output, result.duration_ms, result.steps,
  37. result.input_tokens, now_utc(), run_id)
  38. )
  39. queue.update_job(job.id, status=result.status, result=result.output)
  40. db.commit()
  41. print(f" Job {job.id} → {result.status} ({result.duration_ms}ms)")
  42. while True:
  43. job = await queue.dequeue(timeout=5.0)
  44. if job:
  45. asyncio.create_task(process_job(job))
  46. await asyncio.sleep(0.1)