smoke_runtime_no_key.py 13 KB

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