agent_client.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. agent_id: str,
  14. agent_version_id: str | None,
  15. session_id: str | None,
  16. input_text: str | None,
  17. input_json: dict[str, JSONValue] | None) -> AgentRunContract:
  18. payload: dict[str, JSONValue] = {
  19. "agent_id": agent_id,
  20. }
  21. if agent_version_id is not None:
  22. payload["agent_version_id"] = agent_version_id
  23. if session_id is not None:
  24. payload["session_id"] = session_id
  25. if input_text is not None:
  26. payload["input_text"] = input_text
  27. if input_json is not None:
  28. payload["input_json"] = input_json
  29. try:
  30. with httpx.Client(timeout=self.timeout_seconds) as client:
  31. response = client.post(f"{self.base_url}/agents/runs", json=payload)
  32. response.raise_for_status()
  33. return AgentRunContract.model_validate(response.json())
  34. except httpx.HTTPError as exc:
  35. raise AgentServiceClientError(f"agent-service create run failed: {exc}") from exc
  36. def execute_agent_run(
  37. self,
  38. *,
  39. agent_run_id: str,
  40. worker_key: str | None,
  41. dry_run: bool) -> AgentRunContract:
  42. payload: dict[str, JSONValue] = {
  43. "dry_run": dry_run,
  44. }
  45. if worker_key is not None:
  46. payload["worker_key"] = worker_key
  47. try:
  48. with httpx.Client(timeout=self.timeout_seconds) as client:
  49. response = client.post(
  50. f"{self.base_url}/agents/runs/{agent_run_id}/execute",
  51. json=payload)
  52. response.raise_for_status()
  53. response_payload = response.json()
  54. run_payload = response_payload.get("run")
  55. if not isinstance(run_payload, dict):
  56. raise AgentServiceClientError("agent-service execute response missing run")
  57. return AgentRunContract.model_validate(run_payload)
  58. except httpx.HTTPError as exc:
  59. raise AgentServiceClientError(f"agent-service execute run failed: {exc}") from exc