Find the parameter name that has a Context type annotation. This function inspects the signature of a callable and returns the name of the first parameter that is annotated with Context or a type alias of Context (e.g., ToolContext, CallbackContext). Args: func: The callable to inspect
(func: Callable[..., Any])
| 65 | |
| 66 | @functools.lru_cache(maxsize=1024) |
| 67 | def find_context_parameter(func: Callable[..., Any]) -> str | None: |
| 68 | """Find the parameter name that has a Context type annotation. |
| 69 | |
| 70 | This function inspects the signature of a callable and returns the name |
| 71 | of the first parameter that is annotated with Context or a type alias of |
| 72 | Context (e.g., ToolContext, CallbackContext). |
| 73 | |
| 74 | Args: |
| 75 | func: The callable to inspect. |
| 76 | |
| 77 | Returns: |
| 78 | The parameter name if found, None otherwise. |
| 79 | """ |
| 80 | if func is None: |
| 81 | return None |
| 82 | try: |
| 83 | signature = inspect.signature(func) |
| 84 | except (ValueError, TypeError): |
| 85 | return None |
| 86 | # Resolve string annotations (e.g., 'Context') |
| 87 | try: |
| 88 | type_hints = typing.get_type_hints(func) |
| 89 | except Exception: |
| 90 | # get_type_hints can fail for various reasons (e.g., unresolvable forward |
| 91 | # references). In such cases, we fall back to inspecting the parameter |
| 92 | # annotations directly. |
| 93 | type_hints = {} |
| 94 | |
| 95 | for name, param in signature.parameters.items(): |
| 96 | annotation = type_hints.get(name, param.annotation) |
| 97 | if _is_context_type(annotation): |
| 98 | return name |
| 99 | return None |