callbacks
agent_cover.instrumentation.callbacks
Module for Langchain callback instrumentation.
Why Callbacks?
While tools and agents are instrumented via Direct Patching (wrapping methods),
Raw Strings (e.g., prompt = "You are a bot") present a unique challenge:
they are passive data, not active objects.
We cannot patch a string to notify us when it is used. Instead, we use Callbacks as an "Observation Post":
- The Choke Point: Every request to an LLM in LangChain goes through the Callback Manager.
- Payload Inspection: We intercept the
on_llm_startevent. - Pattern Matching: We scan the incoming prompt text against the regex patterns registered for raw strings.
This allows us to verify that a specific global string variable was actually rendered and sent to the LLM, even though we never "touched" the variable itself.
Classes
CoverageCallbackHandler
Bases: BaseCallbackHandler
A custom callback handler that integrates with AgentCover to track and analyze LLM and tool usage.
This handler acts as a bridge between the LangChain execution lifecycle and the AgentRegistry. It performs two main tasks:
- Raw String Detection: During
on_llm_start, it scans the prompt text to see if it matches any raw string patterns registered in the system. - Output Analysis: During
on_llm_endoron_chain_end, it captures the generated text and passes it to the OutputAnalyzer to verify if business decisions/rules are met.
Attributes:
| Name | Type | Description |
|---|---|---|
registry |
AgentRegistry
|
The registry instance used to track execution coverage. |
analyzer |
OutputAnalyzer
|
The component used to analyze LLM generations against configured decisions. |
Examples:
Manually using the handler without the global instrumentor:
from langchain_chat.chat_models import ChatOpenAI
from agent_cover.instrumentation.callbacks import CoverageCallbackHandler
# Create the handler
handler = CoverageCallbackHandler()
# Pass it to a LangChain model
llm = ChatOpenAI(callbacks=[handler])
llm.invoke("Hello world")
Source code in src/agent_cover/instrumentation/callbacks.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | |
Functions
__init__(registry=None, analyzer=None)
Initializes the CoverageCallbackHandler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
Optional[AgentRegistry]
|
An optional |
None
|
analyzer
|
Optional[OutputAnalyzer]
|
An optional |
None
|
Source code in src/agent_cover/instrumentation/callbacks.py
on_chain_end(outputs, **kwargs)
Handles the end of a chain execution.
Analyzes the final chain outputs. This is useful for agents that return structured dictionaries rather than just raw strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outputs
|
Dict[str, Any]
|
The final dictionary returned by the chain. |
required |
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
Source code in src/agent_cover/instrumentation/callbacks.py
on_chain_end_async(outputs, **kwargs)
async
Asynchronously handles the end of a chain execution.
Delegates logic to on_chain_end.
Source code in src/agent_cover/instrumentation/callbacks.py
on_chat_model_start(serialized, messages, **kwargs)
Handles the start of a chat model call.
Iterates through the list of message objects (e.g., HumanMessage, SystemMessage),
extracts their content, and performs raw string detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
serialized
|
Dict[str, Any]
|
Metadata about the chat model. |
required |
messages
|
List[List[Any]]
|
A list of lists, where each inner list contains LangChain message objects. |
required |
**kwargs
|
Any
|
Additional arguments. |
{}
|
Source code in src/agent_cover/instrumentation/callbacks.py
on_chat_model_start_async(serialized, messages, **kwargs)
async
Asynchronously handles the start of a chat model call.
Delegates logic to on_chat_model_start.
Source code in src/agent_cover/instrumentation/callbacks.py
on_llm_end(response, **kwargs)
Handles the end of an LLM call to analyze output quality.
Extracts the generated text from the response object and passes it to the
analyzer to check for Decision Coverage (e.g., "Did the agent output 'REFUND'?").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
Any
|
The |
required |
**kwargs
|
Any
|
Additional arguments. |
{}
|
Source code in src/agent_cover/instrumentation/callbacks.py
on_llm_end_async(response, **kwargs)
async
Asynchronously handles the end of an LLM call.
Delegates logic to on_llm_end.
Source code in src/agent_cover/instrumentation/callbacks.py
on_llm_start(serialized, prompts, **kwargs)
Handles the start of an LLM call to detect raw string usage.
It concatenates all input prompts into a single text block and checks if this block matches any regex patterns defined for "Raw String" prompts (variables tracked by scan_raw_string_prompts).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
serialized
|
Dict[str, Any]
|
A dictionary containing the serialized LLM call information. |
required |
prompts
|
List[str]
|
A list of string prompts passed to the LLM. |
required |
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
Source code in src/agent_cover/instrumentation/callbacks.py
on_llm_start_async(serialized, prompts, **kwargs)
async
Asynchronously handles the start of an LLM call.
Delegates logic to on_llm_start.
Source code in src/agent_cover/instrumentation/callbacks.py
on_tool_start(serialized, input_str, **kwargs)
Handles the start of a tool call.
Note
Currently, this method is a placeholder. Tool execution tracking is primarily handled by the ToolInstrumentor which patches the tool methods directly, rather than relying on callbacks.
Source code in src/agent_cover/instrumentation/callbacks.py
GlobalCallbackInstrumentor
Bases: BaseInstrumentor
Instrumentor that globally injects the CoverageCallbackHandler into LangChain.
This class performs monkey-patching on langchain_core.callbacks.manager.CallbackManager
and AsyncCallbackManager. It wraps their __init__ methods to automatically
append a CoverageCallbackHandler
to every new manager instance.
Attributes:
| Name | Type | Description |
|---|---|---|
registry |
AgentRegistry
|
The registry instance. |
handler_factory |
Callable
|
A factory function that returns a new handler instance. |
Methods:
| Name | Description |
|---|---|
instrument |
Applies the instrumentation to Langchain's callback managers. |
_patch_manager_init |
Internal method to patch the init of a manager class. |
Source code in src/agent_cover/instrumentation/callbacks.py
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | |
Functions
__init__(registry=None, patch_manager=None, handler_factory=None)
Initializes the instrumentor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
Optional[AgentRegistry]
|
The registry instance. |
None
|
patch_manager
|
Optional[PatchManager]
|
The patch manager instance to ensure safe patching. |
None
|
handler_factory
|
Optional[Callable]
|
Optional factory for dependency injection (testing).
If None, defaults to creating a real |
None
|
Source code in src/agent_cover/instrumentation/callbacks.py
instrument()
Applies the patches to LangChain's CallbackManagers.
If langchain_core is not installed, this method returns silently.