Coverage for app / services / skill_runs / steps.py: 90%

68 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2What each node of a skill run did, read off svc-ai's execution trace. 

3 

4svc-ai answers a batch run with ``messages`` — every message the graph 

5produced, in order — and ``context``, which carries each skill node's result 

6under ``<node_id>_output``. A node's final message is named after the node; 

7the tool-call messages it made on the way there are not, so they are held 

8until the named message that closes them arrives. 

9 

10The result is a list of steps, one per node execution, which is what the run 

11page draws as a timeline: which node ran, what it said (or returned, for a 

12structured worker), the tools it called and what it cost. 

13""" 

14 

15from __future__ import annotations 

16 

17import json 

18from typing import Any 

19 

20from app.services.ai_client import TOOL_OUTPUT_CHARS 

21 

22#: Characters of a node's answer kept on the step. The final answer and the 

23#: structured outputs are stored whole; a step is there to show the work. 

24STEP_OUTPUT_CHARS = 6000 

25 

26 

27def _is_system(node_id: str) -> bool: 

28 """svc-ai's pipeline nodes (``__gate__``, ``__synthesis__`` …).""" 

29 return node_id.startswith("__") and node_id.endswith("__") 

30 

31 

32def _text(content: Any) -> str: 

33 if isinstance(content, str): 

34 return content 

35 if isinstance(content, list): 

36 # Anthropic-style content blocks. 

37 return "".join( 

38 str(block.get("text", "")) if isinstance(block, dict) else str(block) 

39 for block in content 

40 ) 

41 return json.dumps(content, ensure_ascii=False, default=str) 

42 

43 

44def _tokens(message: dict[str, Any]) -> tuple[int, int]: 

45 usage = message.get("usage_metadata") 

46 if not isinstance(usage, dict): 

47 return 0, 0 

48 return int(usage.get("input_tokens") or 0), int(usage.get("output_tokens") or 0) 

49 

50 

51def _structured(value: Any) -> dict[str, Any] | None: 

52 if isinstance(value, dict): 

53 return value 

54 return None 

55 

56 

57def steps_from_trace(messages: Any, context: dict[str, Any] | None) -> list[dict]: 

58 """One step per node execution, in the order the nodes ran.""" 

59 context = context or {} 

60 steps: list[dict[str, Any]] = [] 

61 pending_calls: list[dict[str, Any]] = [] 

62 pending_in = pending_out = 0 

63 calls_by_id: dict[str, dict[str, Any]] = {} 

64 

65 for message in messages if isinstance(messages, list) else []: 

66 if not isinstance(message, dict): 

67 continue 

68 kind = message.get("type") 

69 if kind == "tool": 

70 call = calls_by_id.get(str(message.get("tool_call_id") or "")) 

71 if call is not None: 

72 call["output"] = _text(message.get("content"))[:TOOL_OUTPUT_CHARS] 

73 if message.get("status") == "error": 

74 call["error"] = True 

75 continue 

76 if kind != "ai": 

77 continue 

78 

79 tokens_in, tokens_out = _tokens(message) 

80 pending_in += tokens_in 

81 pending_out += tokens_out 

82 for raw in message.get("tool_calls") or []: 

83 if not isinstance(raw, dict) or not raw.get("name"): 

84 continue 

85 call = { 

86 "name": str(raw["name"]), 

87 "args": raw.get("args") if isinstance(raw.get("args"), dict) else {}, 

88 "output": None, 

89 } 

90 pending_calls.append(call) 

91 if raw.get("id"): 

92 calls_by_id[str(raw["id"])] = call 

93 

94 node_id = message.get("name") 

95 if not node_id: 

96 continue 

97 node_id = str(node_id) 

98 text = _text(message.get("content")) 

99 steps.append( 

100 { 

101 "node_id": node_id, 

102 "kind": "system" if _is_system(node_id) else "skill", 

103 "output": text[:STEP_OUTPUT_CHARS], 

104 "truncated": len(text) > STEP_OUTPUT_CHARS, 

105 "structured": None, 

106 "error": text.startswith(f"Error in {node_id}:"), 

107 "tool_calls": pending_calls, 

108 "input_tokens": pending_in, 

109 "output_tokens": pending_out, 

110 } 

111 ) 

112 pending_calls = [] 

113 pending_in = pending_out = 0 

114 

115 if pending_calls and steps: 

116 # Tool calls with no named message after them — a node that ended on 

117 # an error. They belong to the work, so keep them on the last step. 

118 steps[-1]["tool_calls"].extend(pending_calls) 

119 

120 # A structured worker's return value, on its last execution — the 

121 # context holds one per node, so an earlier pass of a loop has none. 

122 seen: set[str] = set() 

123 for step in reversed(steps): 

124 node_id = step["node_id"] 

125 if step["kind"] == "skill" and node_id not in seen: 

126 seen.add(node_id) 

127 step["structured"] = _structured(context.get(f"{node_id}_output")) 

128 return steps