1616import logging
1717from typing import Dict , Optional
1818
19- from fastapi import FastAPI
19+ from fastapi import Depends , FastAPI
2020from pydantic import BaseModel , Field
2121
2222from nemoguardrails .actions .action_dispatcher import ActionDispatcher
3434
3535
3636# 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
3843
3944
4045class RequestBody (BaseModel ):
@@ -58,30 +63,36 @@ class ResponseBody(BaseModel):
5863 summary = "Execute action" ,
5964 response_model = ResponseBody ,
6065)
61- async def run_action (body : RequestBody ):
66+ async def run_action (
67+ body : RequestBody ,
68+ action_dispatcher : ActionDispatcher = Depends (get_action_dispatcher ),
69+ ):
6270 """Execute the specified action and return the result.
6371
6472 Args:
6573 body (RequestBody): The request body containing action_name and action_parameters.
74+ action_dispatcher (ActionDispatcher): The action dispatcher dependency.
6675
6776 Returns:
6877 dict: The response containing the execution status and result.
6978 """
7079
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 (
7382 body .action_name , body .action_parameters
7483 )
7584 resp = {"status" : status , "result" : result }
76- log .info (f "Response: { resp } " )
85+ log .info ("Response: %s" , resp )
7786 return resp
7887
7988
8089@app .get (
8190 "/v1/actions/list" ,
8291 summary = "List available actions" ,
8392)
84- async def get_actions_list ():
93+ async def get_actions_list (
94+ action_dispatcher : ActionDispatcher = Depends (get_action_dispatcher ),
95+ ):
8596 """Returns the list of available actions."""
8697
87- return app . action_dispatcher .get_registered_actions ()
98+ return action_dispatcher .get_registered_actions ()
0 commit comments