Invoke a function tool, enforcing timeout configuration when provided.
(
*,
function_tool: FunctionTool,
context: ToolContext[Any],
arguments: str,
)
| 1804 | |
| 1805 | |
| 1806 | async def invoke_function_tool( |
| 1807 | *, |
| 1808 | function_tool: FunctionTool, |
| 1809 | context: ToolContext[Any], |
| 1810 | arguments: str, |
| 1811 | ) -> Any: |
| 1812 | """Invoke a function tool, enforcing timeout configuration when provided.""" |
| 1813 | invoke_context = _get_function_tool_invoke_context(function_tool, context) |
| 1814 | timeout_seconds = function_tool.timeout_seconds |
| 1815 | if timeout_seconds is None: |
| 1816 | return await function_tool.on_invoke_tool(cast(Any, invoke_context), arguments) |
| 1817 | |
| 1818 | tool_task: asyncio.Future[Any] = asyncio.ensure_future( |
| 1819 | function_tool.on_invoke_tool(cast(Any, invoke_context), arguments) |
| 1820 | ) |
| 1821 | try: |
| 1822 | return await asyncio.wait_for(tool_task, timeout=timeout_seconds) |
| 1823 | except asyncio.TimeoutError as exc: |
| 1824 | if tool_task.done() and not tool_task.cancelled(): |
| 1825 | tool_exception = tool_task.exception() |
| 1826 | if tool_exception is None: |
| 1827 | return tool_task.result() |
| 1828 | raise tool_exception from None |
| 1829 | |
| 1830 | timeout_error = ToolTimeoutError( |
| 1831 | tool_name=function_tool.name, |
| 1832 | timeout_seconds=timeout_seconds, |
| 1833 | ) |
| 1834 | if function_tool.timeout_behavior == "raise_exception": |
| 1835 | raise timeout_error from exc |
| 1836 | |
| 1837 | timeout_error_function = function_tool.timeout_error_function |
| 1838 | if timeout_error_function is None: |
| 1839 | return default_tool_timeout_error_message( |
| 1840 | tool_name=function_tool.name, |
| 1841 | timeout_seconds=timeout_seconds, |
| 1842 | ) |
| 1843 | |
| 1844 | timeout_result = timeout_error_function(context, timeout_error) |
| 1845 | if inspect.isawaitable(timeout_result): |
| 1846 | return await timeout_result |
| 1847 | return timeout_result |
| 1848 | |
| 1849 | |
| 1850 | @overload |