Datasets:
Download src/instrumentation.py from tesraghavan/agent-trace: direct link, hf CLI and curl.
- Browser
- Download file 6.15 kB
-
https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/src/instrumentation.py
- Command line
-
hf download hf://datasets/tesraghavan/agent-trace/src/instrumentation.py
-
curl -L -o instrumentation.py https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/src/instrumentation.py
6.15 kB
| """Instrumentation for capturing tool execution telemetry.""" | |
| import platform | |
| import resource | |
| import time | |
| import uuid | |
| from typing import Any | |
| from smolagents import Tool | |
| from smolagents.models import ChatMessage | |
| from .tracing import Span, Telemetry, TraceCollector | |
| def _rusage_delta(before: resource.struct_rusage, after: resource.struct_rusage) -> dict: | |
| """Raw delta between two rusage snapshots.""" | |
| return { | |
| "user_time_s": after.ru_utime - before.ru_utime, | |
| "system_time_s": after.ru_stime - before.ru_stime, | |
| "max_rss": after.ru_maxrss, # not a delta — peak value | |
| "read_blocks": after.ru_inblock - before.ru_inblock, | |
| "write_blocks": after.ru_oublock - before.ru_oublock, | |
| } | |
| def get_rusage_delta( | |
| children_before: resource.struct_rusage, | |
| children_after: resource.struct_rusage, | |
| self_before: resource.struct_rusage, | |
| self_after: resource.struct_rusage, | |
| ) -> Telemetry: | |
| """Combine RUSAGE_CHILDREN (subprocess) and RUSAGE_SELF (in-process) deltas. | |
| For BashTool: CHILDREN has the subprocess data, SELF is near-zero. | |
| For PythonInterpreterTool: CHILDREN is zero, SELF has the in-process data. | |
| Summing both gives correct telemetry for either tool type. | |
| """ | |
| children = _rusage_delta(children_before, children_after) | |
| self = _rusage_delta(self_before, self_after) | |
| # Note: ru_maxrss is in bytes on macOS, kilobytes on Linux | |
| max_rss = max(children["max_rss"], self["max_rss"]) | |
| if platform.system() == "Linux": | |
| max_rss *= 1024 | |
| return Telemetry( | |
| user_time_s=children["user_time_s"] + self["user_time_s"], | |
| system_time_s=children["system_time_s"] + self["system_time_s"], | |
| max_rss_bytes=max_rss, | |
| read_bytes=(children["read_blocks"] + self["read_blocks"]) * 512, | |
| write_bytes=(children["write_blocks"] + self["write_blocks"]) * 512, | |
| ) | |
| def _format_input(args: tuple, kwargs: dict) -> str: | |
| """Format tool input as string for logging.""" | |
| parts = [] | |
| if args: | |
| parts.append(f"args={args}") | |
| if kwargs: | |
| parts.append(f"kwargs={kwargs}") | |
| return ", ".join(parts) if parts else "(no input)" | |
| def instrument_tool(tool: Tool, collector: TraceCollector) -> Tool: | |
| """ | |
| Instrument a tool by patching its forward method to capture telemetry. | |
| The tool remains a proper Tool instance (passes isinstance checks). | |
| Saves the original forward as _original_forward so it can be re-instrumented | |
| with a different collector. | |
| """ | |
| # Unwrap if already instrumented | |
| if hasattr(tool, '_original_forward'): | |
| original_forward = tool._original_forward | |
| else: | |
| original_forward = tool.forward | |
| tool._original_forward = original_forward | |
| def instrumented_forward(*args, **kwargs) -> Any: | |
| # Capture input for the span | |
| tool_input = _format_input(args, kwargs) | |
| # Timing and resource measurement (both subprocess and in-process) | |
| children_before = resource.getrusage(resource.RUSAGE_CHILDREN) | |
| self_before = resource.getrusage(resource.RUSAGE_SELF) | |
| start_ns = time.perf_counter_ns() | |
| result = None | |
| exit_code = 0 | |
| try: | |
| result = original_forward(*args, **kwargs) | |
| # Parse exit_code from BashTool output (returns it in text, never raises) | |
| if isinstance(result, str) and result.startswith("exit_code: "): | |
| try: | |
| exit_code = int(result.split("\n")[0].split(": ")[1]) | |
| except (IndexError, ValueError): | |
| pass | |
| except Exception as e: | |
| result = f"Error: {e}" | |
| exit_code = 1 | |
| raise # Re-raise so caller sees the error | |
| finally: | |
| end_ns = time.perf_counter_ns() | |
| children_after = resource.getrusage(resource.RUSAGE_CHILDREN) | |
| self_after = resource.getrusage(resource.RUSAGE_SELF) | |
| # Build and record span | |
| telemetry = get_rusage_delta( | |
| children_before, children_after, | |
| self_before, self_after, | |
| ) | |
| duration_ms = (end_ns - start_ns) / 1_000_000 | |
| span = Span( | |
| span_id=str(uuid.uuid4()), | |
| type="TOOL", | |
| tool_name=tool.name, | |
| tool_input=tool_input, | |
| tool_output=str(result)[:10000], # Cap output size | |
| start_ns=start_ns, | |
| end_ns=end_ns, | |
| duration_ms=duration_ms, | |
| telemetry=telemetry, | |
| exit_code=exit_code, | |
| ) | |
| collector.record_span(span) | |
| return result | |
| # Patch the forward method | |
| tool.forward = instrumented_forward | |
| return tool | |
| def instrument_tools(tools: list[Tool], collector: TraceCollector) -> list[Tool]: | |
| """Instrument a list of tools to capture telemetry.""" | |
| return [instrument_tool(tool, collector) for tool in tools] | |
| def instrument_model(model, collector: TraceCollector): | |
| """Patch model.generate() to capture reasoning_content from the live response. | |
| The OpenAI SDK preserves reasoning_content in pydantic_extra, but smolagents | |
| serializes the ChatMessage.raw via asdict() which drops it. We intercept | |
| the ChatMessage before serialization and stash reasoning per step. | |
| """ | |
| import types | |
| if hasattr(model, '_original_generate'): | |
| original_generate = model._original_generate | |
| else: | |
| original_generate = model.generate | |
| model._original_generate = original_generate | |
| def patched_generate(self, *args, **kwargs) -> ChatMessage: | |
| result = original_generate(*args, **kwargs) | |
| # Extract reasoning_content from the live Pydantic response object | |
| reasoning = None | |
| if result.raw and hasattr(result.raw, 'choices') and result.raw.choices: | |
| msg = result.raw.choices[0].message | |
| reasoning = getattr(msg, 'reasoning_content', None) | |
| if reasoning: | |
| collector.record_reasoning(reasoning) | |
| return result | |
| model.generate = types.MethodType(patched_generate, model) | |
| return model | |