Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(guardrails): provide _inplacevar_ to sandbox

jayden469045ba91bc
diff --git a/litellm/proxy/guardrails/guardrail_hooks/custom_code/sandbox.py b/litellm/proxy/guardrails/guardrail_hooks/custom_code/sandbox.py
index 7e1c3f228bc..2250daaf899 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/custom_code/sandbox.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/custom_code/sandbox.py
@@ -14,6 +14,7 @@ We subclass it to permit those specific nodes, while keeping every other
restriction intact.
"""
+import operator
from typing import Any, Dict
from RestrictedPython import (
@@ -57,6 +58,34 @@ class AsyncAwareTransformer(RestrictingNodeTransformer):
return self.node_contents_visit(node)
+_INPLACE_OPS: Dict[str, Any] = {
+ "+=": operator.iadd,
+ "-=": operator.isub,
+ "*=": operator.imul,
+ "/=": operator.itruediv,
+ "//=": operator.ifloordiv,
+ "%=": operator.imod,
+ "**=": operator.ipow,
+ "@=": operator.imatmul,
+ "&=": operator.iand,
+ "|=": operator.ior,
+ "^=": operator.ixor,
+ "<<=": operator.ilshift,
+ ">>=": operator.irshift,
+}
+
+
+def _inplacevar_(op: str, x: Any, y: Any) -> Any:
+ # RestrictedPython rewrites ``x += 1`` on a simple name into
+ # ``x = _inplacevar_("+=", x, 1)``. The package deliberately ships no
+ # default, so we dispatch through ``operator``'s in-place helpers, which
+ # honour Python's normal ``__iadd__``/``__add__`` fallback.
+ fn = _INPLACE_OPS.get(op)
+ if fn is None:
+ raise SyntaxError(f"augmented assignment {op!r} is not supported")
+ return fn(x, y)
+
+
def _build_sandbox_builtins() -> Dict[str, Any]:
# ``limited_builtins`` overrides ``list``/``tuple``/``range`` from
# ``safe_builtins`` with bounds-checking variants (e.g. ``limited_range``
@@ -83,6 +112,7 @@ def build_sandbox_globals() -> Dict[str, Any]:
sandbox["_getiter_"] = default_guarded_getiter
sandbox["_iter_unpack_sequence_"] = guarded_iter_unpack_sequence
sandbox["_write_"] = full_write_guard
+ sandbox["_inplacevar_"] = _inplacevar_
return sandbox
diff --git a/tests/test_litellm/proxy/guardrails/test_custom_code_security.py b/tests/test_litellm/proxy/guardrails/test_custom_code_security.py
index 4a47672e9b4..00cf3f317c9 100644
--- a/tests/test_litellm/proxy/guardrails/test_custom_code_security.py
+++ b/tests/test_litellm/proxy/guardrails/test_custom_code_security.py
@@ -162,6 +162,25 @@ def test_typical_sync_guardrail_still_works():
assert guardrail._compiled_function is not None
+def test_augmented_assignment_works():
+ # The transformer rewrites `n += 1` into `n = _inplacevar_("+=", n, 1)`,
+ # so the sandbox must bind `_inplacevar_`.
+ code = (
+ "def apply_guardrail(inputs, request_data, input_type):\n"
+ " count = 0\n"
+ ' for _ in inputs["texts"]:\n'
+ " count += 1\n"
+ ' return {"action": "allow", "n": count}\n'
+ )
+ guardrail = _compile(code)
+ fn = guardrail._compiled_function
+ assert fn is not None
+ assert fn({"texts": ["a", "b", "c"]}, {}, "request") == {
+ "action": "allow",
+ "n": 3,
+ }
+
+
def test_missing_apply_guardrail_raises():
with pytest.raises(CustomCodeCompilationError, match="apply_guardrail"):
_compile("x = 1\n")