@@ -292,6 +292,7 @@ class WeatherArgs(BaseModel):
292292 "_cached_parameters" ,
293293 "_input_schema" ,
294294 "_schema_supplied" ,
295+ "_invoke_sync_on_event_loop" ,
295296 }
296297
297298 def __init__ (
@@ -366,6 +367,7 @@ def __init__(
366367 self .description = description
367368 self .kind = kind
368369 self .additional_properties = additional_properties
370+ self ._invoke_sync_on_event_loop = False
369371 for key , value in kwargs .items ():
370372 setattr (self , key , value )
371373
@@ -537,6 +539,16 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any:
537539 self .invocation_exception_count += 1
538540 raise
539541
542+ async def _invoke_function (self , call_kwargs : Mapping [str , Any ]) -> Any :
543+ """Run sync tools off the event loop during async invocation."""
544+ func = self .func .func if isinstance (self .func , FunctionTool ) else self .func
545+ if inspect .iscoroutinefunction (func ) or getattr (self , "_invoke_sync_on_event_loop" , False ):
546+ res = self .__call__ (** call_kwargs )
547+ return await res if inspect .isawaitable (res ) else res
548+
549+ res = await asyncio .to_thread (self .__call__ , ** call_kwargs )
550+ return await res if inspect .isawaitable (res ) else res
551+
540552 @overload
541553 async def invoke (
542554 self ,
@@ -679,8 +691,7 @@ async def invoke(
679691 if not OBSERVABILITY_SETTINGS .ENABLED : # type: ignore[name-defined]
680692 logger .info (f"Function name: { self .name } " )
681693 logger .debug (f"Function arguments: { observable_kwargs } " )
682- res = self .__call__ (** call_kwargs )
683- result = await res if inspect .isawaitable (res ) else res
694+ result = await self ._invoke_function (call_kwargs )
684695 if skip_parsing :
685696 logger .info (f"Function { self .name } succeeded." )
686697 logger .debug (f"Function result: { type (result ).__name__ } " )
@@ -730,8 +741,7 @@ async def invoke(
730741 start_time_stamp = perf_counter ()
731742 end_time_stamp : float | None = None
732743 try :
733- res = self .__call__ (** call_kwargs )
734- result = await res if inspect .isawaitable (res ) else res
744+ result = await self ._invoke_function (call_kwargs )
735745 end_time_stamp = perf_counter ()
736746 except Exception as exception :
737747 end_time_stamp = perf_counter ()
0 commit comments