|
| 1 | +""" |
| 2 | +Escape curly braces in dynamic text so {xx} is not interpreted as a variable placeholder. |
| 3 | +
|
| 4 | +Used when embedding user/model content into templates that use {variable} substitution |
| 5 | +(e.g. ADK instruction inject_session_state). If the runtime is changed later, remove |
| 6 | +the decorator or calls and braces no longer need escaping. |
| 7 | +""" |
| 8 | + |
| 9 | +import functools |
| 10 | +import inspect |
| 11 | + |
| 12 | + |
| 13 | +def sanitize_braces(text: str) -> str: |
| 14 | + """Escape `{` and `}` in text so they are not treated as variable placeholders. |
| 15 | +
|
| 16 | + Use for any dynamic content (user input, model output, plan text, etc.) before |
| 17 | + inserting into a template that does {name} substitution. Empty/None returns as-is. |
| 18 | + """ |
| 19 | + if not text: |
| 20 | + return text |
| 21 | + return text.replace('\\', '\\\\').replace('{', '\\{').replace('}', '\\}') |
| 22 | + |
| 23 | + |
| 24 | +def with_sanitized_braces(*param_names: str): |
| 25 | + """Decorator: sanitize the listed string parameters before calling the function. |
| 26 | +
|
| 27 | + Use on functions that build instruction/template strings from dynamic args. |
| 28 | + If you stop using a runtime that interprets {var}, remove this decorator and |
| 29 | + no other logic changes are needed. |
| 30 | + """ |
| 31 | + param_set = set(param_names) |
| 32 | + |
| 33 | + def deco(f): |
| 34 | + sig = inspect.signature(f) |
| 35 | + |
| 36 | + @functools.wraps(f) |
| 37 | + def wrapper(*args, **kwargs): |
| 38 | + bound = sig.bind(*args, **kwargs) |
| 39 | + bound.apply_defaults() |
| 40 | + for name in param_set: |
| 41 | + if name in bound.arguments and isinstance(bound.arguments[name], str): |
| 42 | + bound.arguments[name] = sanitize_braces(bound.arguments[name]) |
| 43 | + args_list = [] |
| 44 | + kwargs_dict = {} |
| 45 | + for name in sig.parameters: |
| 46 | + p = sig.parameters[name] |
| 47 | + val = bound.arguments.get(name) |
| 48 | + if p.kind == inspect.Parameter.VAR_POSITIONAL: |
| 49 | + args_list.extend(val) |
| 50 | + elif p.kind == inspect.Parameter.VAR_KEYWORD: |
| 51 | + kwargs_dict.update(val) |
| 52 | + elif p.kind in ( |
| 53 | + inspect.Parameter.POSITIONAL_ONLY, |
| 54 | + inspect.Parameter.POSITIONAL_OR_KEYWORD, |
| 55 | + ): |
| 56 | + args_list.append(val) |
| 57 | + else: |
| 58 | + kwargs_dict[name] = val |
| 59 | + return f(*args_list, **kwargs_dict) |
| 60 | + |
| 61 | + return wrapper |
| 62 | + |
| 63 | + return deco |
0 commit comments