smoke_runtime_no_key.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. from __future__ import annotations
  2. import json
  3. import os
  4. import sys
  5. import uuid
  6. from dataclasses import dataclass
  7. import httpx
  8. WORKFLOW_SERVICE_URL = os.getenv(
  9. "AGENT_PLATFORM_SMOKE_WORKFLOW_URL",
  10. "http://127.0.0.1:8002/workflows")
  11. RUNTIME_SERVICE_URL = os.getenv(
  12. "AGENT_PLATFORM_SMOKE_RUNTIME_URL",
  13. "http://127.0.0.1:8003/runtime")
  14. SMOKE_API_KEY = os.getenv("AGENT_PLATFORM_SMOKE_API_KEY")
  15. @dataclass(frozen=True)
  16. class SmokeScenario:
  17. score: int
  18. expected_branch_node_id: str
  19. expected_output_text: str
  20. SCENARIOS = (
  21. SmokeScenario(
  22. score=7,
  23. expected_branch_node_id="high_path",
  24. expected_output_text="Alice passed with score 7"),
  25. SmokeScenario(
  26. score=3,
  27. expected_branch_node_id="low_path",
  28. expected_output_text="Alice did not pass; score 3"))
  29. def main() -> int:
  30. unique_suffix = uuid.uuid4().hex[:8]
  31. headers = {}
  32. if SMOKE_API_KEY:
  33. headers["x-api-key"] = SMOKE_API_KEY
  34. with httpx.Client(timeout=20.0, headers=headers) as client:
  35. app_id = create_app(client, unique_suffix)
  36. workflow_id = create_workflow(client, app_id, unique_suffix)
  37. results: list[dict[str, object]] = []
  38. for scenario in SCENARIOS:
  39. results.append(run_scenario(client, app_id, workflow_id, unique_suffix, scenario))
  40. results.append(run_retriever_scenario(client, app_id, workflow_id, unique_suffix))
  41. print(json.dumps(results, ensure_ascii=False, indent=2))
  42. return 0
  43. def create_app(client: httpx.Client, unique_suffix: str) -> str:
  44. response = client.post(
  45. f"{WORKFLOW_SERVICE_URL}/apps",
  46. json={
  47. "code": f"smoke-app-{unique_suffix}",
  48. "name": f"Smoke App {unique_suffix}",
  49. })
  50. response.raise_for_status()
  51. payload = response.json()
  52. return str(payload["id"])
  53. def create_workflow(client: httpx.Client, app_id: str, unique_suffix: str) -> str:
  54. response = client.post(
  55. WORKFLOW_SERVICE_URL,
  56. json={
  57. "app_id": app_id,
  58. "code": f"smoke-flow-{unique_suffix}",
  59. "name": f"Smoke Flow {unique_suffix}",
  60. })
  61. response.raise_for_status()
  62. payload = response.json()
  63. return str(payload["id"])
  64. def run_scenario(
  65. client: httpx.Client,
  66. app_id: str,
  67. workflow_id: str,
  68. unique_suffix: str,
  69. scenario: SmokeScenario) -> dict[str, object]:
  70. workflow_version_id = create_workflow_version(client, workflow_id, unique_suffix, scenario.score)
  71. app_version_id = create_app_version(client, app_id, workflow_version_id)
  72. run_id = create_run(client, app_id, app_version_id, workflow_id, workflow_version_id)
  73. execute_run(client, run_id)
  74. node_runs = list_node_runs(client, run_id)
  75. artifacts = list_node_artifacts(client, run_id)
  76. if len(artifacts) < 3:
  77. raise AssertionError(f"expected at least 3 artifacts, got {len(artifacts)}")
  78. trace_spans = list_trace_spans(client, run_id)
  79. if len(trace_spans) < 3:
  80. raise AssertionError(f"expected at least 3 trace spans, got {len(trace_spans)}")
  81. node_map = {str(item["node_id"]): item for item in node_runs}
  82. assert scenario.expected_branch_node_id in node_map, (
  83. f"expected branch node not found: {scenario.expected_branch_node_id}"
  84. )
  85. expected_node = node_map[scenario.expected_branch_node_id]
  86. actual_output_text = expected_node.get("output_text")
  87. if actual_output_text != scenario.expected_output_text:
  88. raise AssertionError(
  89. f"unexpected output_text for {scenario.expected_branch_node_id}: {actual_output_text!r}"
  90. )
  91. other_branch_node_id = "low_path" if scenario.expected_branch_node_id == "high_path" else "high_path"
  92. if other_branch_node_id in node_map:
  93. raise AssertionError(f"unexpected branch node executed: {other_branch_node_id}")
  94. return {
  95. "score": scenario.score,
  96. "executed_node_ids": [str(item["node_id"]) for item in node_runs],
  97. "branch_output_text": actual_output_text,
  98. "artifact_count": len(artifacts),
  99. "trace_span_count": len(trace_spans),
  100. }
  101. def run_retriever_scenario(
  102. client: httpx.Client,
  103. app_id: str,
  104. workflow_id: str,
  105. unique_suffix: str) -> dict[str, object]:
  106. workflow_version_id = create_retriever_workflow_version(client, workflow_id, unique_suffix)
  107. app_version_id = create_app_version(client, app_id, workflow_version_id)
  108. run_id = create_run(client, app_id, app_version_id, workflow_id, workflow_version_id)
  109. execute_run(client, run_id)
  110. node_runs = list_node_runs(client, run_id)
  111. artifacts = list_node_artifacts(client, run_id)
  112. if len(artifacts) < 3:
  113. raise AssertionError(f"expected at least 3 retriever artifacts, got {len(artifacts)}")
  114. trace_spans = list_trace_spans(client, run_id)
  115. if len(trace_spans) < 3:
  116. raise AssertionError(f"expected at least 3 retriever trace spans, got {len(trace_spans)}")
  117. node_map = {str(item["node_id"]): item for item in node_runs}
  118. answer_node = node_map.get("render_answer")
  119. if answer_node is None:
  120. raise AssertionError("retriever answer node was not executed")
  121. answer_text = answer_node.get("output_text")
  122. expected_answer_text = "Top doc: Refund Policy"
  123. if answer_text != expected_answer_text:
  124. raise AssertionError(f"unexpected retriever answer text: {answer_text!r}")
  125. retrieve_node = node_map.get("retrieve_docs")
  126. if retrieve_node is None:
  127. raise AssertionError("retriever node was not executed")
  128. retrieve_output = retrieve_node.get("output_json")
  129. if not isinstance(retrieve_output, dict):
  130. raise AssertionError("retriever output_json must be an object")
  131. return {
  132. "scenario": "retriever",
  133. "executed_node_ids": [str(item["node_id"]) for item in node_runs],
  134. "answer_text": answer_text,
  135. "artifact_count": len(artifacts),
  136. "trace_span_count": len(trace_spans),
  137. }
  138. def create_workflow_version(
  139. client: httpx.Client,
  140. workflow_id: str,
  141. unique_suffix: str,
  142. score: int) -> str:
  143. response = client.post(
  144. f"{WORKFLOW_SERVICE_URL}/versions",
  145. json={
  146. "workflow_id": workflow_id,
  147. "status": "active",
  148. "dsl_json": build_workflow_dsl(unique_suffix, score),
  149. })
  150. response.raise_for_status()
  151. payload = response.json()
  152. return str(payload["id"])
  153. def create_retriever_workflow_version(
  154. client: httpx.Client,
  155. workflow_id: str,
  156. unique_suffix: str) -> str:
  157. response = client.post(
  158. f"{WORKFLOW_SERVICE_URL}/versions",
  159. json={
  160. "workflow_id": workflow_id,
  161. "status": "active",
  162. "dsl_json": build_retriever_workflow_dsl(unique_suffix),
  163. })
  164. response.raise_for_status()
  165. payload = response.json()
  166. return str(payload["id"])
  167. def create_app_version(client: httpx.Client, app_id: str, workflow_version_id: str) -> str:
  168. response = client.post(
  169. f"{WORKFLOW_SERVICE_URL}/apps/versions",
  170. json={
  171. "app_id": app_id,
  172. "workflow_version_id": workflow_version_id,
  173. "status": "active",
  174. })
  175. response.raise_for_status()
  176. payload = response.json()
  177. return str(payload["id"])
  178. def create_run(
  179. client: httpx.Client,
  180. app_id: str,
  181. app_version_id: str,
  182. workflow_id: str,
  183. workflow_version_id: str) -> str:
  184. response = client.post(
  185. f"{RUNTIME_SERVICE_URL}/runs",
  186. json={
  187. "app_id": app_id,
  188. "app_version_id": app_version_id,
  189. "workflow_id": workflow_id,
  190. "workflow_version_id": workflow_version_id,
  191. })
  192. response.raise_for_status()
  193. payload = response.json()
  194. return str(payload["run"]["id"])
  195. def execute_run(client: httpx.Client, run_id: str) -> None:
  196. response = client.post(
  197. f"{RUNTIME_SERVICE_URL}/runs/{run_id}/execute",
  198. json={"max_steps": 8})
  199. response.raise_for_status()
  200. def list_node_runs(client: httpx.Client, run_id: str) -> list[dict[str, object]]:
  201. response = client.get(
  202. f"{RUNTIME_SERVICE_URL}/node-runs",
  203. params={"run_id": run_id})
  204. response.raise_for_status()
  205. payload = response.json()
  206. if not isinstance(payload, list):
  207. raise AssertionError("node-runs response must be a list")
  208. return [item for item in payload if isinstance(item, dict)]
  209. def list_node_artifacts(client: httpx.Client, run_id: str) -> list[dict[str, object]]:
  210. response = client.get(
  211. f"{RUNTIME_SERVICE_URL}/node-artifacts",
  212. params={"run_id": run_id})
  213. response.raise_for_status()
  214. payload = response.json()
  215. if not isinstance(payload, list):
  216. raise AssertionError("node-artifacts response must be a list")
  217. return [item for item in payload if isinstance(item, dict)]
  218. def list_trace_spans(client: httpx.Client, run_id: str) -> list[dict[str, object]]:
  219. response = client.get(
  220. f"{RUNTIME_SERVICE_URL}/trace-spans",
  221. params={"run_id": run_id})
  222. response.raise_for_status()
  223. payload = response.json()
  224. if not isinstance(payload, list):
  225. raise AssertionError("trace-spans response must be a list")
  226. return [item for item in payload if isinstance(item, dict)]
  227. def build_workflow_dsl(unique_suffix: str, score: int) -> dict[str, object]:
  228. return {
  229. "code": f"smoke-flow-{unique_suffix}-{score}",
  230. "name": f"Smoke Flow {score}",
  231. "nodes": [
  232. {
  233. "id": "seed_state",
  234. "type": "assigner",
  235. "config": {
  236. "assignments": {
  237. "score": score,
  238. "user_name": "Alice",
  239. },
  240. },
  241. },
  242. {
  243. "id": "check_score",
  244. "type": "if-else",
  245. "config": {
  246. "expression": "state.score >= 5",
  247. },
  248. },
  249. {
  250. "id": "high_path",
  251. "type": "template-transform",
  252. "config": {
  253. "template": "{{state.user_name}} passed with score {{state.score}}",
  254. },
  255. },
  256. {
  257. "id": "low_path",
  258. "type": "template-transform",
  259. "config": {
  260. "template": "{{state.user_name}} did not pass; score {{state.score}}",
  261. },
  262. },
  263. ],
  264. "edges": [
  265. {"source": "seed_state", "target": "check_score"},
  266. {"source": "check_score", "target": "high_path", "condition": "true"},
  267. {"source": "check_score", "target": "low_path", "condition": "false"},
  268. ],
  269. }
  270. def build_retriever_workflow_dsl(unique_suffix: str) -> dict[str, object]:
  271. return {
  272. "code": f"smoke-retriever-{unique_suffix}",
  273. "name": "Smoke Retriever Flow",
  274. "nodes": [
  275. {
  276. "id": "seed_query",
  277. "type": "assigner",
  278. "config": {
  279. "assignments": {
  280. "query": "refund policy",
  281. },
  282. },
  283. },
  284. {
  285. "id": "retrieve_docs",
  286. "type": "knowledge-retrieval",
  287. "config": {
  288. "query_template": "{{state.query}}",
  289. "top_k": 1,
  290. "documents": [
  291. {
  292. "id": "shipping",
  293. "title": "Shipping Policy",
  294. "text": "Shipping usually takes three to five business days.",
  295. },
  296. {
  297. "id": "refund",
  298. "title": "Refund Policy",
  299. "text": "Refund policy allows returns within seven days after delivery.",
  300. },
  301. ],
  302. },
  303. },
  304. {
  305. "id": "render_answer",
  306. "type": "template-transform",
  307. "config": {
  308. "template": "Top doc: {{nodes.retrieve_docs.output.retrieved_documents.0.title}}",
  309. },
  310. },
  311. ],
  312. "edges": [
  313. {"source": "seed_query", "target": "retrieve_docs"},
  314. {"source": "retrieve_docs", "target": "render_answer"},
  315. ],
  316. }
  317. if __name__ == "__main__":
  318. try:
  319. raise SystemExit(main())
  320. except Exception as exc:
  321. print(f"smoke test failed: {exc}", file=sys.stderr)
  322. raise