{"record":{"id":"40e2cb79c4feeffa","repo":"BerriAI/litellm","slug":"syntax-error-in-custom-code-e","errorCode":null,"errorMessage":"Syntax error in custom code: {e}","messagePattern":"Syntax error in custom code: (.+?)","errorType":"exception","errorClass":"CustomCodeCompilationError","httpStatus":null,"severity":"error","filePath":"litellm/proxy/guardrails/guardrail_hooks/custom_code/custom_code_guardrail.py","lineNumber":183,"sourceCode":"        self._compiled_function = apply_fn\n\n    def _compile_custom_code(self) -> None:\n        \"\"\"\n        Compile the custom code and extract the apply_guardrail function.\n\n        The code runs in a sandboxed environment with only the allowed primitives.\n        \"\"\"\n        with self._compile_lock:\n            if self._compiled_function is not None:\n                return\n\n            try:\n                self._do_compile()\n                verbose_proxy_logger.debug(\"Custom code guardrail '%s' compiled successfully\", self.guardrail_name)\n\n            except SyntaxError as e:\n                self._compile_error = f\"Syntax error in custom code: {e}\"\n                raise CustomCodeCompilationError(self._compile_error) from e\n            except CustomCodeCompilationError:\n                raise\n            except Exception as e:\n                self._compile_error = f\"Failed to compile custom code: {e}\"\n                raise CustomCodeCompilationError(self._compile_error) from e\n\n    @log_guardrail_information\n    async def apply_guardrail(\n        self,\n        inputs: GenericGuardrailAPIInputs,\n        request_data: dict,\n        input_type: Literal[\"request\", \"response\"],\n        logging_obj: Optional[\"LiteLLMLoggingObj\"] = None,\n    ) -> GenericGuardrailAPIInputs:\n        \"\"\"\n        Apply the custom code guardrail to the inputs.\n\n        This method calls the user-defined apply_guardrail function and","sourceCodeStart":165,"sourceCodeEnd":201,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/proxy/guardrails/guardrail_hooks/custom_code/custom_code_guardrail.py#L165-L201","documentation":"CustomCodeCompilationError wrapping a Python SyntaxError raised while compiling the custom_code string inside the RestrictedPython sandbox (initial compile path). The message embeds the underlying syntax error with its line/column, so the submitted string itself is not valid Python for this compiler.","triggerScenarios":"custom_code contains invalid Python: bad indentation, unclosed quotes/brackets, or constructs the RestrictedPython policy rewrites into rejected code; also YAML block-scalar mistakes that mangle the string before it reaches the compiler.","commonSituations":"Block scalar (custom_code: |) indentation lost or extra-indented when copied; tabs mixed with spaces; smart quotes pasted from rich-text docs; f-string nesting unsupported by the runtime.","solutions":["Reproduce locally with compile(code, '<custom>', 'exec') to get the exact failing line, then fix it","Fix the YAML block-scalar indentation so the string reaches the proxy unchanged","Keep the code to plain functions and avoid exotic syntax the sandbox policy restricts","After fixing, hot-update via the guardrail update API or restart the proxy"],"exampleFix":"# before (value of custom_code): missing colon and bad indent\ndef apply_guardrail(inputs, request_data, input_type)\n      return allow()\n\n# after\ndef apply_guardrail(inputs, request_data, input_type):\n    return allow()","handlingStrategy":"validation","validationCode":"def check_syntax(src: str) -> None:\n    try:\n        compile(src, '<custom_code>', 'exec')\n    except SyntaxError as e:\n        raise ValueError(f'custom_code has a syntax error at line {e.lineno}: {e.msg}') from e","typeGuard":null,"tryCatchPattern":"from litellm.proxy.guardrails.guardrail_hooks.custom_code.custom_code_guardrail import CustomCodeCompilationError\ntry:\n    guardrail._compile_custom_code()\nexcept CustomCodeCompilationError as e:\n    if 'Syntax error' in str(e):\n        ...  # fix the named line in custom_code; safe to keep old code serving\n    raise","preventionTips":["Always compile() the custom_code string in CI before it reaches the proxy","Use a YAML linter and consistent block-scalar indentation for custom_code: |","Paste code as plain text (smart quotes and tabs break compilation)"],"tags":["guardrails","custom-code","syntax-error","sandbox","yaml"],"backgroundTag":"user-code-syntax-error","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}