{"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","generate","render","signal","stream","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":";;;;;;;;;;;;;AAoDO,MAAMA,mBAAmBC,aAAAA,CAAAA;EApDhC;;;EAqDEC,IAAO,GAAA,QAAA;EACPC,WAAc,GAAA;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,OAA0DC,GAAAA,mBAAAA,CAAQC,KAAKC,KAAM,CAAA;IAC3FC,SAAW,EAAA;AAAC,MAAA,MAAA;AAAQ,MAAA;;IACpBC,OAAS,EAAA;GACX,CAAA;AAEA,EAAA,MAAMC,WAAc,GAAA;AAClB,IAAA,IAAA,CAAKP,KAAQ,GAAA,MAAM,IAAKD,C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AApCsBrC,MAAAA,CAAAA,mBAAAA,EAAAA,qBAAAA,CAAAA","file":"python.cjs","sourcesContent":["/**\n * Copyright 2025 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\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 { BaseLLMOutput } from \"@/llms/base.js\";\nimport { LLM } from \"@/llms/llm.js\";\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\";\n\nexport interface CodeInterpreterOptions {\n  url: string;\n  connectionOptions?: ConnectionOptions;\n}\n\nexport interface PythonToolOptions extends BaseToolOptions {\n  codeInterpreter: CodeInterpreterOptions;\n  preprocess?: {\n    llm: LLM<BaseLLMOutput>;\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.generate(promptTemplate.render({ input: input.code }), {\n          signal: run.signal,\n          stream: false,\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}) {\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 bee-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 bee-code-interpreter has failed.\", [error]);\n    }\n  });\n\n  if (!response?.ok) {\n    throw new ToolError(\n      `Request to bee-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"]}