Principle:Wandb Weave Auto Patching
| Knowledge Sources | |
|---|---|
| Domains | Instrumentation, Monkey_Patching |
| Last Updated | 2026-02-14 00:00 GMT |
Overview
An automatic instrumentation mechanism that transparently wraps third-party library methods at import time to capture execution data.
Description
Auto Patching uses two complementary strategies to instrument LLM provider SDKs without user intervention: (1) implicit patching scans already-imported modules and wraps their methods immediately, and (2) an import hook intercepts future module imports via Python's sys.meta_path mechanism to wrap methods as they become available.
This pattern enables zero-configuration tracing of 25+ LLM providers (OpenAI, Anthropic, Mistral, Cohere, etc.) when weave.init() is called.
Usage
This principle activates automatically when weave.init() is called. No explicit user action is required. For fine-grained control, users can call provider-specific patch_*() functions with custom settings.
Theoretical Basis
Auto-patching relies on two Python runtime mechanisms:
- Module Introspection (implicit_patch): After initialization, scan sys.modules for known integration module names. If found, invoke the corresponding patch function.
- Import Hooks (register_import_hook): Install a MetaPathFinder at sys.meta_path[0] that intercepts module imports. When a known integration module is loaded, wrap it with a PatchingLoader that applies patches after the module is fully initialized.
The combination ensures that both pre-imported and post-imported libraries are instrumented.