{"version":3,"sources":["../../../src/tools/python/python.ts"],"names":["PythonTool","Tool","name","description","join","storage","files","emitter","Emitter","root","child","namespace","creator","inputSchema","list","fileNames","unique","map","filename","z","object","language","enum","describe","code","string","hasMinLength","inputFiles","array","preprocess","options","codeInterpreter","url","ValidationError","message","data","propertyName","register","_run","input","_options","run","pipe","uniqueBy","f","filter","file","isIncludedIn","upload","getSourceCode","llm","promptTemplate","response","create","messages","UserMessage","render","abortSignal","signal","getTextContent","trim","prefix","result","callCodeInterpreter","body","source_code","Object","fromEntries","pythonId","filesOutput","download","entries","path","_","startsWith","String","slice","length","every","PythonToolOutput","stdout","stderr","exit_code","createSnapshot","shallowCopy","loadSnapshot","snapshot","fetch","method","headers","JSON","stringify","catch","error","cause","ToolError","ok","status","Error","text","json"],"mappings":";;;;;;;;;;;;;;AAyCO,MAAMA,mBAAmBC,aAAAA,CAAAA;EAzChC;;;EA0CEC,IAAAA,GAAO,QAAA;EACPC,WAAAA,GAAc;AACZ,IAAA,0OAAA;AACA,IAAA,yKAAA;AACA,IAAA,6CAAA;AACA,IAAA,+BAAA;AACA,IAAA,yJAAA;AACA,IAAA,iKAAA;AACA,IAAA,iDAAA;AACA,IAAA,2DAAA;AACA,IAAA,gCAAA;AACA,IAAA,0DAAA;AACA,IAAA,oDAAA;AACA,IAAA,kDAAA;AACA,IAAA,yCAAA;AACA,IAAA,oFAAA;AACA,IAAA,6GAAA;AACA,IAAA,mEAAA;AACA,IAAA,uGAAA;AACA,IAAA;AACAC,GAAAA,CAAAA,IAAAA,CAAK,GAAA,CAAA;AAESC,EAAAA,OAAAA;AACNC,EAAAA,KAAAA,GAAsB,EAAA;EAEhBC,OAAAA,GAA0DC,mBAAAA,CAAQC,KAAKC,KAAAA,CAAM;IAC3FC,SAAAA,EAAW;AAAC,MAAA,MAAA;AAAQ,MAAA;;IACpBC,OAAAA,EAAS;GACX,CAAA;AAEA,EAAA,MAAMC,WAAAA,GAAc;AAClB,IAAA,IAAA,CAAKP,KAAAA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AS6C,UAAU,GAAA,EAAK;AAC1C,IAAA,MAAM,IAAIF,kBAAAA,CACR,CAAA,6DAAA,EAAgE3C,QAAAA,CAAS6C,MAAM,CAAA,CAAA,CAAA,EAC/E;AAAC,MAAA,IAAIC,KAAAA,CAAM,MAAM9C,QAAAA,CAAS+C,IAAAA,EAAI;AAAI,KAAA,CAAA;AAEtC,EAAA;AAEA,EAAA,OAAO,MAAM/C,SAASgD,IAAAA,EAAI;AAC5B;AAxCsBrC,MAAAA,CAAAA,mBAAAA,EAAAA,qBAAAA,CAAAA","file":"python.cjs","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n  BaseToolOptions,\n  BaseToolRunOptions,\n  ToolEmitter,\n  Tool,\n  ToolError,\n  ToolInput,\n} from \"@/tools/base.js\";\nimport { z } from \"zod\";\nimport { PromptTemplate } from \"@/template.js\";\nimport { filter, isIncludedIn, map, pipe, unique, uniqueBy } from \"remeda\";\nimport { PythonFile, PythonStorage } from \"@/tools/python/storage.js\";\nimport { PythonToolOutput } from \"@/tools/python/output.js\";\nimport { ValidationError } from \"ajv\";\nimport { ConnectionOptions } from \"node:tls\";\nimport { RunContext } from \"@/context.js\";\nimport { hasMinLength } from \"@/internals/helpers/array.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport { shallowCopy } from \"@/serializer/utils.js\";\nimport { ChatModel } from \"@/backend/chat.js\";\nimport { UserMessage } from \"@/backend/message.js\";\n\nexport interface CodeInterpreterOptions {\n  url: string;\n  connectionOptions?: ConnectionOptions;\n}\n\nexport interface PythonToolOptions extends BaseToolOptions {\n  codeInterpreter: CodeInterpreterOptions;\n  preprocess?: {\n    llm: ChatModel;\n    promptTemplate: PromptTemplate.infer<{ input: string }>;\n  };\n  storage: PythonStorage;\n}\n\nexport class PythonTool extends Tool<PythonToolOutput, PythonToolOptions> {\n  name = \"Python\";\n  description = [\n    \"Run Python and/or shell code and return the console output. Use for isolated calculations, computations, data or file manipulation but still prefer assistant's capabilities (IMPORTANT: Do not use for text analysis or summarization).\",\n    \"Files provided by the user, or created in a previous run, will be accessible if and only if they are specified in the input. It is necessary to always print() results.\",\n    \"The following shell commands are available:\",\n    \"Use ffmpeg to convert videos.\",\n    \"Use yt-dlp to download videos, and unless specified otherwise use `-S vcodec:h264,res,acodec:m4a` for video and `-x --audio-format mp3` for audio-only.\",\n    \"Use pandoc to convert documents between formats (like MD, DOC, DOCX, PDF) -- and don't forget that you can create PDFs by writing markdown and then converting.\",\n    \"In Python, the following modules are available:\",\n    \"Use numpy, pandas, scipy and sympy for working with data.\",\n    \"Use matplotlib to plot charts.\",\n    \"Use pillow (import PIL) to create and manipulate images.\",\n    \"Use moviepy for complex manipulations with videos.\",\n    \"Use PyPDF2, pikepdf, or fitz to manipulate PDFs.\",\n    \"Use pdf2image to convert PDF to images.\",\n    \"Other Python libraries are also available -- however, prefer using the ones above.\",\n    \"Prefer using qualified imports -- `import library; library.thing()` instead of `import thing from library`.\",\n    \"Do not attempt to install libraries manually -- it will not work.\",\n    \"Each invocation of Python runs in a completely fresh VM -- it will not remember anything from before.\",\n    \"Do not use this tool multiple times in a row, always write the full code you want to run in a single invocation.\",\n  ].join(\" \");\n\n  public readonly storage: PythonStorage;\n  protected files: PythonFile[] = [];\n\n  public readonly emitter: ToolEmitter<ToolInput<this>, PythonToolOutput> = Emitter.root.child({\n    namespace: [\"tool\", \"python\"],\n    creator: this,\n  });\n\n  async inputSchema() {\n    this.files = await this.storage.list();\n    const fileNames = unique(map(this.files, ({ filename }) => filename));\n    return z.object({\n      language: z.enum([\"python\", \"shell\"]).describe(\"Use shell for ffmpeg, pandoc, yt-dlp\"),\n      code: z.string().describe(\"full source code file that will be executed\"),\n      ...(hasMinLength(fileNames, 1)\n        ? {\n            inputFiles: z\n              .array(z.enum(fileNames))\n              .describe(\n                \"To access an existing file, you must specify it; otherwise, the file will not be accessible. IMPORTANT: If the file is not provided in the input, it will not be accessible.\",\n              ),\n          }\n        : {}),\n    });\n  }\n\n  protected readonly preprocess;\n\n  public constructor(options: PythonToolOptions) {\n    super(options);\n    if (!options.codeInterpreter.url) {\n      throw new ValidationError([\n        {\n          message: \"Property must be a valid URL!\",\n          data: options,\n          propertyName: \"codeInterpreter.url\",\n        },\n      ]);\n    }\n    this.preprocess = options.preprocess;\n    this.storage = options.storage;\n  }\n\n  static {\n    this.register();\n  }\n\n  protected async _run(\n    input: ToolInput<this>,\n    _options: Partial<BaseToolRunOptions>,\n    run: RunContext<this>,\n  ) {\n    const inputFiles = await pipe(\n      this.files ?? (await this.storage.list()),\n      uniqueBy((f) => f.filename),\n      filter((file) => isIncludedIn(file.filename, (input.inputFiles ?? []) as string[])),\n      (files) => this.storage.upload(files),\n    );\n\n    const getSourceCode = async () => {\n      if (this.preprocess) {\n        const { llm, promptTemplate } = this.preprocess;\n        const response = await llm.create({\n          messages: [new UserMessage(promptTemplate.render({ input: input.code }))],\n          abortSignal: run.signal,\n        });\n        return response.getTextContent().trim();\n      }\n      return input.code;\n    };\n\n    const prefix = \"/workspace/\";\n\n    const result = await callCodeInterpreter({\n      url: `${this.options.codeInterpreter.url}/v1/execute`,\n      body: {\n        source_code: await getSourceCode(),\n        files: Object.fromEntries(\n          inputFiles.map((file) => [`${prefix}${file.filename}`, file.pythonId]),\n        ),\n      },\n      signal: run.signal,\n    });\n\n    const filesOutput = await this.storage.download(\n      Object.entries(result.files)\n        .filter(([path, _]) => path.startsWith(prefix))\n        .map(([path, pythonId]) => ({ path: path, pythonId: String(pythonId) }))\n        .map((file) => ({ filename: file.path.slice(prefix.length), pythonId: file.pythonId }))\n        .filter((file) =>\n          inputFiles.every(\n            (input) => input.filename !== file.filename || input.pythonId !== file.pythonId,\n          ),\n        ),\n    );\n\n    return new PythonToolOutput(result.stdout, result.stderr, result.exit_code, filesOutput);\n  }\n\n  createSnapshot() {\n    return {\n      ...super.createSnapshot(),\n      files: shallowCopy(this.files),\n      storage: this.storage,\n      preprocess: this.preprocess,\n    };\n  }\n\n  loadSnapshot(snapshot: ReturnType<typeof this.createSnapshot>): void {\n    super.loadSnapshot(snapshot);\n  }\n}\n\nexport async function callCodeInterpreter({\n  url,\n  body,\n  signal,\n}: {\n  url: string;\n  body: unknown;\n  signal?: AbortSignal;\n}): Promise<Record<string, any>> {\n  const response = await fetch(url, {\n    method: \"POST\",\n    headers: {\n      \"Accept\": \"application/json\",\n      \"Content-Type\": \"application/json\",\n    },\n    body: JSON.stringify(body),\n    signal,\n  }).catch((error) => {\n    if (error.cause?.name === \"HTTPParserError\") {\n      throw new ToolError(\n        \"Request to code interpreter has failed -- ensure that CODE_INTERPRETER_URL points to the new HTTP endpoint (default port: 50081).\",\n        [error],\n      );\n    } else {\n      throw new ToolError(\"Request to code interpreter has failed.\", [error]);\n    }\n  });\n\n  if (!response) {\n    throw new ToolError(\"Request to code interpreter has failed.\");\n  }\n\n  if (!response.ok && response.status >= 400) {\n    throw new ToolError(\n      `Request to code interpreter has failed with HTTP status code ${response.status}.`,\n      [new Error(await response.text())],\n    );\n  }\n\n  return await response.json();\n}\n"]}