Skip to main content

A LangChain adapter for KernelBox, enabling stateful IPython execution.

Project description

🦜🔗 LangChain KernelBox

PyPI - Version Python versions License: MIT

A stateful, persistent IPython code execution environment for LangChain and LangGraph agents.

langchain-kernelbox replaces the legacy, stateless PythonREPLTool with a high-performance stateful sandbox. By keeping variables and imports alive across conversational turns, this adapter dramatically reduces LLM token consumption, saving you over 80% on API costs!


⚡ Quick Install

You can install the package using uv (recommended) or pip:

uv add langchain-kernelbox
# or
pip install langchain-kernelbox

🚀 Quick Run (LangChain)

Simply swap out PythonREPLTool for KernelBoxTool. Your agent will instantly gain persistent memory.

from langchain_kernelbox import KernelBoxTool

# Initialize the stateful tool
tool = KernelBoxTool()

# Step 1: Define a variable
tool.run("x = 10\nprint('Defined x')")

# Step 2: Use it later (no need to redefine!)
result = tool.run("y = x * 5\nprint(y)")
print(result) # Output: 50

🕸️ Quick Run (LangGraph)

For multi-agent or multi-user architectures, you need isolated sessions per thread. langchain-kernelbox provides a native LangGraph config factory:

from langchain_core.runnables.config import RunnableConfig
from langchain_kernelbox import KernelBoxTool, get_session_id_from_config

def execute_code_node(state: dict, config: RunnableConfig):
    # Extracts `thread_id` dynamically to ensure private sessions
    session_id = get_session_id_from_config(config)
    
    tool = KernelBoxTool(session_id=session_id)
    return {"messages": [tool.run(state["code"])]}

📉 Why KernelBox? (The Savings)

Standard tools require your LLM agent to remember and re-send all previously generated code on every single step. As the conversation gets longer, this causes a massive spike in token costs.

KernelBox remembers everything for you, so you only ever send the new code. We've included a token audit script to prove the cost savings:

Token Audit Benchmark

# Run the benchmark locally
uv run python benchmarks/token_audit.py

Example Output:

============================================================
Token Usage Benchmark: Stateless Tool vs KernelBox
============================================================
Step       | Stateless Tokens       | KernelBox Tokens
-----------------------------------------------------------------
Step 1     | 70                     | 55
Step 2     | 116                    | 93
Step 3     | 177                    | 131
Step 4     | 253                    | 169
Step 5     | 344                    | 207
Step 6     | 451                    | 245
Step 7     | 574                    | 283
Step 8     | 713                    | 321
Step 9     | 869                    | 359
Step 10    | 1043                   | 398
-----------------------------------------------------------------
TOTAL      | 4610                   | 2261
============================================================

Conclusion: KernelBox saves ~51.0% on LLM API costs!
The stateless tool gets more expensive with every step, while KernelBox stays cheap and fast.

🧪 Quick Test

Want to contribute or run the test suite locally? Clone the repository and use pytest:

git clone https://github.com/VinayChaudhari1996/langchain-kernelbox.git
cd langchain-kernelbox

# Add dev dependencies and test
uv add --dev pytest pytest-asyncio
uv run pytest

🛡️ Powered by KernelBox Core

langchain-kernelbox is a lightweight adapter built on top of the KernelBox engine.

Security & Sandboxing Executing LLM-generated code directly on your host machine is extremely dangerous. KernelBox provides a production-ready Docker sandbox out of the box to mitigate Remote Code Execution (RCE) risks:

  • Runs code as a non-root sandbox_user
  • Enforces read-only filesystem mounts
  • Uses in-memory tmpfs for temporary scratch space
  • Drops all Linux capabilities to prevent privilege escalation

Links & Resources:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

langchain_kernelbox-0.1.0.tar.gz (1.5 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

langchain_kernelbox-0.1.0-py3-none-any.whl (4.8 kB view details)

Uploaded Python 3

File details

Details for the file langchain_kernelbox-0.1.0.tar.gz.

File metadata

  • Download URL: langchain_kernelbox-0.1.0.tar.gz
  • Upload date:
  • Size: 1.5 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for langchain_kernelbox-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d21888c2520ef2c7443f59fceecc5cb736cb440ac19e4c53020e8d92c8d18c70
MD5 40ec2eae1c1d526453ba407b00a83bf2
BLAKE2b-256 ec3e97dc8bbd450a6bead1f8fa9e49b8582a3dfefc124fcdbdcb5367002f9093

See more details on using hashes here.

File details

Details for the file langchain_kernelbox-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: langchain_kernelbox-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 4.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for langchain_kernelbox-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 49ace7058b9dda0e856fb3b2dc4f2e7044db451687097c661820edf5b5030248
MD5 27e416bf1e8babeb8bbd53965dedf3e4
BLAKE2b-256 9be5661fd56171483b64f09c2bbb4cca960fca4a5abc60f773a73d5a4f1815b5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page