|
| 1 | +"""Optional Pydantic AI Harness capability instrumentation.""" |
| 2 | + |
| 3 | +import sys |
| 4 | +from contextvars import ContextVar |
| 5 | + |
| 6 | +from braintrust.integrations.base import CompositeFunctionWrapperPatcher, FunctionWrapperPatcher |
| 7 | +from braintrust.logger import Span |
| 8 | +from braintrust.span_types import SpanTypeAttribute |
| 9 | + |
| 10 | +from .tracing import start_span |
| 11 | + |
| 12 | + |
| 13 | +async def _compact_messages(wrapped, _instance, args, kwargs): |
| 14 | + messages = kwargs["messages"] |
| 15 | + before = len(messages) |
| 16 | + compacted = await wrapped(*args, **kwargs) |
| 17 | + # Harness returns the original list when compaction leaves the history unchanged. |
| 18 | + if compacted is not messages: |
| 19 | + metadata = {"strategy": kwargs["strategy"]} |
| 20 | + if kwargs.get("model_requested"): |
| 21 | + metadata["model_requested"] = True |
| 22 | + if kwargs.get("background") is not None: |
| 23 | + metadata["background"] = kwargs["background"] |
| 24 | + start_span( |
| 25 | + name="compact_messages", |
| 26 | + type=SpanTypeAttribute.TASK, |
| 27 | + input={"messages": before}, |
| 28 | + output={"messages": len(compacted)}, |
| 29 | + metadata=metadata, |
| 30 | + ).end() |
| 31 | + return compacted |
| 32 | + |
| 33 | + |
| 34 | +def _record_memory_injection(wrapped, instance, args, kwargs): |
| 35 | + result = wrapped(*args, **kwargs) |
| 36 | + _, main, subfiles, files_truncated, snapshot, appended, withheld = args |
| 37 | + main_chars = len(main.content) if main is not None else 0 |
| 38 | + has_memory = bool(main_chars or subfiles or files_truncated) |
| 39 | + start_span( |
| 40 | + name="memory.inject", |
| 41 | + type=SpanTypeAttribute.TASK, |
| 42 | + input={"main_chars": main_chars, "files": len(subfiles)}, |
| 43 | + output={ |
| 44 | + "appended": appended is not None, |
| 45 | + "injected_chars": len(appended or ""), |
| 46 | + "outcome": "budget_exhausted" if snapshot is None and has_memory else "ok", |
| 47 | + }, |
| 48 | + metadata={ |
| 49 | + "files_truncated": files_truncated, |
| 50 | + "main_truncated": main is not None and main.truncated, |
| 51 | + **({"main_withheld": withheld} if instance.scanner is not None else {}), |
| 52 | + }, |
| 53 | + ).end() |
| 54 | + return result |
| 55 | + |
| 56 | + |
| 57 | +def _trace_guardrail_block(wrapped, _instance, args, kwargs): |
| 58 | + result = wrapped(*args, **kwargs) |
| 59 | + direction = kwargs["direction"] |
| 60 | + tool_name = kwargs.get("tool_name") |
| 61 | + start_span( |
| 62 | + name=f"guardrail blocked {direction}", |
| 63 | + type=SpanTypeAttribute.TASK, |
| 64 | + input={"direction": direction}, |
| 65 | + output={"action": "block", "reason": kwargs["message"]}, |
| 66 | + metadata={"tool_name": tool_name} if tool_name is not None else None, |
| 67 | + ).end() |
| 68 | + return result |
| 69 | + |
| 70 | + |
| 71 | +_router_span = ContextVar[Span | None]("pydantic_ai_harness_router_span", default=None) |
| 72 | + |
| 73 | + |
| 74 | +async def _select_model(wrapped, instance, args, kwargs): |
| 75 | + # Bootstrap and cached lookups do not make a routing decision. |
| 76 | + if instance._run_ctx is None or (instance.mode == "once" and instance._cached_choice is not None): |
| 77 | + return await wrapped(*args, **kwargs) |
| 78 | + with start_span( |
| 79 | + name="model_router.select", |
| 80 | + type=SpanTypeAttribute.TASK, |
| 81 | + input={"choices": list(instance.choices), "default": instance.default}, |
| 82 | + ) as span: |
| 83 | + token = _router_span.set(span) |
| 84 | + try: |
| 85 | + return await wrapped(*args, **kwargs) |
| 86 | + finally: |
| 87 | + _router_span.reset(token) |
| 88 | + |
| 89 | + |
| 90 | +def _record_model_selection(wrapped, _instance, args, kwargs): |
| 91 | + result = wrapped(*args, **kwargs) |
| 92 | + span = _router_span.get() |
| 93 | + if span is not None: |
| 94 | + _, attributes, choice, fallback_reason = args |
| 95 | + prefix = "model_router." |
| 96 | + span.log( |
| 97 | + output={"choice": choice, "fallback_reason": fallback_reason}, |
| 98 | + metadata={key.removeprefix(prefix): value for key, value in attributes.items() if key.startswith(prefix)}, |
| 99 | + ) |
| 100 | + return result |
| 101 | + |
| 102 | + |
| 103 | +class _HarnessPatcher(FunctionWrapperPatcher): |
| 104 | + version_spec = ">=2.75" |
| 105 | + |
| 106 | + |
| 107 | +class _SharedHarnessFunctionPatcher(_HarnessPatcher): |
| 108 | + @classmethod |
| 109 | + def patch(cls, module, version, *, target=None): |
| 110 | + root = cls.resolve_root(module, version, target=target) |
| 111 | + original = cls.resolve_target(module, version, target=target) |
| 112 | + if not super().patch(module, version, target=target): |
| 113 | + return False |
| 114 | + wrapped = cls.resolve_target(module, version, target=target) |
| 115 | + # Harness imports these helpers by name while initializing their feature packages. |
| 116 | + prefix = root.__package__ + "." |
| 117 | + for name, imported in sys.modules.copy().items(): |
| 118 | + if name.startswith(prefix) and getattr(imported, cls.target_path, None) is original: |
| 119 | + setattr(imported, cls.target_path, wrapped) |
| 120 | + return True |
| 121 | + |
| 122 | + |
| 123 | +class HarnessCompactionPatcher(_SharedHarnessFunctionPatcher): |
| 124 | + name = "pydantic_ai.harness.compaction" |
| 125 | + target_module = "pydantic_ai_harness.compaction._shared" |
| 126 | + target_path = "compact_with_span" |
| 127 | + wrapper = _compact_messages |
| 128 | + |
| 129 | + |
| 130 | +class HarnessMemoryInjectionPatcher(_HarnessPatcher): |
| 131 | + name = "pydantic_ai.harness.memory_injection" |
| 132 | + target_module = "pydantic_ai_harness.memory._capability" |
| 133 | + target_path = "Memory._record_injection" |
| 134 | + wrapper = _record_memory_injection |
| 135 | + |
| 136 | + |
| 137 | +class HarnessGuardrailBlockPatcher(_SharedHarnessFunctionPatcher): |
| 138 | + name = "pydantic_ai.harness.guardrail_block" |
| 139 | + target_module = "pydantic_ai_harness.guardrails._shared" |
| 140 | + target_path = "trace_block" |
| 141 | + wrapper = _trace_guardrail_block |
| 142 | + |
| 143 | + |
| 144 | +class _HarnessModelRouterSelectPatcher(_HarnessPatcher): |
| 145 | + name = "pydantic_ai.harness.model_router.select" |
| 146 | + target_module = "pydantic_ai_harness.model_router._capability" |
| 147 | + target_path = "ModelRouter._select_model" |
| 148 | + wrapper = _select_model |
| 149 | + |
| 150 | + |
| 151 | +class _HarnessModelRouterRecordPatcher(_HarnessPatcher): |
| 152 | + name = "pydantic_ai.harness.model_router.record" |
| 153 | + target_module = "pydantic_ai_harness.model_router._capability" |
| 154 | + target_path = "_record" |
| 155 | + wrapper = _record_model_selection |
| 156 | + |
| 157 | + |
| 158 | +class HarnessModelRouterPatcher(CompositeFunctionWrapperPatcher): |
| 159 | + name = "pydantic_ai.harness.model_router" |
| 160 | + sub_patchers = (_HarnessModelRouterSelectPatcher, _HarnessModelRouterRecordPatcher) |
| 161 | + |
| 162 | + @classmethod |
| 163 | + def applies(cls, module, version, *, target=None): |
| 164 | + return all(patcher.applies(module, version, target=target) for patcher in cls.sub_patchers) |
0 commit comments