1
1
import instructor
2
2
from pydantic import BaseModel , Field
3
- from typing import Optional , Type , Generator , AsyncGenerator , get_args , Dict , List , Callable , Any
3
+ from typing import Optional , Type , Generator , AsyncGenerator , get_args , Dict , List , Callable
4
4
import logging
5
5
from atomic_agents .context .chat_history import ChatHistory
6
6
from atomic_agents .context .system_prompt_generator import (
@@ -98,13 +98,13 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
98
98
Hook System:
99
99
The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring
100
100
and error handling capabilities. Supported events include:
101
-
101
+
102
102
- 'parse:error': Triggered when Pydantic validation fails
103
- - 'completion:kwargs': Triggered before completion request
103
+ - 'completion:kwargs': Triggered before completion request
104
104
- 'completion:response': Triggered after completion response
105
105
- 'completion:error': Triggered on completion errors
106
106
- 'completion:last_attempt': Triggered on final retry attempt
107
-
107
+
108
108
Hook Methods:
109
109
- register_hook(event, handler): Register a hook handler for an event
110
110
- unregister_hook(event, handler): Remove a hook handler
@@ -116,14 +116,14 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
116
116
```python
117
117
# Basic usage
118
118
agent = AtomicAgent[InputSchema, OutputSchema](config)
119
-
119
+
120
120
# Register parse error hook for intelligent retry handling
121
121
def handle_parse_error(error):
122
122
print(f"Validation failed: {error}")
123
123
# Implement custom retry logic, logging, etc.
124
-
124
+
125
125
agent.register_hook("parse:error", handle_parse_error)
126
-
126
+
127
127
# Now parse:error hooks will fire on validation failures
128
128
response = agent.run(user_input)
129
129
```
@@ -144,7 +144,7 @@ def __init__(self, config: AgentConfig):
144
144
self .initial_history = self .history .copy ()
145
145
self .current_user_input = None
146
146
self .model_api_parameters = config .model_api_parameters or {}
147
-
147
+
148
148
# Hook management attributes
149
149
self ._hook_handlers : Dict [str , List [Callable ]] = {}
150
150
self ._hooks_enabled : bool = True
@@ -361,65 +361,65 @@ def unregister_context_provider(self, provider_name: str):
361
361
def register_hook (self , event : str , handler : Callable ) -> None :
362
362
"""
363
363
Registers a hook handler for a specific event.
364
-
364
+
365
365
Args:
366
366
event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)
367
367
handler (Callable): The callback function to handle the event
368
368
"""
369
369
if event not in self ._hook_handlers :
370
370
self ._hook_handlers [event ] = []
371
371
self ._hook_handlers [event ].append (handler )
372
-
372
+
373
373
# Register with instructor client if it supports hooks
374
- if hasattr (self .client , 'on' ):
374
+ if hasattr (self .client , "on" ):
375
375
self .client .on (event , handler )
376
376
377
377
def unregister_hook (self , event : str , handler : Callable ) -> None :
378
378
"""
379
379
Unregisters a hook handler for a specific event.
380
-
380
+
381
381
Args:
382
382
event (str): The event name
383
383
handler (Callable): The callback function to remove
384
384
"""
385
385
if event in self ._hook_handlers and handler in self ._hook_handlers [event ]:
386
386
self ._hook_handlers [event ].remove (handler )
387
-
387
+
388
388
# Remove from instructor client if it supports hooks
389
- if hasattr (self .client , ' off' ):
389
+ if hasattr (self .client , " off" ):
390
390
self .client .off (event , handler )
391
391
392
392
def clear_hooks (self , event : Optional [str ] = None ) -> None :
393
393
"""
394
394
Clears hook handlers for a specific event or all events.
395
-
395
+
396
396
Args:
397
397
event (Optional[str]): The event name to clear, or None to clear all
398
398
"""
399
399
if event :
400
400
if event in self ._hook_handlers :
401
401
# Clear from instructor client first
402
- if hasattr (self .client , ' clear' ):
402
+ if hasattr (self .client , " clear" ):
403
403
self .client .clear (event )
404
404
self ._hook_handlers [event ].clear ()
405
405
else :
406
406
# Clear all hooks
407
- if hasattr (self .client , ' clear' ):
407
+ if hasattr (self .client , " clear" ):
408
408
self .client .clear ()
409
409
self ._hook_handlers .clear ()
410
410
411
411
def _dispatch_hook (self , event : str , * args , ** kwargs ) -> None :
412
412
"""
413
413
Internal method to dispatch hook events with error isolation.
414
-
414
+
415
415
Args:
416
416
event (str): The event name
417
417
*args: Arguments to pass to handlers
418
418
**kwargs: Keyword arguments to pass to handlers
419
419
"""
420
420
if not self ._hooks_enabled or event not in self ._hook_handlers :
421
421
return
422
-
422
+
423
423
for handler in self ._hook_handlers [event ]:
424
424
try :
425
425
handler (* args , ** kwargs )
0 commit comments