agent_client.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import httpx
  2. from core_domain import AgentRunContract
  3. from core_shared import JSONValue
  4. class AgentServiceClientError(Exception):
  5. pass
  6. class AgentServiceClient:
  7. def __init__(self, base_url: str, timeout_seconds: float = 30.0) -> None:
  8. self.base_url = base_url.rstrip("/")
  9. self.timeout_seconds = timeout_seconds
  10. def create_agent_run(
  11. self,
  12. *,
  13. tenant_id: str,
  14. agent_id: str,
  15. agent_version_id: str | None,
  16. session_id: str | None,
  17. input_text: str | None,
  18. input_json: dict[str, JSONValue] | None,
  19. ) -> AgentRunContract:
  20. payload: dict[str, JSONValue] = {
  21. "tenant_id": tenant_id,
  22. "agent_id": agent_id,
  23. }
  24. if agent_version_id is not None:
  25. payload["agent_version_id"] = agent_version_id
  26. if session_id is not None:
  27. payload["session_id"] = session_id
  28. if input_text is not None:
  29. payload["input_text"] = input_text
  30. if input_json is not None:
  31. payload["input_json"] = input_json
  32. try:
  33. with httpx.Client(timeout=self.timeout_seconds) as client:
  34. response = client.post(f"{self.base_url}/agents/runs", json=payload)
  35. response.raise_for_status()
  36. return AgentRunContract.model_validate(response.json())
  37. except httpx.HTTPError as exc:
  38. raise AgentServiceClientError(f"agent-service create run failed: {exc}") from exc
  39. def execute_agent_run(
  40. self,
  41. *,
  42. tenant_id: str,
  43. agent_run_id: str,
  44. worker_key: str | None,
  45. dry_run: bool,
  46. ) -> AgentRunContract:
  47. payload: dict[str, JSONValue] = {
  48. "tenant_id": tenant_id,
  49. "dry_run": dry_run,
  50. }
  51. if worker_key is not None:
  52. payload["worker_key"] = worker_key
  53. try:
  54. with httpx.Client(timeout=self.timeout_seconds) as client:
  55. response = client.post(
  56. f"{self.base_url}/agents/runs/{agent_run_id}/execute",
  57. json=payload,
  58. )
  59. response.raise_for_status()
  60. response_payload = response.json()
  61. run_payload = response_payload.get("run")
  62. if not isinstance(run_payload, dict):
  63. raise AgentServiceClientError("agent-service execute response missing run")
  64. return AgentRunContract.model_validate(run_payload)
  65. except httpx.HTTPError as exc:
  66. raise AgentServiceClientError(f"agent-service execute run failed: {exc}") from exc