16
16
import logging
17
17
from typing import Dict , Optional
18
18
19
- from fastapi import FastAPI
19
+ from fastapi import Depends , FastAPI
20
20
from pydantic import BaseModel , Field
21
21
22
22
from nemoguardrails .actions .action_dispatcher import ActionDispatcher
34
34
35
35
36
36
# Create action dispatcher object to communicate with actions
37
- app .action_dispatcher = ActionDispatcher (load_all_actions = True )
37
+ _action_dispatcher = ActionDispatcher (load_all_actions = True )
38
+
39
+
40
+ def get_action_dispatcher () -> ActionDispatcher :
41
+ """Dependency to provide the action dispatcher instance."""
42
+ return _action_dispatcher
38
43
39
44
40
45
class RequestBody (BaseModel ):
@@ -58,30 +63,36 @@ class ResponseBody(BaseModel):
58
63
summary = "Execute action" ,
59
64
response_model = ResponseBody ,
60
65
)
61
- async def run_action (body : RequestBody ):
66
+ async def run_action (
67
+ body : RequestBody ,
68
+ action_dispatcher : ActionDispatcher = Depends (get_action_dispatcher ),
69
+ ):
62
70
"""Execute the specified action and return the result.
63
71
64
72
Args:
65
73
body (RequestBody): The request body containing action_name and action_parameters.
74
+ action_dispatcher (ActionDispatcher): The action dispatcher dependency.
66
75
67
76
Returns:
68
77
dict: The response containing the execution status and result.
69
78
"""
70
79
71
- log .info (f "Request body: { body } " )
72
- result , status = await app . action_dispatcher .execute_action (
80
+ log .info ("Request body: %s" , body )
81
+ result , status = await action_dispatcher .execute_action (
73
82
body .action_name , body .action_parameters
74
83
)
75
84
resp = {"status" : status , "result" : result }
76
- log .info (f "Response: { resp } " )
85
+ log .info ("Response: %s" , resp )
77
86
return resp
78
87
79
88
80
89
@app .get (
81
90
"/v1/actions/list" ,
82
91
summary = "List available actions" ,
83
92
)
84
- async def get_actions_list ():
93
+ async def get_actions_list (
94
+ action_dispatcher : ActionDispatcher = Depends (get_action_dispatcher ),
95
+ ):
85
96
"""Returns the list of available actions."""
86
97
87
- return app . action_dispatcher .get_registered_actions ()
98
+ return action_dispatcher .get_registered_actions ()
0 commit comments