跳到主要内容
此工具执行代码并可能执行破坏性操作。请务必信任传递给它的任何代码!
LangChain 提供了一个实验性工具,用于执行任意 Python 代码。这可以与能够生成代码的 LLM 结合使用,以执行更强大的计算。

用法

import { OpenAI } from "@langchain/openai";
import { PythonInterpreterTool } from "@langchain/community/experimental/tools/pyinterpreter";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

const prompt = ChatPromptTemplate.fromTemplate(
  `Generate python code that does {input}. Do not generate anything else.`
);

const model = new OpenAI({});

const interpreter = await PythonInterpreterTool.initialize({
  indexURL: "../node_modules/pyodide",
});

// Note: In Deno, it may be easier to initialize the interpreter yourself:
// import pyodideModule from "npm:pyodide/pyodide.js";
// import { PythonInterpreterTool } from "npm:@langchain/community/experimental/tools/pyinterpreter";

// const pyodide = await pyodideModule.loadPyodide();
// const pythonTool = new PythonInterpreterTool({instance: pyodide})

const chain = prompt
  .pipe(model)
  .pipe(new StringOutputParser())
  .pipe(interpreter);

const result = await chain.invoke({
  input: `prints "Hello LangChain"`,
});

console.log(JSON.parse(result).stdout);

// To install python packages:
// This uses the loadPackages command.
// This works for packages built with pyodide.
await interpreter.addPackage("numpy");
// But for other packages, you will want to use micropip.
// See: https://pyodide.org/en/stable/usage/loading-packages.html
// for more information
await interpreter.addPackage("micropip");
// The following is roughly equivalent to:
// pyodide.runPython(`import ${pkgname}; ${pkgname}`);
const micropip = interpreter.pyodideInstance.pyimport("micropip");
await micropip.install("numpy");

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.