Choose the runtime context object to pass into a function tool wrapper. Third-party wrappers may declare a narrower `RunContextWrapper` contract and then serialize that object downstream. In those cases, passing the richer `ToolContext` can leak runtime-only metadata such as agents or r
(
function_tool: FunctionTool,
context: ToolContext[Any],
)
| 1770 | |
| 1771 | |
| 1772 | def _get_function_tool_invoke_context( |
| 1773 | function_tool: FunctionTool, |
| 1774 | context: ToolContext[Any], |
| 1775 | ) -> ToolContext[Any] | RunContextWrapper[Any]: |
| 1776 | """Choose the runtime context object to pass into a function tool wrapper. |
| 1777 | |
| 1778 | Third-party wrappers may declare a narrower `RunContextWrapper` contract and then serialize |
| 1779 | that object downstream. In those cases, passing the richer `ToolContext` can leak runtime-only |
| 1780 | metadata such as agents or run config into incompatible serializers. When the wrapper |
| 1781 | explicitly declares `RunContextWrapper`, preserve only the base context state. |
| 1782 | """ |
| 1783 | try: |
| 1784 | parameters = tuple(inspect.signature(function_tool.on_invoke_tool).parameters.values()) |
| 1785 | except (TypeError, ValueError): |
| 1786 | return context |
| 1787 | |
| 1788 | if not parameters: |
| 1789 | return context |
| 1790 | |
| 1791 | context_annotation = parameters[0].annotation |
| 1792 | try: |
| 1793 | resolved_annotations = get_type_hints(function_tool.on_invoke_tool, include_extras=True) |
| 1794 | except Exception: |
| 1795 | pass |
| 1796 | else: |
| 1797 | context_annotation = resolved_annotations.get(parameters[0].name, context_annotation) |
| 1798 | |
| 1799 | if _annotation_mentions_context_type(context_annotation, context_type=ToolContext): |
| 1800 | return context |
| 1801 | if _annotation_mentions_context_type(context_annotation, context_type=RunContextWrapper): |
| 1802 | return context._fork_with_tool_input(context.tool_input) |
| 1803 | return context |
| 1804 | |
| 1805 | |
| 1806 | async def invoke_function_tool( |
no test coverage detected