{"record":{"id":"5ac321e7ef8fd5a7","repo":"BerriAI/litellm","slug":"failed-to-compile-custom-code-e","errorCode":null,"errorMessage":"Failed to compile custom code: {e}","messagePattern":"Failed to compile custom code: (.+?)","errorType":"exception","errorClass":"CustomCodeCompilationError","httpStatus":null,"severity":"error","filePath":"litellm/proxy/guardrails/guardrail_hooks/custom_code/custom_code_guardrail.py","lineNumber":188,"sourceCode":"\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\n        processes its result to determine the appropriate action.\n\n        The user-defined function can be either sync or async:\n        - Sync: def apply_guardrail(inputs, request_data, input_type): ...\n        - Async: async def apply_guardrail(inputs, request_data, input_type): ...","sourceCodeStart":170,"sourceCodeEnd":206,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/proxy/guardrails/guardrail_hooks/custom_code/custom_code_guardrail.py#L170-L206","documentation":"CustomCodeCompilationError raised when compiling/executing the sandboxed code raises anything other than a SyntaxError or a prior CustomCodeCompilationError — typically a runtime error thrown while exec() runs module-level statements, since compilation happens in two phases (compile, then exec in sandbox globals). The original exception is chained via raise ... from e and its message is embedded.","triggerScenarios":"Module-level code that executes during sandbox exec and fails: calling a bounds-checked limited builtin out of range (e.g. limited_range with a huge bound), NameError from an undefined name, TypeError while evaluating a class body, or accessing attributes the sandbox denies at exec time.","commonSituations":"Trying to import packages at module top (import os fails — the sandbox provides no __import__); module-level config reads or heavy computation that runs at import; code copied from a normal Python module that does work on import.","solutions":["Read the embedded {e} — it names the exact exception and expression that failed during exec","Move all logic inside def apply_guardrail; keep the module top level to declarations only","Remove import statements — use only the primitives the sandbox provides (regex_match, http_get, http_post, block, allow, ...)","Defer any expensive or environment-dependent computation to first call inside the entry function"],"exampleFix":"# before: import-time work fails inside the sandbox\nimport os\nFLAG = os.environ.get('STRICT')\n\ndef apply_guardrail(inputs, request_data, input_type):\n    ...\n\n# after: declarative top level, lazy reads inside the entry point\ndef apply_guardrail(inputs, request_data, input_type):\n    strict = (request_data.get('metadata') or {}).get('strict', False)\n    if strict:\n        return block('strict mode')\n    return allow()","handlingStrategy":"validation","validationCode":"from litellm.proxy.guardrails.guardrail_hooks.custom_code.sandbox import (\n    build_sandbox_globals, compile_sandboxed,\n)\n\ndef sandbox_preflight(custom_code: str) -> None:\n    g = build_sandbox_globals()\n    try:\n        exec(compile_sandboxed(custom_code), g)\n    except Exception as e:\n        raise ValueError(f'custom_code fails inside the sandbox: {type(e).__name__}: {e}') from e\n    assert callable(g.get('apply_guardrail'))","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    cause = e.__cause__  # the original module-level failure\n    raise SystemExit(f'custom_code rejected: {e} (caused by {cause!r})') from e","preventionTips":["Never put import statements or executable work at module level in custom_code - the sandbox has no __import__","Run the exact sandbox preflight (same build_sandbox_globals/compile_sandboxed) in CI, not just python -m py_compile","Keep top-level code declarative; compute inside apply_guardrail"],"tags":["guardrails","custom-code","sandbox","compile-error","restricted-python"],"backgroundTag":"sandboxed-code-compile-failed","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}