Skip to content

Integrations

LangChain and LangGraph

A LangChain tool for createAgent, which runs on LangGraph. The same tool works in any LangGraph graph.

Install

Terminal
npm i sandboxplease langchain @langchain/core @langchain/openai zod

Code

Copy it as langchain.ts. The model is the only part you would change.

langchain.ts
// LangChain (createAgent, built on LangGraph): a run_command tool backed by one sandbox per agent run.
// Run: SANDBOXPLEASE_API_KEY=... OPENAI_API_KEY=... npx tsx langchain.ts
import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { tool } from "@langchain/core/tools";
import { ChatOpenAI } from "@langchain/openai";
import { createAgent } from "langchain";
import { type Sandbox, SandboxPlease } from "sandboxplease";
import { z } from "zod";

export function sandboxTool(sp = new SandboxPlease()) {
  let sandbox: Promise<Sandbox> | undefined;
  const runCommand = tool(
    async ({ command }) => {
      sandbox ??= sp.sandboxes.create({ timeout: 600 });
      const { exitCode, stdout, stderr } = await (await sandbox).exec(command);
      return JSON.stringify({ exitCode, stdout, stderr });
    },
    {
      name: "run_command",
      description:
        "Run a shell command in a Linux sandbox with Python 3 and Node. Returns exit code, stdout and stderr.",
      schema: z.object({ command: z.string().describe("Shell command, e.g. python3 -c 'print(1+1)'") }),
    },
  );
  return { runCommand, close: async () => (await sandbox)?.kill() };
}

export async function solve(model: BaseChatModel, prompt: string) {
  const { runCommand, close } = sandboxTool();
  try {
    const agent = createAgent({ model, tools: [runCommand] });
    return await agent.invoke({ messages: [{ role: "user", content: prompt }] });
  } finally {
    await close();
  }
}

if (import.meta.url === `file://${process.argv[1]}`) {
  const { messages } = await solve(new ChatOpenAI({ model: "gpt-5-mini" }), "Compute 6*7 with Python in the sandbox.");
  console.log(messages.at(-1)?.content);
}

Run it

Terminal
export SANDBOXPLEASE_API_KEY=sp-v1-…
export OPENAI_API_KEY=…
npx tsx langchain.ts

The agent runs Python in the sandbox and answers 42. Each sandbox shows up in Logs with its provider and cost.