{"version":3,"sources":["jsdelivr-header.js","/npm/baseai@0.9.44/src/index.ts","/npm/baseai@0.9.44/src/utils/formatting.ts","/npm/baseai@0.9.44/src/utils/get-available-pipes.ts","/npm/baseai@0.9.44/src/utils/get-available-tools.ts","/npm/baseai@0.9.44/src/utils/heading.ts","/npm/baseai@0.9.44/src/utils/icons.ts","/npm/baseai@0.9.44/src/utils/is-tool-present.ts","/npm/baseai@0.9.44/src/utils/config/config-handler.ts","/npm/baseai@0.9.44/src/utils/retrieve-credentials.ts","/npm/baseai@0.9.44/src/utils/ts-format-code.ts","/npm/baseai@0.9.44/src/add/index.ts","/npm/baseai@0.9.44/src/auth/index.ts","/npm/baseai@0.9.44/src/build/index.ts","/npm/baseai@0.9.44/src/dev/data/models.ts","/npm/baseai@0.9.44/src/dev/utils/dlog.ts","/npm/baseai@0.9.44/src/utils/memory/compare-docs-list.ts","/npm/baseai@0.9.44/src/utils/memory/constants.ts","/npm/baseai@0.9.44/src/utils/memory/load-memory-files.ts","/npm/baseai@0.9.44/src/utils/memory/get-document-content.ts","/npm/baseai@0.9.44/src/utils/memory/lib.ts","/npm/baseai@0.9.44/src/utils/memory/db/lib.ts","/npm/baseai@0.9.44/types/memory.ts","/npm/baseai@0.9.44/src/utils/logger-utils.ts","/npm/baseai@0.9.44/src/utils/logger.ts","/npm/baseai@0.9.44/src/utils/memory/generate-local-embeddings.ts","/npm/baseai@0.9.44/src/utils/memory/generate-openai-embeddings.ts","/npm/baseai@0.9.44/src/utils/memory/load-memory-config.ts","/npm/baseai@0.9.44/src/utils/memory/handle-old-memory-config.ts","/npm/baseai@0.9.44/src/utils/memory/print-diff-table.ts","/npm/baseai@0.9.44/src/deploy/index.ts","/npm/baseai@0.9.44/src/utils/memory/git-sync/handle-git-sync-memories.ts","/npm/baseai@0.9.44/src/utils/memory/git-sync/save-deployed-commit-in-config.ts","/npm/baseai@0.9.44/src/utils/memory/git-sync/get-changed-files-between-commits.ts","/npm/baseai@0.9.44/src/utils/memory/generate-embeddings.ts","/npm/baseai@0.9.44/src/utils/memory/chunker.ts","/npm/baseai@0.9.44/src/utils/memory/git-sync/save-embedded-commit-in-config.ts","/npm/baseai@0.9.44/src/utils/memory/check-memory-doc-exists.ts","/npm/baseai@0.9.44/src/utils/memory/check-memory-exist.ts","/npm/baseai@0.9.44/src/deploy/document.ts","/npm/baseai@0.9.44/src/dev/index.ts","/npm/baseai@0.9.44/src/dev/hono/errors.ts","/npm/baseai@0.9.44/src/dev/middleware/custom-cors.ts","/npm/baseai@0.9.44/src/dev/middleware/powered-by.ts","/npm/baseai@0.9.44/src/dev/middleware/pre-flight.ts","/npm/baseai@0.9.44/src/dev/routes/base.ts","/npm/baseai@0.9.44/src/dev/utils/thread/get-few-shot-messages.ts","/npm/baseai@0.9.44/src/data/models.ts","/npm/baseai@0.9.44/src/dev/data/globals.ts","/npm/baseai@0.9.44/src/dev/utils/thread/add-json-mode.ts","/npm/baseai@0.9.44/src/dev/utils/thread/get-system-prompt.ts","/npm/baseai@0.9.44/src/dev/utils/thread/process-messages.ts","/npm/baseai@0.9.44/src/dev/utils/thread/get-run-thread.ts","/npm/baseai@0.9.44/src/dev/providers/anthropic/api.ts","/npm/baseai@0.9.44/src/dev/providers/utils.ts","/npm/baseai@0.9.44/src/dev/providers/anthropic/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/anthropic/index.ts","/npm/baseai@0.9.44/src/dev/providers/openai/api.ts","/npm/baseai@0.9.44/src/dev/providers/openai/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/openai/index.ts","/npm/baseai@0.9.44/src/dev/providers/together-ai/api.ts","/npm/baseai@0.9.44/src/dev/providers/together-ai/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/together-ai/index.ts","/npm/baseai@0.9.44/src/dev/providers/groq/api.ts","/npm/baseai@0.9.44/src/dev/providers/groq/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/groq/index.ts","/npm/baseai@0.9.44/src/dev/providers/google/api.ts","/npm/baseai@0.9.44/src/dev/providers/google/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/google/index.ts","/npm/baseai@0.9.44/src/dev/providers/cohere/api.ts","/npm/baseai@0.9.44/src/dev/providers/cohere/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/cohere/index.ts","/npm/baseai@0.9.44/src/dev/providers/fireworks-ai/api.ts","/npm/baseai@0.9.44/src/dev/providers/fireworks-ai/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/fireworks-ai/index.ts","/npm/baseai@0.9.44/src/dev/providers/perplexity/api.ts","/npm/baseai@0.9.44/src/dev/providers/perplexity/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/perplexity/index.ts","/npm/baseai@0.9.44/src/dev/providers/mistral-ai/api.ts","/npm/baseai@0.9.44/src/dev/providers/mistral-ai/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/mistral-ai/index.ts","/npm/baseai@0.9.44/src/dev/providers/ollama/api.ts","/npm/baseai@0.9.44/src/dev/providers/ollama/chatComplete.ts","/npm/baseai@0.9.44/src/dev/providers/ollama/index.ts","/npm/baseai@0.9.44/src/dev/providers/index.ts","/npm/baseai@0.9.44/src/dev/utils/provider-handlers/transfrom-to-provider-request.ts","/npm/baseai@0.9.44/src/dev/utils/provider-handlers/response-handler-utils.ts","/npm/baseai@0.9.44/src/dev/utils/provider-handlers/provider-response-handler.ts","/npm/baseai@0.9.44/src/dev/utils/provider-handlers/construct-provider-request.ts","/npm/baseai@0.9.44/src/dev/utils/provider-handlers/provider-request-handler.ts","/npm/baseai@0.9.44/src/dev/utils/is-json-mode.ts","/npm/baseai@0.9.44/src/dev/llms/utils.ts","/npm/baseai@0.9.44/src/dev/utils/get-provider.ts","/npm/baseai@0.9.44/src/dev/utils/has-tool-support.ts","/npm/baseai@0.9.44/src/dev/utils/add-tools-to-params.ts","/npm/baseai@0.9.44/src/dev/llms/call-anthropic.ts","/npm/baseai@0.9.44/src/dev/llms/call-cohere.ts","/npm/baseai@0.9.44/src/dev/llms/call-fireworks.ts","/npm/baseai@0.9.44/src/dev/llms/call-google.ts","/npm/baseai@0.9.44/src/dev/llms/call-groq.ts","/npm/baseai@0.9.44/src/dev/llms/call-ollama.ts","/npm/baseai@0.9.44/src/dev/llms/call-openai.ts","/npm/baseai@0.9.44/src/dev/utils/moderate.ts","/npm/baseai@0.9.44/src/dev/llms/call-perplexity.ts","/npm/baseai@0.9.44/src/dev/llms/call-together.ts","/npm/baseai@0.9.44/src/dev/llms/call-xai.ts","/npm/baseai@0.9.44/src/dev/llms/call-llm.ts","/npm/baseai@0.9.44/src/dev/utils/provider-handlers/streaming-response-handler.ts","/npm/baseai@0.9.44/src/dev/routes/v1/pipes/run.ts","/npm/baseai@0.9.44/types/pipe.ts","/npm/baseai@0.9.44/types/tools.ts","/npm/baseai@0.9.44/src/init/index.ts","/npm/baseai@0.9.44/src/memory/create.ts","/npm/baseai@0.9.44/src/memory/embed.ts","/npm/baseai@0.9.44/src/memory/embed-doc.ts","/npm/baseai@0.9.44/src/utils/memory/get-available-memories.ts","/npm/baseai@0.9.44/src/memory/list.ts","/npm/baseai@0.9.44/src/memory/retrieve.ts","/npm/baseai@0.9.44/src/pipe/index.ts","/npm/baseai@0.9.44/src/tool/index.ts","/npm/baseai@0.9.44/src/utils/cli.ts","/npm/baseai@0.9.44/src/utils/config/set-local-embeddings.ts","/npm/baseai@0.9.44/src/utils/debug-mode.ts","/npm/baseai@0.9.44/src/utils/init.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;OCLO,OAAY,gBACZ,OAAU,cCFV,OAAa,iBACb,MAAQ,aAER,IAAM,GAAQ,CACpB,KAAM,EAAG,KACT,QAAS,EAAG,MACZ,QAAS,EAAG,OACZ,MAAO,EAAG,IACV,MAAO,EAAG,MACV,IAAK,EAAG,IACR,OAAQ,EAAG,OACX,KAAM,EAAG,KACT,KAAM,EAAG,KACT,QAAS,EAAG,QACZ,MAAO,EAAG,MACV,KAAM,E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cACL,KAGH,EAAQ,eACL,KAGH,EAAQ,eACL,KAGH,EAAQ,gBACL,GAAM,CAAE,iBAAiB,IAI5B,EAAQ,YAAc,GAAK,YAAc,GAAK,mBAC3C,GAAO,CACZ,UAAW,EAAM,YAKf,EAAQ,WAAa,GAAK,YAAc,GAAK,mBAC1C,GAAmB,CACxB,WAAY,EAAM,OAClB,UAAW,EAAM,YAKf,EAAQ,WAAa,GAAK,WAAa,GAAK,mBACzC,GAAqB,CAC1B,WAAY,EAAM,OAClB,aAAc,EAAM,SACpB,UAAW,EAAM,YAIf,EAAQ,WAAa,GAAK,eACvB,KAGH,EAAQ,YAAc,GAAK,eACxB,KAGH,EAAQ,UAAY,GAAK,aAAe,GAAK,iBAC1C,GAAS,CACd,WAAY,EAAM,OAClB,aAAc,EAAM,SACpB,UAAW,EAAM,YAIf,EAAQ,WAAa,GAAK,mBACvB,GAAY,CACjB,WAAY,EAAM,OAClB,UAAW,EAAM,YAIf,EAAQ,mBACL,GAAe,CAAE,OAAQ,EAAM,OAAQ,MAAO,EAAM,QAGvD,EAAQ,WAAa,EAAQ,qBAC1B,GAAyB,EAAM,OAKrC,EAAQ,QACR,EAAQ,MACR,EAAQ,UACR,EAAQ,YACR,EAAQ,KACP,CAED,IAAO,EAAG,GAAgB,SACpB,GAAQ,CAAE,gBACjB,CACD,EA9GwD","file":"/npm/baseai@0.9.44/dist/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/baseai@0.9.44/dist/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","#!/usr/bin/env node\nimport dotenv from 'dotenv';\nimport path from 'path';\nimport { addPipe } from './add';\nimport { auth } from './auth';\nimport build from './build';\nimport { deploy, deploySingleMemory } from './deploy';\nimport { runBaseServer } from './dev';\nimport { init } from './init';\nimport { createMemory } from './memory/create';\nimport { embedMemory } from './memory/embed';\nimport { embedDoc } from './memory/embed-doc';\nimport { listMemory } from './memory/list';\nimport { retrieveMemory } from './memory/retrieve';\nimport { createPipe } from './pipe';\nimport { createTool } from './tool';\nimport cli from './utils/cli';\nimport { loadConfig } from './utils/config/config-handler';\nimport { setLocalEmbeddingsConfig } from './utils/config/set-local-embeddings';\nimport debugMode from './utils/debug-mode';\nimport cliInit from './utils/init';\nimport { initLogger } from './utils/logger-utils';\nimport { deploySingleDocument } from './deploy/document';\n\nconst { flags, input, showHelp } = cli;\nconst { clear, debug } = flags;\n\n// Utility function to check if a command is present\nconst command = (cmd: string): boolean => input.includes(cmd);\n\n// Utility function to check if a flag is present\nconst flag = (flg: string): boolean => Boolean(flags[flg]);\n\n(async () => {\n\tawait cliInit({ clear });\n\tif (debug) debugMode(cli);\n\n\t// Make sure baseai is initialized\n\tdebug && console.log('Checking if baseai is initialized');\n\tcommand('init')\n\t\t? await init({ calledAsCommand: true, debug })\n\t\t: await init({ calledAsCommand: false, debug });\n\n\t// Envs.\n\tconst config = await loadConfig();\n\tdotenv.config({ path: path.resolve(process.cwd(), config.envFilePath) });\n\n\tdebug && console.log('Initializing logger');\n\tawait initLogger();\n\n\tif (command('help')) {\n\t\tshowHelp(0);\n\t}\n\n\tif (command('auth')) {\n\t\tawait auth();\n\t}\n\n\tif (command('dev')) {\n\t\tawait runBaseServer();\n\t}\n\n\tif (command('pipe')) {\n\t\tawait createPipe();\n\t}\n\n\tif (command('tool')) {\n\t\tawait createTool();\n\t}\n\n\tif (command('build')) {\n\t\tawait build({ calledAsCommand: true });\n\t}\n\n\t// Deploy all\n\tif (command('deploy') && !flag('memory') && !flag('document')) {\n\t\tawait deploy({\n\t\t\toverwrite: flags.overwrite\n\t\t});\n\t}\n\n\t// Deploy memory\n\tif (command('deploy') && flag('memory') && !flag('document')) {\n\t\tawait deploySingleMemory({\n\t\t\tmemoryName: flags.memory,\n\t\t\toverwrite: flags.overwrite\n\t\t});\n\t}\n\n\t// Deploy single document\n\tif (command('deploy') && flag('memory') && flag('document')) {\n\t\tawait deploySingleDocument({\n\t\t\tmemoryName: flags.memory,\n\t\t\tdocumentName: flags.document,\n\t\t\toverwrite: flags.overwrite\n\t\t});\n\t}\n\n\tif (command('memory') && flag('list')) {\n\t\tawait listMemory();\n\t}\n\n\tif (command('memory') && !flag('list')) {\n\t\tawait createMemory();\n\t}\n\n\tif (command('embed') && flag('document') && flag('memory')) {\n\t\tawait embedDoc({\n\t\t\tmemoryName: flags.memory,\n\t\t\tdocumentName: flags.document,\n\t\t\toverwrite: flags.overwrite\n\t\t});\n\t}\n\n\tif (command('embed') && !flag('document')) {\n\t\tawait embedMemory({\n\t\t\tmemoryName: flags.memory,\n\t\t\toverwrite: flags.overwrite\n\t\t});\n\t}\n\n\tif (command('retrieve')) {\n\t\tawait retrieveMemory({ memory: flags.memory, query: flags.query });\n\t}\n\n\tif (command('config') && command('embeddings')) {\n\t\tawait setLocalEmbeddingsConfig(flags.local);\n\t}\n\n\t// Add | Clone | Install\n\tif (\n\t\tcommand('add') ||\n\t\tcommand('a') ||\n\t\tcommand('clone') ||\n\t\tcommand('install') ||\n\t\tcommand('i')\n\t) {\n\t\t// `baseai add login/pipe` so destructing the second one.\n\t\tconst [_, loginAndPipe] = input;\n\t\tawait addPipe({ loginAndPipe });\n\t}\n})();\n\n// Types.\nexport * from 'types/config';\n","import figures from 'figures';\nimport pc from 'picocolors';\n\nexport const color = {\n\tinfo: pc.cyan,\n\tsuccess: pc.green,\n\twarning: pc.yellow,\n\terror: pc.red,\n\tgreen: pc.green,\n\tred: pc.red,\n\tyellow: pc.yellow,\n\tcyan: pc.cyan,\n\tblue: pc.blue,\n\tmagenta: pc.magenta,\n\twhite: pc.white,\n\tgray: pc.gray,\n\tdim: pc.dim,\n\tbold: pc.bold\n};\n\nexport const dimItalic = (text: string) => pc.italic(pc.dim(text));\nexport const dim = pc.dim;\nexport const bold = pc.bold;\nexport const underline = pc.underline;\nexport const italic = pc.italic;\nexport const inverse = pc.inverse;\nexport const hidden = pc.hidden;\nexport const strikethrough = pc.strikethrough;\nexport const reset = pc.reset;\nexport const black = pc.black;\nexport const red = pc.red;\nexport const green = pc.green;\nexport const yellow = pc.yellow;\nexport const blue = pc.blue;\nexport const magenta = pc.magenta;\nexport const cyan = pc.cyan;\nexport const white = pc.white;\nexport const gray = pc.gray;\nexport const oneSpaced = ` `;\nexport const twoSpaced = `  `;\nexport const threeSpaced = `   `;\nexport const fourSpaced = `    `;\nexport const newLine = `\\n`;\n\nexport const pad = (n: number): string => {\n\treturn ' '.repeat(n);\n};\n\nexport const lineItem = pc.dim(`${figures.lineUpDownRight} `);\n","import fs from 'fs';\nimport path from 'path';\n\nexport async function getAvailablePipes() {\n\t// Construct the path containing all pipes folders.\n\tconst pipesPath = path.join(process.cwd(), 'baseai', 'pipes');\n\n\t// Check if the baseai directory exists.\n\tif (!fs.existsSync(pipesPath)) return [];\n\n\t// Get all directories names in the pipe path.\n\tconst pipeNames = await fs.promises.readdir(pipesPath);\n\n\t// Make complete paths for each pipe.\n\tconst slugifiedPipes = pipeNames.map(pipeName =>\n\t\tpipeName.replace('.ts', '')\n\t);\n\n\t// Return the pipe names.\n\treturn slugifiedPipes;\n}\n","import fs from 'fs';\nimport path from 'path';\n\nexport async function getAvailableTools() {\n\t// Construct the path containing all tools folders.\n\tconst toolsPath = path.join(process.cwd(), 'baseai', 'tools');\n\n\t// Check if the baseai directory exists.\n\tif (!fs.existsSync(toolsPath)) return [];\n\n\t// Get all directories names in the tool path.\n\tconst toolsNames = await fs.promises.readdir(toolsPath);\n\n\t// Make complete paths for each tool.\n\tconst toolsPaths = toolsNames.map(toolName => toolName.replace('.ts', ''));\n\n\t// Return the tool names.\n\treturn toolsPaths;\n}\n","import color from 'picocolors';\n\nexport function heading({\n\ttext,\n\tsub,\n\tdim,\n\tgreen\n}: {\n\ttext: string;\n\tsub?: string;\n\tdim?: boolean;\n\tgreen?: boolean;\n}) {\n\tif (green) {\n\t\treturn `${color.bgGreen(color.black(` ${text} `))} ${sub && sub}`;\n\t}\n\tif (dim) {\n\t\treturn `${color.bgBlack(color.white(` ${text} `))} ${sub && sub}`;\n\t}\n\treturn `${color.bold(color.bgCyan(color.black(` ${text} `)))} ${sub && sub}`;\n}\n","import figures from 'figures';\n\nconst icons = {\n\tpipe: figures.lineDownDoubleRightDouble,\n\ttool: figures.lineDownLeftBoldRightBold,\n\tmemory: figures.nodejs\n};\n\nexport default icons;\n","import slugify from '@sindresorhus/slugify';\n\n/**\n * Checks if a tool with the given name is present in the list of all tools.\n *\n * @param {Object} params - The parameters for the function.\n * @param {string} params.name - The name of the tool to check for.\n * @param {string[]} params.allTools - The list of all tools.\n * @returns {boolean} - Returns `true` if the tool is present, otherwise `false`.\n */\nexport function isToolPresent({\n\tname,\n\tallTools\n}: {\n\tname: string;\n\tallTools: string[];\n}) {\n\treturn allTools.some(tool => {\n\t\treturn slugify(tool) === slugify(name);\n\t});\n}\n","import * as p from '@clack/prompts';\nimport { cosmiconfig } from 'cosmiconfig';\nimport { TypeScriptLoader } from 'cosmiconfig-typescript-loader';\nimport type { BaseAIConfig } from 'types/config';\n\nexport const defaultConfig: BaseAIConfig = {\n\tlog: {\n\t\t// Enable or disable logging\n\t\tisEnabled: true,\n\t\t// Log sensitive data\n\t\tlogSensitiveData: false,\n\t\t// Toggle specific log categories\n\t\tpipe: true,\n\t\t'pipe.completion': true,\n\t\t'pipe.request': true,\n\t\t'pipe.response': true,\n\t\ttool: true,\n\t\tmemory: true\n\t},\n\tmemory: {\n\t\tuseLocalEmbeddings: false\n\t},\n\tenvFilePath: '.env'\n\t// Other default configuration options can be added here\n};\n\nexport async function loadConfig(): Promise<BaseAIConfig> {\n\tconst explorer = cosmiconfig('baseai', {\n\t\tsearchPlaces: ['baseai/baseai.config.ts'],\n\t\tloaders: {\n\t\t\t'.ts': TypeScriptLoader()\n\t\t}\n\t});\n\ttry {\n\t\tlet result = await explorer.search();\n\t\tif (!result) {\n\t\t\t// throw new Error('No config file found');\n\t\t\tp.cancel('Failed to create config file');\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\t// BaseAI config is expected to be in the config key of the config file\n\t\tconst config = result.config.config;\n\t\tif (config) {\n\t\t\treturn {\n\t\t\t\t...defaultConfig,\n\t\t\t\t...config,\n\t\t\t\tlog: {\n\t\t\t\t\t...defaultConfig.log,\n\t\t\t\t\t...config.log\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t} catch (error) {\n\t\t// console.log(error);\n\t\tp.cancel('Error: Unable to load config file');\n\t\tprocess.exit(1);\n\t}\n\treturn defaultConfig;\n}\n","import { loadConfig } from './config/config-handler';\nimport fs from 'fs/promises';\nimport * as p from '@clack/prompts';\nimport color from 'picocolors';\n\nexport interface Account {\n\tapiKey: string;\n}\n\ntype Spinner = ReturnType<typeof p.spinner>;\n\nfunction handleNoAccountFound({ spinner }: { spinner: Spinner }): void {\n\tspinner.stop('No account found');\n\tp.log.warn('No account found. Please authenticate first.');\n\tp.log.info(`Run: ${color.green('npx baseai auth')}`);\n}\nfunction handleAuthError({\n\tspinner,\n\terror\n}: {\n\tspinner: Spinner;\n\terror: unknown;\n}): void {\n\tspinner.stop('Failed to retrieve authentication');\n\tp.log.error(`Error retrieving stored auth: ${(error as Error).message}`);\n}\n\nexport async function retrieveAuthentication({\n\tspinner\n}: {\n\tspinner: Spinner;\n}): Promise<Account | null> {\n\tspinner.start('Retrieving stored authentication');\n\ttry {\n\t\tconst baiConfig = await loadConfig();\n\t\tlet envFile = baiConfig.envFilePath || '.env';\n\t\tconst envFileContent = await fs.readFile(envFile, 'utf-8');\n\n\t\tconst apiKey = envFileContent\n\t\t\t.split('\\n')\n\t\t\t.reverse()\n\t\t\t.find(line => line.includes('LANGBASE_API_KEY='))\n\t\t\t?.split('=')[1];\n\n\t\tif (!apiKey) {\n\t\t\thandleNoAccountFound({ spinner });\n\t\t\treturn null;\n\t\t}\n\n\t\tspinner.stop('Retrieved stored authentication');\n\n\t\treturn {\n\t\t\tapiKey\n\t\t};\n\t} catch (error) {\n\t\thandleAuthError({ spinner, error });\n\t\treturn null;\n\t}\n}\n","import * as prettier from 'prettier';\n\n/**\n * Formats the given TypeScript code string using Prettier with specified options.\n *\n * @param code - The TypeScript code to format.\n * @returns A promise that resolves to the formatted code string.\n */\nexport async function formatCode(code: string) {\n\treturn await prettier.format(code, {\n\t\tparser: 'typescript',\n\t\tsingleQuote: true,\n\t\ttrailingComma: 'none',\n\t\tarrowParens: 'avoid',\n\t\tprintWidth: 80,\n\t\tuseTabs: true,\n\t\tsemi: true,\n\t\ttabWidth: 4\n\t});\n}\n","import { dim, dimItalic } from '@/utils/formatting';\nimport { getAvailablePipes } from '@/utils/get-available-pipes';\nimport { getAvailableTools } from '@/utils/get-available-tools';\nimport { heading } from '@/utils/heading';\nimport icons from '@/utils/icons';\nimport { isToolPresent } from '@/utils/is-tool-present';\nimport { retrieveAuthentication } from '@/utils/retrieve-credentials';\nimport { formatCode } from '@/utils/ts-format-code';\nimport * as p from '@clack/prompts';\nimport slugify from '@sindresorhus/slugify';\nimport camelCase from 'camelcase';\nimport figures from 'figures';\nimport fs from 'fs';\nimport pMap from 'p-map';\nimport path from 'path';\nimport color from 'picocolors';\nimport type { Pipe } from 'types/pipe';\nimport type { PipeTool } from 'types/tools';\n\ninterface ErrorResponse {\n\terror?: { message: string };\n}\n\ntype Spinner = ReturnType<typeof p.spinner>;\n\n/**\n * Extracts the login name and name from a given pipe-separated string.\n *\n * @param loginAndPipe - login/pipe string to extract from.\n * @returns An object containing the extracted `login` and `name`.\n */\nfunction extractLoginName(loginAndPipe: string) {\n\tif (!loginAndPipe) return { login: '', name: '' };\n\n\tconst split = loginAndPipe.split('/');\n\tconst length = split.length;\n\n\tif (length < 2) return { login: '', name: '' };\n\n\treturn {\n\t\tlogin: split[length - 2],\n\t\tname: split[length - 1]\n\t};\n}\n\n\n/**\n * Fetches a pipe from Langbase using the provided login and name.\n *\n * @param {Object} params - The parameters for fetching the pipe.\n * @param {string} params.login - The login identifier.\n * @param {string} params.name - The name of the pipe.\n * @param {Spinner} params.spinner - The spinner instance for displaying loading status.\n * @returns {Promise<Pipe | null>} - A promise that resolves to the fetched pipe or null if an error occurs.\n */\nasync function getPipe({\n\tlogin,\n\tname,\n\tspinner\n}: {\n\tlogin: string;\n\tname: string;\n\tspinner: Spinner;\n}) {\n\ttry {\n\t\tconst account = await retrieveAuthentication({ spinner });\n\t\tif (!account) {\n\t\t\tp.log.error(\n\t\t\t\t'Authentication failed. Please run \"npx baseai auth\" to authenticate.'\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tspinner.start('Fetching pipe from Langbase');\n\n\t\tconst API_URL = `https://api.langbase.com/v1/pipes/${login}/${name}`;\n\n\t\tconst createResponse = await fetch(API_URL, {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t...(account && { Authorization: `Bearer ${account.apiKey}` })\n\t\t\t}\n\t\t});\n\n\t\tif (createResponse.ok) {\n\t\t\tspinner.stop('Fetched pipe from Langbase');\n\t\t\treturn (await createResponse.json()) as Pipe;\n\t\t}\n\n\t\tconst errorData = (await createResponse.json()) as ErrorResponse;\n\n\t\tif (errorData) {\n\t\t\tspinner.stop(\n\t\t\t\t`Failed to fetch pipe from Langbase: ${errorData.error?.message}`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t} catch (error: any) {\n\t\tspinner.stop(error);\n\t\treturn null;\n\t}\n}\n\n/**\n * Asynchronously creates local tools based on the provided `Pipe` object.\n *\n * @param {Pipe} pipe - The pipe object containing tools to be created.\n *\n * The function performs the following steps:\n * 1. Checks if there are any tools in the `pipe`. If none, it returns immediately.\n * 2. Retrieves all available tools.\n * 3. Iterates over each tool in the `pipe` and checks if the tool is already present.\n * 4. If the tool is present, prompts the user to confirm if they want to overwrite the existing tool.\n * 5. If the user chooses not to overwrite, the tool creation is skipped.\n * 6. If the tool is not present or the user chooses to overwrite, the tool's code is generated and formatted.\n * 7. The formatted code is then written to a file in the `baseai/tools` directory.\n * 8. If any error occurs during the process, it is caught and an appropriate message is displayed.\n */\nasync function createLocalTool(pipe: Pipe) {\n\tif (!pipe.tools.length) return;\n\tconst allTools = await getAvailableTools();\n\n\ttry {\n\t\tawait pMap(\n\t\t\tpipe.tools,\n\t\t\tasync tool => {\n\t\t\t\tconst hasTool = isToolPresent({\n\t\t\t\t\tname: tool.function.name,\n\t\t\t\t\tallTools\n\t\t\t\t});\n\n\t\t\t\tif (hasTool) {\n\t\t\t\t\tconst toolInfo = await p.group(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toverwrite: () =>\n\t\t\t\t\t\t\t\tp.confirm({\n\t\t\t\t\t\t\t\t\tmessage: `${color.dim(icons.tool)} Tool: ${color.cyan(tool.function.name)} already exists. Do you want to overwrite it?`,\n\t\t\t\t\t\t\t\t\tinitialValue: false\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\t\t\t\t\tprocess.exit(0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\n\t\t\t\t\tif (!toolInfo.overwrite) {\n\t\t\t\t\t\tp.outro(`Skipped …`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst name = tool.function.name;\n\t\t\t\tconst camelCaseName = camelCase(name);\n\t\t\t\tconst slugifiedName = slugify(name);\n\n\t\t\t\tconst code = `import { ToolI } from '@baseai/core';\n\n\t\t\texport async function ${name}() {\n\t\t\t\t// Your tool logic here\n\t\t\t}\n\n\t\t\tconst ${camelCaseName}Tool = (): ToolI => ({\n\t\t\t\trun: ${name}, // Name of the function to run\n\t\t\t\ttype: 'function' as const,\n\t\t\t\tfunction: {\n\t\t\t\t\tname: \\`${name}\\`,\n\t\t\t\t\tdescription: \\`${tool.function.description}\\`,\n\t\t\t\t\tparameters: ${JSON.stringify(tool.function.parameters || {}, null, 6)}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\texport default ${camelCaseName}Tool;`;\n\n\t\t\t\tconst formattedCode = await formatCode(code);\n\n\t\t\t\tconst baseDir = path.join(process.cwd(), 'baseai', 'tools');\n\t\t\t\tconst filePath = path.join(baseDir, `${slugifiedName}.ts`);\n\n\t\t\t\tawait fs.promises.mkdir(baseDir, { recursive: true });\n\t\t\t\tawait fs.promises.writeFile(filePath, formattedCode);\n\t\t\t\tp.outro(`Tool created successfully at ${filePath}`);\n\t\t\t},\n\t\t\t{ concurrency: 1 }\n\t\t);\n\t} catch (error: any) {\n\t\tp.cancel(`Error creating tool: ${error.message}`);\n\t}\n}\n\n/**\n * Transforms an array of `PipeTool` objects into an array of objects containing\n * tool call strings, import paths, and tool file names.\n *\n * @param tools - An array of `PipeTool` objects to be transformed.\n * @returns An array of objects, each containing:\n * - `toolCall`: A string representing the tool call.\n * - `importPath`: A string representing the import path for the tool.\n * - `toolFileName`: A string representing the file name of the tool.\n */\nfunction getToolsPipeData(tools: PipeTool[]) {\n\treturn tools.map(tool => {\n\t\tconst toolFileName = slugify(tool.function.name);\n\t\tconst toolName = `${camelCase(tool.function.name)}Tool`;\n\t\tconst importPath = `import ${toolName} from '../tools/${toolFileName}';`;\n\n\t\treturn {\n\t\t\ttoolCall: `${toolName}()`,\n\t\t\timportPath,\n\t\t\ttoolFileName\n\t\t};\n\t});\n}\n\n/**\n * Asynchronously creates a local pipe configuration file.\n *\n * This function performs the following steps:\n * 1. Retrieves all available pipes.\n * 2. Slugifies the provided pipe name.\n * 3. Checks if a pipe with the same name already exists.\n * 4. If the pipe exists, prompts the user to confirm overwriting the existing pipe.\n * 5. If the user chooses not to overwrite, the operation is skipped.\n * 6. Retrieves tool data for the provided pipe tools.\n * 7. Constructs the pipe content with the provided pipe details and tool data.\n * 8. Formats the generated pipe content.\n * 9. Creates the necessary directories and writes the formatted pipe content to a file.\n * 10. Outputs a success message upon successful creation of the pipe.\n *\n * @param {Pipe} pipe - The pipe object containing configuration details.\n * @returns {Promise<void>} - A promise that resolves when the pipe is successfully created.\n */\nasync function createLocalPipe(pipe: Pipe) {\n\ttry {\n\t\tconst allPipes = await getAvailablePipes();\n\n\t\tconst pipeNameSlugified = slugify(pipe.name);\n\n\t\tconst hasPipe = allPipes.some(p => p === pipeNameSlugified);\n\n\t\tif (hasPipe) {\n\t\t\tconst pipeInfo = await p.group(\n\t\t\t\t{\n\t\t\t\t\toverwrite: () =>\n\t\t\t\t\t\tp.confirm({\n\t\t\t\t\t\t\tmessage: `PIPE: ${color.cyan(pipe.name)} already exists. Do you want to overwrite it?`,\n\t\t\t\t\t\t\tinitialValue: false\n\t\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\t\t\tprocess.exit(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tif (!pipeInfo.overwrite) {\n\t\t\t\tp.outro(`Skipped …`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst toolData = await getToolsPipeData(pipe.tools);\n\n\t\tconst toolCalls = toolData.map(tool => tool.toolCall);\n\t\tconst pipeNameCamelCase = camelCase('pipe-' + pipe.name);\n\n\t\tconst messages = pipe.messages.map(message => ({\n\t\t\t...(message.name && { name: message.name }),\n\t\t\trole: message.role,\n\t\t\tcontent: message.content\n\t\t}));\n\n\t\tconst pipeContent = `import { PipeI } from '@baseai/core';\n${toolData.map(tool => tool.importPath).join('\\n')}\n\n\t\tconst ${pipeNameCamelCase} = (): PipeI => ({\n\t\t\t// Replace with your API key https://langbase.com/docs/api-reference/api-keys\n\t\t\tapiKey: process.env.LANGBASE_API_KEY!,\n\t\t\tname: \\`${pipe.name}\\`,\n\t\t\tdescription: \\`${pipe.description}\\`,\n\t\t\tstatus: \\`${pipe.status}\\`,\n\t\t\tmodel: \\`${pipe.model}\\`,\n\t\t\tstream: ${pipe.stream},\n\t\t\tjson: ${pipe.json},\n\t\t\tstore: ${pipe.store},\n\t\t\tmoderate: ${pipe.moderate || true},\n\t\t\ttop_p: ${pipe.top_p},\n\t\t\tmax_tokens: ${pipe.max_tokens},\n\t\t\ttemperature: ${pipe.temperature},\n\t\t\tpresence_penalty: ${pipe.presence_penalty},\n\t\t\tfrequency_penalty: ${pipe.frequency_penalty},\n\t\t\tstop: ${JSON.stringify(pipe.stop)},\n\t\t\ttool_choice: ${JSON.stringify(pipe.tool_choice)},\n\t\t\tparallel_tool_calls: ${pipe.parallel_tool_calls},\n\t\t\tmessages: ${JSON.stringify(messages || [])},\n\t\t\tvariables: ${JSON.stringify(pipe.variables)},\n\t\t\ttools: [${toolCalls}],\n\t\t\tmemory: [],\n\t\t});\n\n\t\texport default ${pipeNameCamelCase};`;\n\n\t\tconst formattedCode = await formatCode(pipeContent);\n\n\t\tconst baseDir = path.join(process.cwd(), 'baseai', 'pipes');\n\t\tconst filePath = path.join(baseDir, `${pipeNameSlugified}.ts`);\n\n\t\tawait fs.promises.mkdir(baseDir, { recursive: true });\n\t\tawait fs.promises.writeFile(filePath, formattedCode);\n\t\tp.outro(`Pipe created successfully at ${filePath}`);\n\t\tp.outro(\n\t\t\theading({\n\t\t\t\ttext: pipeNameSlugified,\n\t\t\t\tsub: `pipe added \\n ${dim(figures.pointer)} ${dimItalic(` ${filePath}`)}`,\n\t\t\t\tgreen: true\n\t\t\t})\n\t\t);\n\t\tprocess.exit(0);\n\t} catch (error: any) {\n\t\tp.cancel(`Error creating pipe: ${error.message}`);\n\t}\n}\n\n/**\n * Adds a pipe by extracting login and name from the provided pipe information,\n * fetching the pipe details, and creating local tool and pipe.\n *\n * @param {Object} params - The parameters for the function.\n * @param {string} params.pipeInfo - The pipe information string.\n * @returns {Promise<void>} - A promise that resolves when the pipe is added.\n */\nexport async function addPipe({ loginAndPipe }: { loginAndPipe: string }) {\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'PIPE',\n\t\t\tsub: `Adding ${color.cyan(loginAndPipe)}`\n\t\t})\n\t);\n\n\tconst { login, name } = extractLoginName(loginAndPipe);\n\n\tif (!login || !name) {\n\t\tp.log.error('Invalid pipe information provided');\n\t\treturn;\n\t}\n\n\tconst spinner = p.spinner();\n\n\ttry {\n\t\tconst pipe = await getPipe({ login, name, spinner });\n\t\tif (!pipe) return;\n\n\t\tawait createLocalTool(pipe);\n\t\tawait createLocalPipe(pipe);\n\t} catch (error: any) {\n\t\tspinner.stop('An unexpected error occurred');\n\t\tp.log.error(\n\t\t\t`'An unexpected error occurred': ${(error as Error).message}`\n\t\t);\n\t}\n}\n","import { loadConfig } from '@/utils/config/config-handler';\nimport { heading } from '@/utils/heading';\nimport * as p from '@clack/prompts';\nimport {\n\tcancel,\n\tconfirm,\n\tisCancel,\n\tnote,\n\toutro,\n\tpassword\n} from '@clack/prompts';\nimport fs from 'fs/promises';\nimport open from 'open';\nimport path from 'path';\nimport color from 'picocolors';\n\nexport async function auth() {\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'Langbase Authentication',\n\t\t\tsub: 'Auth by logging in to Langbase and getting your API key'\n\t\t})\n\t);\n\n\tconst shouldOpen = await confirm({\n\t\tmessage: `Open the authentication page? ${color.dim(`— copy your API key from there and paste it here.`)}`\n\t});\n\n\tif (isCancel(shouldOpen)) {\n\t\tcancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\n\tif (shouldOpen) {\n\t\tawait open('https://langbase.com/settings/api');\n\n\t\tnote(\n\t\t\tcolor.yellow(\n\t\t\t\t'Please copy your API key from the opened page and paste it here.'\n\t\t\t)\n\t\t);\n\t}\n\n\tconst apiKeyString = await password({\n\t\tmessage: 'Paste your API key string:',\n\t\tmask: '*'\n\t});\n\n\tif (isCancel(apiKeyString)) {\n\t\tcancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\n\tconst [login, apiKey] = (apiKeyString as string).split(':');\n\n\tif (!login || !apiKey) {\n\t\toutro(\n\t\t\tcolor.red(\n\t\t\t\t'Invalid API key string. It should be in the format login:apiKey, when copied from https://langbase.com/settings/api it should be in the correct format.'\n\t\t\t)\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\tconst envKeyName = 'LANGBASE_API_KEY';\n\tconst envContent = `\\n# Langbase API key for https://langbase.com/${login}\\n${envKeyName}=${apiKey}\\n\\n`;\n\n\t// TODO: Do we need this now?\n\t// const envFiles = ['.env', '.env.local', '.dev.vars'];\n\t// let envFile = envFiles.find(file =>\n\t// \tfs.existsSync(path.join(process.cwd(), file))\n\t// );\n\n\t// if (!envFile) {\n\t// \tenvFile = '.env';\n\t// }\n\n\tconst baiConfig = await loadConfig();\n\tlet envFile = baiConfig.envFilePath || '.env';\n\n\tconst envFileContent = await fs.readFile(envFile, 'utf-8');\n\n\tconst oldKey = envFileContent\n\t\t.split('\\n')\n\t\t.reverse() // Reverse to get the latest key if there are multiple\n\t\t.find(line => line.includes('LANGBASE_API_KEY'))\n\t\t?.split('=')[1];\n\n\tif (oldKey) {\n\t\tconst shouldOverwrite = await confirm({\n\t\t\tmessage: `API key found in ${envFile}. Overwrite?`\n\t\t});\n\n\t\tif (isCancel(shouldOverwrite)) {\n\t\t\tcancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\tif (!shouldOverwrite) {\n\t\t\toutro(\n\t\t\t\tcolor.yellow('API key is not overwritten.')\n\t\t\t);\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\tconst newEnvContent = envFileContent.replace(\n\t\t\tnew RegExp(`LANGBASE_API_KEY=${oldKey}`),\n\t\t\tenvContent.trim()\n\t\t);\n\n\t\tawait fs.writeFile(path.join(process.cwd(), envFile), newEnvContent);\n\t} else {\n\t\tawait fs.appendFile(path.join(process.cwd(), envFile), envContent);\n\t}\n\n\toutro(\n\t\tcolor.green(\n\t\t\t`Authentication successful. API key is stored in ${envFile}`\n\t\t)\n\t);\n\tprocess.exit(0);\n}\n","import { heading } from '@/utils/heading';\nimport icons from '@/utils/icons';\nimport * as p from '@clack/prompts';\nimport { exec } from 'child_process';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nasync function build({ calledAsCommand }: { calledAsCommand?: boolean }) {\n\ttry {\n\t\tcalledAsCommand &&\n\t\t\tp.intro(heading({ text: 'BUILDING', sub: 'baseai...' }));\n\n\t\tawait buildPipes();\n\t\tawait buildTools();\n\t\tawait buildMemory();\n\n\t\tconsole.log('');\n\t\tp.outro(heading({ text: 'BUILD', sub: 'complete', green: true }));\n\t} catch (error) {\n\t\tp.log.error('Build failed');\n\t\tthrow error;\n\t}\n}\n\nexport default build;\n\nconst buildPipes = async () => {\n\tconsole.log('');\n\tp.intro(heading({ text: 'PIPES', sub: '', dim: true }));\n\n\tconst sourcePath = path.join(process.cwd(), 'baseai', 'pipes');\n\tconst outputPath = path.join(process.cwd(), '.baseai', 'pipes');\n\n\tconst builtPipes = await buildTypeScriptFiles(\n\t\tsourcePath,\n\t\toutputPath,\n\t\t'pipes'\n\t);\n\tlistBuiltItems('Pipes', builtPipes, icons.pipe);\n};\n\nconst buildTools = async () => {\n\tconsole.log('');\n\tp.intro(heading({ text: 'TOOLS', sub: '', dim: true }));\n\n\tconst sourcePath = path.join(process.cwd(), 'baseai', 'tools');\n\tconst outputPath = path.join(process.cwd(), '.baseai', 'tools');\n\n\tconst builtTools = await buildTypeScriptFiles(\n\t\tsourcePath,\n\t\toutputPath,\n\t\t'tools'\n\t);\n\tlistBuiltItems('Tools', builtTools, icons.tool);\n};\n\nexport const buildMemory = async ({\n\tmemoryName\n}: { memoryName?: string } = {}) => {\n\tconsole.log('');\n\tp.intro(heading({ text: 'MEMORY', sub: '', dim: true }));\n\n\tconst sourcePath = path.join(process.cwd(), 'baseai', 'memory');\n\tconst outputPath = path.join(process.cwd(), '.baseai', 'memory');\n\n\ttry {\n\t\tawait fs.access(sourcePath);\n\t} catch (error) {\n\t\tp.log.info('No memory directory found. Skipping memory build.');\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait fs.access(outputPath);\n\t} catch (error) {\n\t\t// Create the build memory directory if it doesn't exist\n\t\tawait fs.mkdir(outputPath, { recursive: true });\n\t}\n\n\tconst builtMemories: string[] = [];\n\tconst s = p.spinner();\n\tlet tsFiles: string[] = [];\n\n\t// If a memoryName is provided, build only that memory\n\tif (memoryName) {\n\t\ttsFiles = await getSingleMemoryFile({ sourcePath, memoryName });\n\t}\n\n\t// If no memoryName is provided, build all memories\n\tif (!memoryName) {\n\t\ttsFiles = await getAllMemoryFile(sourcePath);\n\n\t\tif (tsFiles.length === 0) {\n\t\t\tp.log.info(\n\t\t\t\t'MEMORY: No index.ts file found. Skipping memory build.'\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t}\n\n\ts.start('Building memory');\n\n\tfor (const file of tsFiles) {\n\t\tconst inputFile = path.join(sourcePath, file);\n\t\tconst outputFile = path.join(outputPath, `${path.dirname(file)}.json`);\n\t\tconst displayName = path.dirname(file); // This is the last directory name\n\t\ttry {\n\t\t\tconst { stdout } = await execAsync(\n\t\t\t\t`npx tsx -e \"import memoryConfig from '${JSON.stringify(inputFile)}'; console.log(JSON.stringify(memoryConfig()))\"`\n\t\t\t);\n\n\t\t\tawait fs.writeFile(outputFile, stdout);\n\t\t\ts.message(`Compiled ${displayName}`);\n\t\t\tbuiltMemories.push(displayName);\n\t\t} catch (error) {\n\t\t\ts.stop(`Error compiling ${displayName}: ${error}`);\n\t\t}\n\t}\n\n\ts.stop('Build complete');\n\tlistBuiltItems('Memories', builtMemories, icons.memory);\n};\n\nconst buildTypeScriptFiles = async (\n\tsourcePath: string,\n\toutputPath: string,\n\ttype: string\n): Promise<string[]> => {\n\ttry {\n\t\tawait fs.access(sourcePath);\n\t} catch (error) {\n\t\tp.log.info(`No ${type} directory found. Skipping ${type} build.`);\n\t\treturn [];\n\t}\n\n\tawait fs.mkdir(outputPath, { recursive: true });\n\n\tconst files = await fs.readdir(sourcePath);\n\tconst tsFiles = files.filter(file => file.endsWith('.ts'));\n\n\tif (tsFiles.length === 0) {\n\t\tp.log.info(\n\t\t\t`No .ts files found in the ${type} directory. Skipping ${type} build.`\n\t\t);\n\t\treturn [];\n\t}\n\n\tconst s = p.spinner();\n\ts.start(`Building ${type}`);\n\n\tconst builtItems: string[] = [];\n\n\tfor (const file of tsFiles) {\n\t\tconst inputFile = path.join(sourcePath, file);\n\t\tconst outputFile = path.join(outputPath, file.replace('.ts', '.json'));\n\t\tconst displayName = path.parse(file).name; // File name without extension\n\n\t\ttry {\n\t\t\tconst { stdout } = await execAsync(\n\t\t\t\t`npx tsx -e \"import config from '${JSON.stringify(inputFile)}'; console.log(JSON.stringify(config()))\"`\n\t\t\t);\n\n\t\t\t// Parse the JSON output\n\t\t\tlet configObject = JSON.parse(stdout);\n\n\t\t\t// Remove the apiKey if it exists\n\t\t\tif ('apiKey' in configObject) {\n\t\t\t\tdelete configObject.apiKey;\n\t\t\t}\n\n\t\t\t// Stringify the modified object back to JSON\n\t\t\tconst modifiedOutput = JSON.stringify(configObject, null, 2);\n\n\t\t\tawait fs.writeFile(outputFile, modifiedOutput);\n\t\t\ts.message(`Compiled ${displayName}`);\n\t\t\tbuiltItems.push(displayName);\n\t\t} catch (error) {\n\t\t\ts.stop(`Error compiling ${displayName}: ${error}`);\n\t\t}\n\t}\n\n\ts.stop(`Build complete`);\n\treturn builtItems;\n};\n\nconst listBuiltItems = (title: string, items: string[], icon: string) => {\n\tif (items.length > 0) {\n\t\titems.forEach(item => {\n\t\t\tconsole.log(`${icon}  ${item}`);\n\t\t});\n\t} else {\n\t\t// console.log(`\\nNo ${title.toLowerCase()} were built.`);\n\t}\n};\n\nasync function getSingleMemoryFile({\n\tsourcePath,\n\tmemoryName\n}: {\n\tsourcePath: string;\n\tmemoryName: string;\n}) {\n\t// Array to store the paths of the memory files\n\tconst tsFiles: string[] = [];\n\n\tconst memoryPath = path.join(sourcePath, memoryName);\n\n\t// Get all files in the memory directory\n\tconst files = await fs.readdir(memoryPath);\n\tconst indexFile = files.find(file => file === 'index.ts');\n\n\t// If no index.ts file is found, no memory entry file exists. Skip the build.\n\tif (!indexFile) {\n\t\tp.log.info('MEMORY: No index.ts file found. Skipping memory build.');\n\t\tprocess.exit(1); // Exiting process because it is a single memory build.\n\t}\n\n\ttsFiles.push(path.join(memoryName, indexFile));\n\n\treturn tsFiles;\n}\n\nasync function getAllMemoryFile(sourcePath: string) {\n\t// Array to store the paths of the memory files\n\tlet tsFiles: string[] = [];\n\n\t// Get all folders in the memory directory\n\tconst filesBaseDir = await fs.readdir(sourcePath);\n\n\t// Get only folders in the memory directory\n\tconst folderPromises = filesBaseDir.map(async file => {\n\t\tconst filePath = path.join(sourcePath, file);\n\t\tconst stats = await fs.stat(filePath);\n\t\treturn stats.isDirectory() ? file : '';\n\t});\n\n\tlet allMemoryFolders = await Promise.all(folderPromises);\n\n\t// Remove empty strings from the array\n\tallMemoryFolders = allMemoryFolders.filter(folder => folder !== '');\n\n\tif (allMemoryFolders.length === 0) {\n\t\tp.log.info('MEMORY: No memory found. Skipping memory build.');\n\t\treturn [];\n\t}\n\n\t// Get all index.ts files in the all the memory folders\n\tconst tsFilesPromise = allMemoryFolders.map(async memory => {\n\t\tconst filePath = path.join(sourcePath, memory);\n\t\tconst files = await fs.readdir(filePath);\n\t\tconst indexFile = files.find(file => file === 'index.ts');\n\n\t\t// if index file, return the memory/index.ts path\n\t\treturn indexFile ? path.join(memory, indexFile) : '';\n\t});\n\n\t// Wait for all the promises to resolve\n\ttsFiles = await Promise.all(tsFilesPromise);\n\n\t// Remove empty strings from the array\n\ttsFiles = tsFiles.filter(file => file !== '');\n\n\treturn tsFiles;\n}\n","export const OPEN_AI: string = 'OpenAI';\nexport const ANTHROPIC: string = 'Anthropic';\nexport const TOGETHER_AI: string = 'Together';\nexport const GOOGLE: string = 'Google';\nexport const GROQ: string = 'Groq';\nexport const COHERE: string = 'Cohere';\nexport const FIREWORKS_AI: string = 'Fireworks AI';\nexport const PERPLEXITY: string = 'Perplexity';\nexport const MISTRAL_AI: string = 'Mistral AI';\nexport const DEEPINFRA: string = 'deepinfra';\nexport const BEDROCK: string = 'bedrock';\nexport const AZURE_OPEN_AI: string = 'azure-openai';\nexport const OLLAMA: string = 'ollama';\nexport const X_AI: string = 'xAI';\n\ninterface Model {\n\tid: string;\n\tprovider: string;\n\tpromptCost: number;\n\tcompletionCost: number;\n\trequestCost?: number;\n\ttoolSupport?: {\n\t\ttoolChoice: boolean;\n\t\tparallelToolCalls: boolean;\n\t};\n}\n\ninterface ModelsByProviderInclCosts {\n\t[provider: string]: Model[];\n}\n\nexport const modelsByProvider: ModelsByProviderInclCosts = {\n\t[OPEN_AI]: [\n\t\t{\n\t\t\tid: 'gpt-4o',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 5.0,\n\t\t\tcompletionCost: 15.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4o-2024-08-06',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 2.5,\n\t\t\tcompletionCost: 10.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4o-mini',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 0.15,\n\t\t\tcompletionCost: 0.6,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-turbo',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-turbo-preview',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-0125-preview',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-1106-preview',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 30.0,\n\t\t\tcompletionCost: 60.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-0613',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 30.0,\n\t\t\tcompletionCost: 60.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-32k',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 60.0,\n\t\t\tcompletionCost: 120.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo-0125',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo-1106',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 1.0,\n\t\t\tcompletionCost: 2.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo-16k',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 3.0,\n\t\t\tcompletionCost: 4.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t}\n\t],\n\t[TOGETHER_AI]: [\n\t\t{\n\t\t\tid: 'meta-llama/Llama-3.3-70B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.88,\n\t\t\tcompletionCost: 0.88,\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 5,\n\t\t\tcompletionCost: 5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.88,\n\t\t\tcompletionCost: 0.88,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.18,\n\t\t\tcompletionCost: 0.18,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-3-70b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-3-8b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'togethercomputer/Llama-2-7B-32K-Instruct',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-2-13b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.225,\n\t\t\tcompletionCost: 0.225\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-2-70b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t},\n\t\t{\n\t\t\tid: 'google/gemma-7b-it',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'google/gemma-2b-it',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.1,\n\t\t\tcompletionCost: 0.1\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mistral-7B-Instruct-v0.1',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mistral-7B-Instruct-v0.2',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mixtral-8x7B-Instruct-v0.1',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.6,\n\t\t\tcompletionCost: 0.6,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mixtral-8x22B-Instruct-v0.1',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 1.2,\n\t\t\tcompletionCost: 1.2\n\t\t},\n\t\t{\n\t\t\tid: 'databricks/dbrx-instruct',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 1.2,\n\t\t\tcompletionCost: 1.2\n\t\t}\n\t],\n\t[ANTHROPIC]: [\n\t\t{\n\t\t\tid: 'claude-3-5-sonnet-latest',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-5-sonnet-20240620',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-opus-20240229',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 15,\n\t\t\tcompletionCost: 75,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-sonnet-20240229',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-haiku-20240307',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 0.25,\n\t\t\tcompletionCost: 1.25,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-5-haiku-20241022',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 1,\n\t\t\tcompletionCost: 5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t}\n\t],\n\t[GROQ]: [\n\t\t{\n\t\t\tid: 'llama-3.3-70b-versatile',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79,\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-70b-versatile',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-8b-instant',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79\n\t\t},\n\t\t{\n\t\t\tid: 'llama3-70b-8192',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79\n\t\t},\n\t\t{\n\t\t\tid: 'llama3-8b-8192',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.05,\n\t\t\tcompletionCost: 0.1\n\t\t},\n\t\t{\n\t\t\tid: 'mixtral-8x7b-32768',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.27,\n\t\t\tcompletionCost: 0.27\n\t\t},\n\t\t{\n\t\t\tid: 'gemma2-9b-it',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'gemma-7b-it',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.07,\n\t\t\tcompletionCost: 0.07\n\t\t}\n\t],\n\t[GOOGLE]: [\n\t\t{\n\t\t\tid: 'gemini-1.5-pro-latest',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 3.5,\n\t\t\tcompletionCost: 10.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gemini-1.5-flash-latest',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 0.075,\n\t\t\tcompletionCost: 0.3,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gemini-1.5-flash-8b-latest',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 0.0375,\n\t\t\tcompletionCost: 0.15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gemini-pro',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: false,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t}\n\t],\n\t[COHERE]: [\n\t\t{\n\t\t\tid: 'command-r',\n\t\t\tprovider: COHERE,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5\n\t\t},\n\t\t{\n\t\t\tid: 'command-r-plus',\n\t\t\tprovider: COHERE,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15\n\t\t}\n\t],\n\t[FIREWORKS_AI]: [\n\t\t{\n\t\t\tid: 'llama-v3p3-70b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.88,\n\t\t\tcompletionCost: 0.88,\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3p1-405b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 3\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3p1-70b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3p1-8b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'yi-large',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 3\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3-70b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t}\n\t],\n\t[PERPLEXITY]: [\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-huge-128k-online',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 5,\n\t\t\tcompletionCost: 5,\n\t\t\trequestCost: 0.005\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-large-128k-online',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 1,\n\t\t\tcompletionCost: 1,\n\t\t\trequestCost: 0.005\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-small-128k-online',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2,\n\t\t\trequestCost: 0.005\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-large-128k-chat',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 1,\n\t\t\tcompletionCost: 1\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-small-128k-chat',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t}\n\t],\n\t[MISTRAL_AI]: [\n\t\t{\n\t\t\tid: 'mistral-large-latest',\n\t\t\tprovider: MISTRAL_AI,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 9\n\t\t},\n\t\t{\n\t\t\tid: 'open-mistral-nemo',\n\t\t\tprovider: MISTRAL_AI,\n\t\t\tpromptCost: 0.3,\n\t\t\tcompletionCost: 0.3\n\t\t},\n\t\t{\n\t\t\tid: 'codestral-latest',\n\t\t\tprovider: MISTRAL_AI,\n\t\t\tpromptCost: 1,\n\t\t\tcompletionCost: 3\n\t\t}\n\t],\n\t[X_AI]: [\n\t\t{\n\t\t\tid: 'grok-beta',\n\t\t\tprovider: X_AI,\n\t\t\tpromptCost: 5,\n\t\t\tcompletionCost: 15\n\t\t}\n\t]\n};\n\nexport const jsonModeModels = [\n\t'gpt-4o',\n\t'gpt-4o-mini-2024-07-18-free',\n\t'gpt-4o-2024-08-06',\n\t'gpt-4o-mini',\n\t'gpt-4-turbo',\n\t'gpt-4-turbo-preview',\n\t'gpt-4-0125-preview',\n\t'gpt-3.5-turbo',\n\t'gpt-3.5-turbo-0125',\n\t'gpt-3.5-turbo-1106',\n\t'gpt-4-1106-preview',\n\t'mistralai/Mistral-7B-Instruct-v0.1',\n\t'mistralai/Mixtral-8x7B-Instruct-v0.1',\n\t'gemini-1.5-pro-latest',\n\t'gemini-1.5-flash-latest'\n];\n","import chalk from 'chalk';\nimport util from 'util';\n\nconst DEBUG = false;\nconst LOG_SENSITIVE_DATA = false;\n\nconst SENSITIVE_WORDS: readonly string[] = [\n\t'sensitive',\n\t'secret',\n\t'hide',\n\t'private',\n\t'password',\n\t'token',\n\t'key',\n\t'auth',\n\t'authorization',\n\t'redact'\n];\n\nconst formatValue = (value: unknown): string => {\n\tif (typeof value === 'object' && value !== null) {\n\t\treturn util.inspect(value, { colors: true, depth: null });\n\t}\n\tif (typeof value === 'string') {\n\t\treturn chalk.green(`\"${value}\"`);\n\t}\n\tif (typeof value === 'number') {\n\t\treturn chalk.yellow(value.toString());\n\t}\n\tif (typeof value === 'boolean') {\n\t\treturn chalk.cyan(value.toString());\n\t}\n\treturn String(value);\n};\n\nconst isSensitiveData = (key: string): boolean =>\n\tSENSITIVE_WORDS.some(word => key.toLowerCase().includes(word));\n\nconst redactSensitiveData = (value: unknown, isSensitive: boolean): string =>\n\tisSensitive && !LOG_SENSITIVE_DATA\n\t\t? chalk.red('======REDACTED======')\n\t\t: formatValue(value);\n\nconst logKeyValue = (key: string, value: unknown, sensitive?: string): void => {\n\tconst formattedValue = redactSensitiveData(\n\t\tvalue,\n\t\tBoolean(sensitive) && isSensitiveData(sensitive || key)\n\t);\n\tconsole.log(\n\t\t`\\n${chalk.blue('======')} 👀 ${chalk.bold(key)} 👀 ${chalk.blue('======')}`\n\t);\n\tconsole.log(formattedValue);\n};\n\nexport const dlog = (\n\tanyKey: unknown,\n\tanyValue?: unknown,\n\tsensitive?: string\n): void => {\n\tif (!DEBUG) return;\n\n\tif (\n\t\ttypeof anyKey === 'object' &&\n\t\tanyKey !== null &&\n\t\tanyValue === undefined\n\t) {\n\t\tObject.entries(anyKey).forEach(([key, value]) =>\n\t\t\tlogKeyValue(key, value, sensitive || key)\n\t\t);\n\t} else {\n\t\tlogKeyValue(String(anyKey), anyValue, sensitive);\n\t}\n};\n","/**\n * Compares two arrays of documents and determines the relationship between them.\n *\n * @param {Object} params - The parameters for comparing the document lists.\n * @param {string[]} params.localDocs - The array of local documents.\n * @param {string[]} params.prodDocs - The array of production documents.\n *\n * @returns {Object} - An object containing the comparison results.\n * @property {boolean} areListsSame - Indicates whether the document lists are the same.\n * @property {boolean} isProdSubsetOfLocal - Indicates whether the production documents are a subset of the local documents.\n * @property {boolean} isProdSupersetOfLocal - Indicates whether the production documents are a superset of the local documents.\n */\nexport function compareDocumentLists({\n\tlocalDocs,\n\tprodDocs\n}: {\n\tlocalDocs: string[];\n\tprodDocs: string[];\n}) {\n\tconst localSet = new Set(localDocs);\n\tconst prodSet = new Set(prodDocs);\n\n\t// Case 1: Lists are the same\n\tconst areListsSame =\n\t\tlocalSet.size === prodSet.size &&\n\t\tlocalDocs.every(doc => prodSet.has(doc));\n\n\t// Case 2: Prod is a subset of local\n\tconst isProdSubsetOfLocal = prodDocs.every(doc => localSet.has(doc));\n\n\t// Case 3: Prod is a superset of local\n\tconst isProdSupersetOfLocal = localDocs.every(doc => prodSet.has(doc));\n\n\t// Case 4: Lists are totally different\n\tconst areMutuallyExclusive =\n\t\t!localDocs.some(doc => prodSet.has(doc)) &&\n\t\t!prodDocs.some(doc => localSet.has(doc));\n\n\t// Case 5: Partial overlap\n\tconst areOverlapping = localDocs.some(doc => prodSet.has(doc));\n\n\treturn {\n\t\tareListsSame,\n\t\tisProdSubsetOfLocal,\n\t\tisProdSupersetOfLocal,\n\t\tareMutuallyExclusive,\n\t\tareOverlapping\n\t};\n}\n","const generalFileExtSupported = [\n\t'.md',\n\t'.txt',\n\t'.pdf',\n\t'.csv',\n\t'.xlsx',\n\t'.xls'\n];\n\nexport const programmingFilesExtensions = {\n\t'.json': 'JSON',\n\t'.yaml': 'YAML',\n\t'.yml': 'YAML',\n\t'.xml': 'XML',\n\t'.html': 'HTML',\n\t'.htm': 'HTML',\n\t'.abap': 'ABAP',\n\t'.asc': 'AGS Script',\n\t'.ash': 'AGS Script',\n\t'.ampl': 'AMPL',\n\t'.mod': 'Modula-2',\n\t'.g4': 'ANTLR',\n\t'.apl': 'APL',\n\t'.dyalog': 'APL',\n\t'.asp': 'ASP',\n\t'.asax': 'ASP',\n\t'.ascx': 'ASP',\n\t'.ashx': 'ASP',\n\t'.asmx': 'ASP',\n\t'.aspx': 'ASP',\n\t'.axd': 'ASP',\n\t'.dats': 'ATS',\n\t'.hats': 'ATS',\n\t'.sats': 'ATS',\n\t'.as': 'ActionScript',\n\t'.adb': 'Ada',\n\t'.ada': 'Ada',\n\t'.ads': 'Ada',\n\t'.agda': 'Agda',\n\t'.als': 'Alloy',\n\t'.cls': 'Visual Basic',\n\t'.applescript': 'AppleScript',\n\t'.scpt': 'AppleScript',\n\t'.arc': 'Arc',\n\t'.ino': 'Arduino',\n\t'.aj': 'AspectJ',\n\t'.asm': 'Assembly',\n\t'.a51': 'Assembly',\n\t'.inc': 'SourcePawn',\n\t'.nasm': 'Assembly',\n\t'.aug': 'Augeas',\n\t'.ahk': 'AutoHotkey',\n\t'.ahkl': 'AutoHotkey',\n\t'.au3': 'AutoIt',\n\t'.awk': 'Awk',\n\t'.auk': 'Awk',\n\t'.gawk': 'Awk',\n\t'.mawk': 'Awk',\n\t'.nawk': 'Awk',\n\t'.bat': 'Batchfile',\n\t'.cmd': 'Batchfile',\n\t'.befunge': 'Befunge',\n\t'.bison': 'Bison',\n\t'.bb': 'BlitzBasic',\n\t'.decls': 'BlitzBasic',\n\t'.bmx': 'BlitzMax',\n\t'.bsv': 'Bluespec',\n\t'.boo': 'Boo',\n\t'.b': 'Limbo',\n\t'.bf': 'HyPhy',\n\t'.brs': 'Brightscript',\n\t'.bro': 'Bro',\n\t'.c': 'C',\n\t'.cats': 'C',\n\t'.h': 'Objective-C',\n\t'.idc': 'C',\n\t'.w': 'C',\n\t'.cs': 'Smalltalk',\n\t'.cake': 'CoffeeScript',\n\t'.cshtml': 'C#',\n\t'.csx': 'C#',\n\t'.cpp': 'C++',\n\t'.c++': 'C++',\n\t'.cc': 'C++',\n\t'.cp': 'Component Pascal',\n\t'.cxx': 'C++',\n\t'.h++': 'C++',\n\t'.hh': 'Hack',\n\t'.hpp': 'C++',\n\t'.hxx': 'C++',\n\t'.inl': 'C++',\n\t'.ipp': 'C++',\n\t'.tcc': 'C++',\n\t'.tpp': 'C++',\n\t'.chs': 'C2hs Haskell',\n\t'.clp': 'CLIPS',\n\t'.cmake': 'CMake',\n\t'.cmake.in': 'CMake',\n\t'.cob': 'COBOL',\n\t'.cbl': 'COBOL',\n\t'.ccp': 'COBOL',\n\t'.cobol': 'COBOL',\n\t'.cpy': 'COBOL',\n\t'.capnp': \"Cap'n Proto\",\n\t'.mss': 'CartoCSS',\n\t'.ceylon': 'Ceylon',\n\t'.chpl': 'Chapel',\n\t'.ch': 'xBase',\n\t'.ck': 'ChucK',\n\t'.cirru': 'Cirru',\n\t'.clw': 'Clarion',\n\t'.icl': 'Clean',\n\t'.dcl': 'Clean',\n\t'.click': 'Click',\n\t'.clj': 'Clojure',\n\t'.boot': 'Clojure',\n\t'.cl2': 'Clojure',\n\t'.cljc': 'Clojure',\n\t'.cljs': 'Clojure',\n\t'.cljs.hl': 'Clojure',\n\t'.cljscm': 'Clojure',\n\t'.cljx': 'Clojure',\n\t'.hic': 'Clojure',\n\t'.coffee': 'CoffeeScript',\n\t'._coffee': 'CoffeeScript',\n\t'.cjsx': 'CoffeeScript',\n\t'.cson': 'CoffeeScript',\n\t'.iced': 'CoffeeScript',\n\t'.cfm': 'ColdFusion',\n\t'.cfml': 'ColdFusion',\n\t'.cfc': 'ColdFusion CFC',\n\t'.lisp': 'NewLisp',\n\t'.asd': 'Common Lisp',\n\t'.cl': 'OpenCL',\n\t'.l': 'PicoLisp',\n\t'.lsp': 'NewLisp',\n\t'.ny': 'Common Lisp',\n\t'.podsl': 'Common Lisp',\n\t'.sexp': 'Common Lisp',\n\t'.cps': 'Component Pascal',\n\t'.coq': 'Coq',\n\t'.v': 'Verilog',\n\t'.cr': 'Crystal',\n\t'.feature': 'Cucumber',\n\t'.cu': 'Cuda',\n\t'.cuh': 'Cuda',\n\t'.cy': 'Cycript',\n\t'.pyx': 'Cython',\n\t'.pxd': 'Cython',\n\t'.pxi': 'Cython',\n\t'.d': 'Makefile',\n\t'.di': 'D',\n\t'.com': 'DIGITAL Command Language',\n\t'.dm': 'DM',\n\t'.dart': 'Dart',\n\t'.djs': 'Dogescript',\n\t'.dylan': 'Dylan',\n\t'.dyl': 'Dylan',\n\t'.intr': 'Dylan',\n\t'.lid': 'Dylan',\n\t'.E': 'E',\n\t'.ecl': 'ECLiPSe',\n\t'.eclxml': 'ECL',\n\t'.e': 'Eiffel',\n\t'.ex': 'Elixir',\n\t'.exs': 'Elixir',\n\t'.elm': 'Elm',\n\t'.el': 'Emacs Lisp',\n\t'.emacs': 'Emacs Lisp',\n\t'.emacs.desktop': 'Emacs Lisp',\n\t'.em': 'EmberScript',\n\t'.emberscript': 'EmberScript',\n\t'.erl': 'Erlang',\n\t'.es': 'JavaScript',\n\t'.escript': 'Erlang',\n\t'.hrl': 'Erlang',\n\t'.xrl': 'Erlang',\n\t'.yrl': 'Erlang',\n\t'.fs': 'GLSL',\n\t'.fsi': 'F#',\n\t'.fsx': 'F#',\n\t'.fx': 'HLSL',\n\t'.flux': 'FLUX',\n\t'.f90': 'FORTRAN',\n\t'.f': 'Forth',\n\t'.f03': 'FORTRAN',\n\t'.f08': 'FORTRAN',\n\t'.f77': 'FORTRAN',\n\t'.f95': 'FORTRAN',\n\t'.for': 'Forth',\n\t'.fpp': 'FORTRAN',\n\t'.factor': 'Factor',\n\t'.fy': 'Fancy',\n\t'.fancypack': 'Fancy',\n\t'.fan': 'Fantom',\n\t'.fth': 'Forth',\n\t'.4th': 'Forth',\n\t'.forth': 'Forth',\n\t'.fr': 'Frege',\n\t'.frt': 'Forth',\n\t'.ftl': 'FreeMarker',\n\t'.gms': 'GAMS',\n\t'.g': 'GAP',\n\t'.gap': 'GAP',\n\t'.gd': 'GDScript',\n\t'.gi': 'GAP',\n\t'.tst': 'Scilab',\n\t'.s': 'GAS',\n\t'.ms': 'MAXScript',\n\t'.glsl': 'GLSL',\n\t'.fp': 'GLSL',\n\t'.frag': 'JavaScript',\n\t'.frg': 'GLSL',\n\t'.fsh': 'GLSL',\n\t'.fshader': 'GLSL',\n\t'.geo': 'GLSL',\n\t'.geom': 'GLSL',\n\t'.glslv': 'GLSL',\n\t'.gshader': 'GLSL',\n\t'.shader': 'GLSL',\n\t'.vert': 'GLSL',\n\t'.vrx': 'GLSL',\n\t'.vsh': 'GLSL',\n\t'.vshader': 'GLSL',\n\t'.gml': 'Game Maker Language',\n\t'.kid': 'Genshi',\n\t'.ebuild': 'Gentoo Ebuild',\n\t'.eclass': 'Gentoo Eclass',\n\t'.glf': 'Glyph',\n\t'.gp': 'Gnuplot',\n\t'.gnu': 'Gnuplot',\n\t'.gnuplot': 'Gnuplot',\n\t'.plot': 'Gnuplot',\n\t'.plt': 'Gnuplot',\n\t'.go': 'Go',\n\t'.golo': 'Golo',\n\t'.gs': 'JavaScript',\n\t'.gst': 'Gosu',\n\t'.gsx': 'Gosu',\n\t'.vark': 'Gosu',\n\t'.grace': 'Grace',\n\t'.gf': 'Grammatical Framework',\n\t'.groovy': 'Groovy',\n\t'.grt': 'Groovy',\n\t'.gtpl': 'Groovy',\n\t'.gvy': 'Groovy',\n\t'.gsp': 'Groovy Server Pages',\n\t'.hcl': 'HCL',\n\t'.tf': 'HCL',\n\t'.hlsl': 'HLSL',\n\t'.fxh': 'HLSL',\n\t'.hlsli': 'HLSL',\n\t'.php': 'PHP',\n\t'.hb': 'Harbour',\n\t'.hs': 'Haskell',\n\t'.hsc': 'Haskell',\n\t'.hx': 'Haxe',\n\t'.hxsl': 'Haxe',\n\t'.hy': 'Hy',\n\t'.pro': 'QMake',\n\t'.dlm': 'IDL',\n\t'.ipf': 'IGOR Pro',\n\t'.idr': 'Idris',\n\t'.lidr': 'Idris',\n\t'.ni': 'Inform 7',\n\t'.i7x': 'Inform 7',\n\t'.iss': 'Inno Setup',\n\t'.io': 'Io',\n\t'.ik': 'Ioke',\n\t'.thy': 'Isabelle',\n\t'.ijs': 'J',\n\t'.flex': 'JFlex',\n\t'.jflex': 'JFlex',\n\t'.jq': 'JSONiq',\n\t'.jsx': 'JSX',\n\t'.mdx': 'MDX',\n\t'.j': 'Objective-J',\n\t'.java': 'Java',\n\t'.jsp': 'Java Server Pages',\n\t'.js': 'JavaScript',\n\t'._js': 'JavaScript',\n\t'.bones': 'JavaScript',\n\t'.es6': 'JavaScript',\n\t'.jake': 'JavaScript',\n\t'.jsb': 'JavaScript',\n\t'.jscad': 'JavaScript',\n\t'.jsfl': 'JavaScript',\n\t'.jsm': 'JavaScript',\n\t'.jss': 'JavaScript',\n\t'.njs': 'JavaScript',\n\t'.pac': 'JavaScript',\n\t'.sjs': 'JavaScript',\n\t'.ssjs': 'JavaScript',\n\t'.sublime-build': 'JavaScript',\n\t'.sublime-commands': 'JavaScript',\n\t'.sublime-completions': 'JavaScript',\n\t'.sublime-keymap': 'JavaScript',\n\t'.sublime-macro': 'JavaScript',\n\t'.sublime-menu': 'JavaScript',\n\t'.sublime-mousemap': 'JavaScript',\n\t'.sublime-project': 'JavaScript',\n\t'.sublime-settings': 'JavaScript',\n\t'.sublime-theme': 'JavaScript',\n\t'.sublime-workspace': 'JavaScript',\n\t'.sublime_metrics': 'JavaScript',\n\t'.sublime_session': 'JavaScript',\n\t'.xsjs': 'JavaScript',\n\t'.xsjslib': 'JavaScript',\n\t'.jl': 'Julia',\n\t'.krl': 'KRL',\n\t'.sch': 'KiCad',\n\t'.brd': 'KiCad',\n\t'.kicad_pcb': 'KiCad',\n\t'.kt': 'Kotlin',\n\t'.ktm': 'Kotlin',\n\t'.kts': 'Kotlin',\n\t'.lfe': 'LFE',\n\t'.ll': 'LLVM',\n\t'.lol': 'LOLCODE',\n\t'.lsl': 'LSL',\n\t'.lslp': 'LSL',\n\t'.lvproj': 'LabVIEW',\n\t'.lasso': 'Lasso',\n\t'.las': 'Lasso',\n\t'.lasso8': 'Lasso',\n\t'.lasso9': 'Lasso',\n\t'.ldml': 'Lasso',\n\t'.lean': 'Lean',\n\t'.hlean': 'Lean',\n\t'.lex': 'Lex',\n\t'.ly': 'LilyPond',\n\t'.ily': 'LilyPond',\n\t'.m': 'Objective-C',\n\t'.lagda': 'Literate Agda',\n\t'.litcoffee': 'Literate CoffeeScript',\n\t'.lhs': 'Literate Haskell',\n\t'.ls': 'LoomScript',\n\t'._ls': 'LiveScript',\n\t'.xm': 'Logos',\n\t'.x': 'Logos',\n\t'.xi': 'Logos',\n\t'.lgt': 'Logtalk',\n\t'.logtalk': 'Logtalk',\n\t'.lookml': 'LookML',\n\t'.lua': 'Lua',\n\t'.fcgi': 'Shell',\n\t'.nse': 'Lua',\n\t'.pd_lua': 'Lua',\n\t'.rbxs': 'Lua',\n\t'.wlua': 'Lua',\n\t'.mumps': 'M',\n\t'.m4': 'M4Sugar',\n\t'.mcr': 'MAXScript',\n\t'.muf': 'MUF',\n\t'.mak': 'Makefile',\n\t'.mk': 'Makefile',\n\t'.mkfile': 'Makefile',\n\t'.mako': 'Mako',\n\t'.mao': 'Mako',\n\t'.mathematica': 'Mathematica',\n\t'.cdf': 'Mathematica',\n\t'.ma': 'Mathematica',\n\t'.mt': 'Mathematica',\n\t'.nb': 'Mathematica',\n\t'.nbp': 'Mathematica',\n\t'.wl': 'Mathematica',\n\t'.wlt': 'Mathematica',\n\t'.matlab': 'Matlab',\n\t'.maxpat': 'Max',\n\t'.maxhelp': 'Max',\n\t'.maxproj': 'Max',\n\t'.mxt': 'Max',\n\t'.pat': 'Max',\n\t'.moo': 'Moocode',\n\t'.metal': 'Metal',\n\t'.minid': 'MiniD',\n\t'.druby': 'Mirah',\n\t'.duby': 'Mirah',\n\t'.mir': 'Mirah',\n\t'.mirah': 'Mirah',\n\t'.mo': 'Modelica',\n\t'.mms': 'Module Management System',\n\t'.mmk': 'Module Management System',\n\t'.monkey': 'Monkey',\n\t'.moon': 'MoonScript',\n\t'.myt': 'Myghty',\n\t'.ncl': 'NCL',\n\t'.nsi': 'NSIS',\n\t'.nsh': 'NSIS',\n\t'.n': 'Nemerle',\n\t'.axs': 'NetLinx',\n\t'.axi': 'NetLinx',\n\t'.axs.erb': 'NetLinx+ERB',\n\t'.axi.erb': 'NetLinx+ERB',\n\t'.nlogo': 'NetLogo',\n\t'.nl': 'NewLisp',\n\t'.nim': 'Nimrod',\n\t'.nimrod': 'Nimrod',\n\t'.nit': 'Nit',\n\t'.nix': 'Nix',\n\t'.nu': 'Nu',\n\t'.numpy': 'NumPy',\n\t'.numpyw': 'NumPy',\n\t'.numsc': 'NumPy',\n\t'.ml': 'OCaml',\n\t'.eliom': 'OCaml',\n\t'.eliomi': 'OCaml',\n\t'.ml4': 'OCaml',\n\t'.mli': 'OCaml',\n\t'.mll': 'OCaml',\n\t'.mly': 'OCaml',\n\t'.mm': 'Objective-C++',\n\t'.sj': 'Objective-J',\n\t'.omgrofl': 'Omgrofl',\n\t'.opa': 'Opa',\n\t'.opal': 'Opal',\n\t'.opencl': 'OpenCL',\n\t'.p': 'OpenEdge ABL',\n\t'.scad': 'OpenSCAD',\n\t'.ox': 'Ox',\n\t'.oxh': 'Ox',\n\t'.oxo': 'Ox',\n\t'.oxygene': 'Oxygene',\n\t'.oz': 'Oz',\n\t'.pwn': 'PAWN',\n\t'.aw': 'PHP',\n\t'.ctp': 'PHP',\n\t'.php3': 'PHP',\n\t'.php4': 'PHP',\n\t'.php5': 'PHP',\n\t'.phps': 'PHP',\n\t'.phpt': 'PHP',\n\t'.pls': 'PLSQL',\n\t'.pck': 'PLSQL',\n\t'.pkb': 'PLSQL',\n\t'.pks': 'PLSQL',\n\t'.plb': 'PLSQL',\n\t'.plsql': 'PLSQL',\n\t'.sql': 'SQLPL',\n\t'.pov': 'POV-Ray SDL',\n\t'.pan': 'Pan',\n\t'.psc': 'Papyrus',\n\t'.parrot': 'Parrot',\n\t'.pasm': 'Parrot Assembly',\n\t'.pir': 'Parrot Internal Representation',\n\t'.pas': 'Pascal',\n\t'.dfm': 'Pascal',\n\t'.dpr': 'Pascal',\n\t'.lpr': 'Pascal',\n\t'.pp': 'Puppet',\n\t'.pl': 'Prolog',\n\t'.al': 'Perl',\n\t'.cgi': 'Shell',\n\t'.perl': 'Perl',\n\t'.ph': 'Perl',\n\t'.plx': 'Perl',\n\t'.pm': 'Perl6',\n\t'.pod': 'Perl',\n\t'.psgi': 'Perl',\n\t'.t': 'Turing',\n\t'.6pl': 'Perl6',\n\t'.6pm': 'Perl6',\n\t'.nqp': 'Perl6',\n\t'.p6': 'Perl6',\n\t'.p6l': 'Perl6',\n\t'.p6m': 'Perl6',\n\t'.pl6': 'Perl6',\n\t'.pm6': 'Perl6',\n\t'.pig': 'PigLatin',\n\t'.pike': 'Pike',\n\t'.pmod': 'Pike',\n\t'.pogo': 'PogoScript',\n\t'.pony': 'Pony',\n\t'.ps1': 'PowerShell',\n\t'.psd1': 'PowerShell',\n\t'.psm1': 'PowerShell',\n\t'.pde': 'Processing',\n\t'.prolog': 'Prolog',\n\t'.yap': 'Prolog',\n\t'.spin': 'Propeller Spin',\n\t'.pd': 'Pure Data',\n\t'.pb': 'PureBasic',\n\t'.pbi': 'PureBasic',\n\t'.purs': 'PureScript',\n\t'.py': 'Python',\n\t'.bzl': 'Python',\n\t'.gyp': 'Python',\n\t'.lmi': 'Python',\n\t'.pyde': 'Python',\n\t'.pyp': 'Python',\n\t'.pyt': 'Python',\n\t'.pyw': 'Python',\n\t'.rpy': \"Ren'Py\",\n\t'.tac': 'Python',\n\t'.wsgi': 'Python',\n\t'.xpy': 'Python',\n\t'.qml': 'QML',\n\t'.qbs': 'QML',\n\t'.pri': 'QMake',\n\t'.r': 'Rebol',\n\t'.rd': 'R',\n\t'.rsx': 'R',\n\t'.rbbas': 'REALbasic',\n\t'.rbfrm': 'REALbasic',\n\t'.rbmnu': 'REALbasic',\n\t'.rbres': 'REALbasic',\n\t'.rbtbar': 'REALbasic',\n\t'.rbuistate': 'REALbasic',\n\t'.rkt': 'Racket',\n\t'.rktd': 'Racket',\n\t'.rktl': 'Racket',\n\t'.scrbl': 'Racket',\n\t'.rl': 'Ragel in Ruby Host',\n\t'.reb': 'Rebol',\n\t'.r2': 'Rebol',\n\t'.r3': 'Rebol',\n\t'.rebol': 'Rebol',\n\t'.red': 'Red',\n\t'.reds': 'Red',\n\t'.cw': 'Redcode',\n\t'.rs': 'Rust',\n\t'.rsh': 'RenderScript',\n\t'.robot': 'RobotFramework',\n\t'.rg': 'Rouge',\n\t'.rb': 'Ruby',\n\t'.builder': 'Ruby',\n\t'.gemspec': 'Ruby',\n\t'.god': 'Ruby',\n\t'.irbrc': 'Ruby',\n\t'.jbuilder': 'Ruby',\n\t'.mspec': 'Ruby',\n\t'.pluginspec': 'Ruby',\n\t'.podspec': 'Ruby',\n\t'.rabl': 'Ruby',\n\t'.rake': 'Ruby',\n\t'.rbuild': 'Ruby',\n\t'.rbw': 'Ruby',\n\t'.rbx': 'Ruby',\n\t'.ru': 'Ruby',\n\t'.ruby': 'Ruby',\n\t'.thor': 'Ruby',\n\t'.watchr': 'Ruby',\n\t'.rs.in': 'Rust',\n\t'.sas': 'SAS',\n\t'.smt2': 'SMT',\n\t'.smt': 'SMT',\n\t'.sqf': 'SQF',\n\t'.hqf': 'SQF',\n\t'.db2': 'SQLPL',\n\t'.sage': 'Sage',\n\t'.sagews': 'Sage',\n\t'.sls': 'Scheme',\n\t'.scala': 'Scala',\n\t'.sbt': 'Scala',\n\t'.sc': 'SuperCollider',\n\t'.scm': 'Scheme',\n\t'.sld': 'Scheme',\n\t'.sps': 'Scheme',\n\t'.ss': 'Scheme',\n\t'.sci': 'Scilab',\n\t'.sce': 'Scilab',\n\t'.self': 'Self',\n\t'.sh': 'Shell',\n\t'.bash': 'Shell',\n\t'.bats': 'Shell',\n\t'.command': 'Shell',\n\t'.ksh': 'Shell',\n\t'.sh.in': 'Shell',\n\t'.tmux': 'Shell',\n\t'.tool': 'Shell',\n\t'.zsh': 'Shell',\n\t'.sh-session': 'ShellSession',\n\t'.shen': 'Shen',\n\t'.sl': 'Slash',\n\t'.smali': 'Smali',\n\t'.st': 'Smalltalk',\n\t'.tpl': 'Smarty',\n\t'.sp': 'SourcePawn',\n\t'.sma': 'SourcePawn',\n\t'.nut': 'Squirrel',\n\t'.stan': 'Stan',\n\t'.ML': 'Standard ML',\n\t'.fun': 'Standard ML',\n\t'.sig': 'Standard ML',\n\t'.sml': 'Standard ML',\n\t'.do': 'Stata',\n\t'.ado': 'Stata',\n\t'.doh': 'Stata',\n\t'.ihlp': 'Stata',\n\t'.mata': 'Stata',\n\t'.matah': 'Stata',\n\t'.sthlp': 'Stata',\n\t'.scd': 'SuperCollider',\n\t'.swift': 'Swift',\n\t'.sv': 'SystemVerilog',\n\t'.svh': 'SystemVerilog',\n\t'.vh': 'SystemVerilog',\n\t'.txl': 'TXL',\n\t'.tcl': 'Tcl',\n\t'.adp': 'Tcl',\n\t'.tm': 'Tcl',\n\t'.tcsh': 'Tcsh',\n\t'.csh': 'Tcsh',\n\t'.thrift': 'Thrift',\n\t'.tu': 'Turing',\n\t'.ts': 'TypeScript',\n\t'.tsx': 'TypeScript',\n\t'.upc': 'Unified Parallel C',\n\t'.uno': 'Uno',\n\t'.uc': 'UnrealScript',\n\t'.ur': 'UrWeb',\n\t'.urs': 'UrWeb',\n\t'.vcl': 'VCL',\n\t'.vhdl': 'VHDL',\n\t'.vhd': 'VHDL',\n\t'.vhf': 'VHDL',\n\t'.vhi': 'VHDL',\n\t'.vho': 'VHDL',\n\t'.vhs': 'VHDL',\n\t'.vht': 'VHDL',\n\t'.vhw': 'VHDL',\n\t'.vala': 'Vala',\n\t'.vapi': 'Vala',\n\t'.veo': 'Verilog',\n\t'.vim': 'VimL',\n\t'.vb': 'Visual Basic',\n\t'.bas': 'Visual Basic',\n\t'.frm': 'Visual Basic',\n\t'.frx': 'Visual Basic',\n\t'.vba': 'Visual Basic',\n\t'.vbhtml': 'Visual Basic',\n\t'.vbs': 'Visual Basic',\n\t'.volt': 'Volt',\n\t'.webidl': 'WebIDL',\n\t'.x10': 'X10',\n\t'.xc': 'XC',\n\t'.xsp-config': 'XPages',\n\t'.xsp.metadata': 'XPages',\n\t'.xpl': 'XProc',\n\t'.xproc': 'XProc',\n\t'.xquery': 'XQuery',\n\t'.xq': 'XQuery',\n\t'.xql': 'XQuery',\n\t'.xqm': 'XQuery',\n\t'.xqy': 'XQuery',\n\t'.xs': 'XS',\n\t'.xslt': 'XSLT',\n\t'.xsl': 'XSLT',\n\t'.xojo_code': 'Xojo',\n\t'.xojo_menu': 'Xojo',\n\t'.xojo_report': 'Xojo',\n\t'.xojo_script': 'Xojo',\n\t'.xojo_toolbar': 'Xojo',\n\t'.xojo_window': 'Xojo',\n\t'.xtend': 'Xtend',\n\t'.y': 'Yacc',\n\t'.yacc': 'Yacc',\n\t'.yy': 'Yacc',\n\t'.zep': 'Zephir',\n\t'.zimpl': 'Zimpl',\n\t'.zmpl': 'Zimpl',\n\t'.zpl': 'Zimpl',\n\t'.ec': 'eC',\n\t'.eh': 'eC',\n\t'.fish': 'fish',\n\t'.mu': 'mupad',\n\t'.nc': 'nesC',\n\t'.ooc': 'ooc',\n\t'.wisp': 'wisp',\n\t'.prg': 'xBase',\n\t'.prw': 'xBase'\n};\n\nexport const allSupportedExtensions = [\n\t...generalFileExtSupported,\n\t...Object.keys(programmingFilesExtensions)\n];\n\nexport const MEMORYSETS: memorysetsConstants = {\n\tMAX_DOC_SIZE: 10 * 1024 * 1024, // 10MB = 10 * 1024 KB = 10 * 1024 * 1024 bytes\n\tACCEPTED_MIME_TYPES: [\n\t\t'text/plain',\n\t\t'application/pdf',\n\t\t'text/markdown',\n\t\t'text/csv',\n\t\t'application/vnd.ms-excel',\n\t\t'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\t],\n\tDOC_TYPES: generalFileExtSupported,\n\tEMBEDDING_MODEL: 'text-embedding-3-large',\n\tEMBEDDING_DIMENSIONS: 256,\n\tMIN_CHUNK_LENGTH: 1024,\n\tMAX_CHUNK_LENGTH: 30000,\n\tMIN_CHUNK_OVERLAP: 256,\n\tEMBEDDING_MODEL_TOKENS_LIMIT: 8191,\n\tEMBEDDING_MAX_BATCH_SIZE: 2048,\n\tEMBEDDING_ENCODING_FORMAT: 'float',\n\tTOP_K: 3,\n\tMAX_CHUNKS_ATTACHED_TO_LLM: 20,\n\tOLLAMA_EMBEDDINGS_ENDPOINT: 'http://localhost:11434/api/embeddings',\n\tOLLAMA_EMBEDDINGS_MODEL: 'mxbai-embed-large'\n};\n\ninterface memorysetsConstants {\n\tMAX_DOC_SIZE: number;\n\tACCEPTED_MIME_TYPES: string[];\n\tDOC_TYPES: string[];\n\tEMBEDDING_MODEL: string;\n\tEMBEDDING_DIMENSIONS: number;\n\tEMBEDDING_ENCODING_FORMAT: 'float' | 'base64';\n\tMIN_CHUNK_LENGTH: number;\n\tMIN_CHUNK_OVERLAP: number;\n\tMAX_CHUNK_LENGTH: number;\n\tEMBEDDING_MODEL_TOKENS_LIMIT: number;\n\tEMBEDDING_MAX_BATCH_SIZE: number;\n\tTOP_K: number;\n\tMAX_CHUNKS_ATTACHED_TO_LLM: number;\n\tOLLAMA_EMBEDDINGS_ENDPOINT: string;\n\tOLLAMA_EMBEDDINGS_MODEL: string;\n}\n\nexport const defaultRagPrompt = `Below is some CONTEXT for you to answer the questions. ONLY answer from the CONTEXT. CONTEXT consists of multiple information chunks. Each chunk has a source mentioned at the end.\\n\\nFor each piece of response you provide, cite the source in brackets like so: [1].\\n\\nAt the end of the answer, always list each source with its corresponding number and provide the document name. like so [1] Filename.doc.\\n\\nIf you don't know the answer, just say that you don't know. Ask for more context and better questions if needed.`;\n","import * as p from '@clack/prompts';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport { allSupportedExtensions, MEMORYSETS } from './constants';\nimport { getDocumentContent } from './get-document-content';\nimport { formatDocSize } from './lib';\nimport loadMemoryConfig from './load-memory-config';\nimport {\n\tmemoryConfigSchema,\n\ttype DocumentConfigI,\n\ttype MemoryConfigI\n} from 'types/memory';\nimport { execSync } from 'child_process';\nimport fg from 'fast-glob';\n\nexport interface MemoryDocumentI {\n\tname: string;\n\tsize: string;\n\tcontent: string;\n\tblob: Blob;\n\tpath: string;\n\tmeta: Record<string, string>;\n}\n\nexport const loadMemoryFiles = async (\n\tmemoryName: string\n): Promise<MemoryDocumentI[]> => {\n\t// Get memory config.\n\tconst memoryConfig = await checkMemoryConfig(memoryName);\n\n\t// useDocumentsDir\n\tconst useDocumentsDir = !memoryConfig || !memoryConfig.git.enabled;\n\tconst documentConfig = memoryConfig?.documents;\n\n\t// Load files from documents directory.\n\tif (useDocumentsDir) {\n\t\treturn await loadMemoryFilesFromDocsDir({ memoryName, documentConfig });\n\t}\n\n\t// Load files from the repo.\n\treturn await loadMemoryFilesFromCustomDir({ memoryName, memoryConfig });\n};\n\n/**\n * Loads memory files from a custom directory specified in the memory configuration.\n *\n * @param {Object} params - The parameters for loading memory files.\n * @param {string} params.memoryName - The name of the memory.\n * @param {MemoryConfigI} params.memoryConfig - The configuration for the memory, including the directory to track and the extensions to track.\n * @returns {Promise<MemoryDocumentI[]>} A promise that resolves to an array of memory documents.\n *\n * @throws Will terminate the process if the documents directory does not exist or if it fails to read documents in the memory.\n */\nexport const loadMemoryFilesFromCustomDir = async ({\n\tmemoryName,\n\tmemoryConfig\n}: {\n\tmemoryName: string;\n\tmemoryConfig: MemoryConfigI;\n}): Promise<MemoryDocumentI[]> => {\n\tconst includePatterns = memoryConfig.git.include;\n\n\tif (!Array.isArray(includePatterns) || includePatterns.length === 0) {\n\t\tp.cancel(`No include patterns specified for memory '${memoryName}'`);\n\t\tprocess.exit(1);\n\t}\n\n\tconsole.log('Reading documents in memory...');\n\n\t// Get all files that match the glob patterns and are tracked by git\n\tlet allFiles: string[];\n\ttry {\n\t\t// First get all git tracked files\n\t\tconst gitFiles = new Set([\n\t\t\t...execSync('git ls-files', { encoding: 'utf-8' })\n\t\t\t\t.split('\\n')\n\t\t\t\t.filter(Boolean),\n\t\t\t...execSync('git ls-files --others --exclude-standard', {\n\t\t\t\tencoding: 'utf-8'\n\t\t\t})\n\t\t\t\t.split('\\n')\n\t\t\t\t.filter(Boolean),\n\t\t\t...execSync('git diff --name-only', { encoding: 'utf-8' })\n\t\t\t\t.split('\\n')\n\t\t\t\t.filter(Boolean)\n\t\t]);\n\n\t\t// Then match against glob patterns\n\t\tconst matchedFiles = await fg(includePatterns, {\n\t\t\tignore: ['node_modules/**'],\n\t\t\tdot: true,\n\t\t\tgitignore: memoryConfig.git.gitignore || true\n\t\t});\n\n\t\t// Only keep files that are both tracked by git and match the patterns\n\t\tallFiles = matchedFiles.filter((file: string) => gitFiles.has(file));\n\t} catch (error) {\n\t\tp.cancel(`Failed to read documents in memory '${memoryName}'.`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst memoryFilesContent = await Promise.all(\n\t\tallFiles.map(async filePath => {\n\t\t\t// Check if the file is allowed\n\t\t\tconst isSupportedExtension = allSupportedExtensions.some(\n\t\t\t\textension => filePath.endsWith(extension)\n\t\t\t);\n\n\t\t\tif (!isSupportedExtension) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tlet fileContentBuffer: Buffer;\n\t\t\ttry {\n\t\t\t\tfileContentBuffer = await fs.readFile(filePath);\n\t\t\t} catch (error) {\n\t\t\t\tp.log.warn(`Failed to read file: ${filePath}. Skipping.`);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst fileContentBlob = new Blob([fileContentBuffer]);\n\t\t\tconst size = fileContentBlob.size;\n\n\t\t\tif (size > MEMORYSETS.MAX_DOC_SIZE) {\n\t\t\t\tp.log.warn(\n\t\t\t\t\t`Skipping ${filePath}; File exceeds the maximum size of ${formatDocSize(MEMORYSETS.MAX_DOC_SIZE)}.`\n\t\t\t\t);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst memoryFile = {\n\t\t\t\tpath: filePath,\n\t\t\t\tname: path.basename(filePath.replace(/\\//g, '-')),\n\t\t\t\tsize: formatDocSize(fileContentBlob.size),\n\t\t\t\tcontent: await getDocumentContent(fileContentBlob),\n\t\t\t\tblob: fileContentBlob\n\t\t\t};\n\n\t\t\tlet meta = {};\n\n\t\t\tif (memoryConfig?.documents?.meta) {\n\t\t\t\tmeta = memoryConfig.documents.meta(memoryFile) || {};\n\t\t\t}\n\n\t\t\treturn { ...memoryFile, meta };\n\t\t})\n\t);\n\n\tconst memoryFilesContentFiltered = memoryFilesContent.filter(\n\t\t(file): file is MemoryDocumentI => file !== null\n\t);\n\n\tif (memoryFilesContentFiltered.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn memoryFilesContentFiltered;\n};\n\n/**\n * Loads memory files from the specified memory directory.\n *\n * @param memoryName - The name of the memory directory to load files from.\n * @returns A promise that resolves to an array of `MemoryDocumentI` objects.\n *\n * @throws Will exit the process if the documents directory does not exist or if reading the directory fails.\n *\n * The function performs the following steps:\n * 1. Constructs the path to the memory directory and the documents subdirectory.\n * 2. Checks if the documents directory exists. If not, logs an error and exits the process.\n * 3. Reads the list of files in the documents directory. If reading fails, logs an error and exits the process.\n * 4. Reads the content of each file and filters out files that:\n *    - Cannot be read.\n *    - Exceed the maximum allowed size.\n *    - Have unsupported file extensions.\n * 5. Returns an array of `MemoryDocumentI` objects representing the valid memory files.\n */\nexport const loadMemoryFilesFromDocsDir = async ({\n\tmemoryName,\n\tdocumentConfig\n}: {\n\tmemoryName: string;\n\tdocumentConfig?: DocumentConfigI;\n}): Promise<MemoryDocumentI[]> => {\n\tconst memoryDir = path.join(process.cwd(), 'baseai', 'memory', memoryName);\n\tconst memoryFilesPath = path.join(memoryDir, 'documents');\n\n\ttry {\n\t\tawait fs.access(memoryFilesPath);\n\t} catch (error) {\n\t\tp.cancel(\n\t\t\t`Documents directory for memory '${memoryName}' does not exist.`\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\tlet memoryFiles: string[];\n\ttry {\n\t\tmemoryFiles = await fs.readdir(memoryFilesPath);\n\t} catch (error) {\n\t\tp.cancel(`Failed to read documents in memory '${memoryName}'.`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst memoryFilesContent = await Promise.all(\n\t\tmemoryFiles.map(async file => {\n\t\t\t// Check if the file is allowed.\n\t\t\tconst isSupportedExtension = allSupportedExtensions.some(\n\t\t\t\textension => file.endsWith(extension)\n\t\t\t);\n\n\t\t\tif (!isSupportedExtension) {\n\t\t\t\tp.log.warn(`Skipping ${file}; Unsupported file extension.`);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst filePath = path.join(memoryFilesPath, file);\n\n\t\t\tlet fileContentBuffer: Buffer;\n\t\t\ttry {\n\t\t\t\tfileContentBuffer = await fs.readFile(filePath);\n\t\t\t} catch (error) {\n\t\t\t\tp.log.warn(`Failed to read file: ${file}. Skipping.`);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst fileContentBlob = new Blob([fileContentBuffer]);\n\t\t\tconst size = fileContentBlob.size;\n\n\t\t\tif (size > MEMORYSETS.MAX_DOC_SIZE) {\n\t\t\t\tp.log.warn(\n\t\t\t\t\t`Skipping ${file}; File exceeds the maximum size of ${formatDocSize(MEMORYSETS.MAX_DOC_SIZE)}.`\n\t\t\t\t);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst memoryFile = {\n\t\t\t\tname: file,\n\t\t\t\tpath: filePath,\n\t\t\t\tsize: formatDocSize(fileContentBlob.size),\n\t\t\t\tcontent: await getDocumentContent(fileContentBlob),\n\t\t\t\tblob: fileContentBlob\n\t\t\t};\n\n\t\t\tlet meta = {};\n\n\t\t\tif (documentConfig?.meta) {\n\t\t\t\tmeta = documentConfig.meta(memoryFile) || {};\n\t\t\t}\n\n\t\t\treturn { ...memoryFile, meta };\n\t\t})\n\t);\n\n\tconst memoryFilesContentFiltered = memoryFilesContent.filter(\n\t\t(file): file is MemoryDocumentI => file !== null\n\t);\n\n\tif (memoryFilesContentFiltered.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn memoryFilesContentFiltered;\n};\n\n/**\n * Asynchronously checks the configuration for a given memory name.\n *\n * @param memoryName - The name of the memory to check the configuration for.\n * @returns A promise that resolves to the memory configuration if it exists and is valid,\n *          resolves to null if the configuration does not exist,\n *          or does not resolve if the configuration is invalid (process exits).\n */\nasync function checkMemoryConfig(\n\tmemoryName: string\n): Promise<MemoryConfigI | null | void> {\n\t// Load config for memory.\n\tconst memoryConfig = await loadMemoryConfig(memoryName);\n\n\t// Check if config exists.\n\tconst configExists = memoryConfig !== null;\n\n\t// No config exists for memory.\n\tif (!configExists) {\n\t\treturn null;\n\t}\n\n\t// Check if config is valid.\n\tconst validatedConfig = memoryConfigSchema.safeParse(memoryConfig);\n\n\t// Config is invalid.\n\tif (!validatedConfig.success) {\n\t\tp.cancel(`Memory '${memoryName}' has an invalid config.`);\n\t\tprocess.exit(1);\n\t}\n\n\treturn {\n\t\t...memoryConfig\n\t};\n}\n\nexport const getMemoryFileNames = async (\n\tmemoryName: string\n): Promise<string[]> => {\n\tconst memoryDir = path.join(process.cwd(), 'baseai', 'memory', memoryName);\n\tconst memoryFilesPath = path.join(memoryDir, 'documents');\n\n\ttry {\n\t\tawait fs.access(memoryFilesPath);\n\t} catch (error) {\n\t\tp.cancel(\n\t\t\t`Documents directory for memory '${memoryName}' does not exist.`\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tconst memoryFiles = await fs.readdir(memoryFilesPath);\n\n\t\tconst validFiles = await Promise.all(\n\t\t\tmemoryFiles.map(async file => {\n\t\t\t\tconst filePath = path.join(memoryFilesPath, file);\n\t\t\t\tconst stats = await fs.stat(filePath);\n\n\t\t\t\tconst isSupportedExtension = allSupportedExtensions.some(\n\t\t\t\t\textension => file.endsWith(extension)\n\t\t\t\t);\n\t\t\t\tconst isNotTooLarge = stats.size <= MEMORYSETS.MAX_DOC_SIZE;\n\n\t\t\t\treturn isSupportedExtension && isNotTooLarge ? file : null;\n\t\t\t})\n\t\t);\n\n\t\treturn validFiles.filter((file): file is string => file !== null);\n\t} catch (error) {\n\t\tp.cancel(`Failed to read documents in memory '${memoryName}'.`);\n\t\tprocess.exit(1);\n\t}\n};\n","import { getDocumentProxy, extractText } from 'unpdf';\nimport * as XLSX from 'xlsx';\n\n/**\n * Retrieves the content of a document.\n *\n * Supported document types:\n * 1- Text files: .txt\n * 2- PDF files: .pdf\n * 3- CSV files: .csv\n * 4- Excel files: .xlsx/.xls\n * 5- Markdown files: .md\n *\n * @param doc - The document to retrieve the content from.\n * @returns A promise that resolves to the content of the document as a string.\n */\nexport async function getDocumentContent(doc: Blob): Promise<string> {\n\t// Extract the content from the doc.\n\tlet docType = doc.type;\n\n\t// Make text files.\n\tif (docType.includes('charset')) docType = 'text/plain';\n\n\tlet content = '';\n\n\t// Process content based on document type.\n\tif (docType === 'text/plain') {\n\t\tcontent = await processTextFile(doc);\n\t} else if (docType === 'application/pdf') {\n\t\tcontent = await processPdfFile(doc);\n\t} else if (docType === 'text/csv') {\n\t\tcontent = await processCsvFile(doc);\n\t} else if (docType.includes('application/vnd')) {\n\t\t/***\n\t\t * 'application/vnd.ms-excel' -> .xls\n\t\t * 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' -> .xlsx\n\t\t */\n\t\tcontent = await processXlsFile(doc);\n\t} else {\n\t\tcontent = await processMarkdownFile(doc);\n\t}\n\n\t// Remove emojis from the content.\n\tcontent = removeEmojis(content);\n\n\treturn content;\n}\n\n/**\n * Processes a text file and returns its content as a string.\n *\n * @param doc - The text file to be processed.\n * @returns A promise that resolves to the content of the text file as a string.\n */\nasync function processTextFile(doc: Blob): Promise<string> {\n\treturn await doc.text();\n}\n\n/**\n * Processes a PDF file and extracts its content as a string.\n *\n * @param doc - The PDF file to process.\n * @returns A promise that resolves to the extracted content as a string.\n */\nasync function processPdfFile(doc: Blob): Promise<string> {\n\tconst pdfDocument = await getDocumentProxy(await doc.arrayBuffer());\n\tconst { text } = await extractText(pdfDocument, {\n\t\tmergePages: true\n\t});\n\treturn typeof text === 'string' ? text : (text as string[]).join('\\n');\n}\n\n/**\n * Processes a CSV file and returns its content as a string.\n *\n * @param doc - The CSV file to be processed.\n * @returns A promise that resolves to the content of the CSV file as a string.\n */\nasync function processCsvFile(doc: Blob): Promise<string> {\n\tconst content = await doc.text();\n\treturn processCSV(content);\n}\n\n/**\n * Processes an XLS file and returns its content as a string.\n * (Supports both .xls and .xlsx files)\n *\n * @param doc - The XLS file to process.\n * @returns A promise that resolves to the content of the XLS file as a string.\n */\nasync function processXlsFile(doc: Blob): Promise<string> {\n\t// Read the Excel file as an array buffer\n\tconst arrayBuffer = await doc.arrayBuffer();\n\n\t// Parse the Excel file\n\tconst workbook = XLSX.read(new Uint8Array(arrayBuffer), { type: 'array' });\n\n\t// Content\n\tlet content = '';\n\t// Traverse all the sheets in the workbook\n\t// and process the content of each sheet and append it to the final content.\n\n\tfor (const sheetName of workbook.SheetNames) {\n\t\t// Get the content of the sheet\n\t\tconst worksheet = workbook.Sheets[sheetName];\n\t\t// Convert the sheet to CSV\n\t\tconst csvContent = XLSX.utils.sheet_to_csv(worksheet);\n\t\t// Process\n\t\tconst processedContent = processCSV(csvContent);\n\t\t// Append the processed content to the final content\n\t\tcontent += processedContent + '\\n\\n';\n\t}\n\n\t// Return the final content\n\treturn content;\n}\n\n/**\n * Processes a markdown file and returns its content as a string.\n *\n * @param doc - The markdown file to process.\n * @returns A promise that resolves to the content of the markdown file as a string.\n */\nasync function processMarkdownFile(doc: Blob): Promise<string> {\n\treturn await doc.text();\n}\n\n/**\n * Removes emojis from the given content.\n *\n * @param content - The content from which emojis should be removed.\n * @returns The content with emojis removed.\n */\nfunction removeEmojis(content: string): string {\n\treturn content.replace(\n\t\t/([\\u2700-\\u27BF]|[\\uE000-\\uF8FF]|\\uD83C[\\uDC00-\\uDFFF]|\\uD83D[\\uDC00-\\uDFFF]|[\\u2011-\\u26FF]|\\uD83E[\\uDD10-\\uDDFF])/g,\n\t\t''\n\t);\n}\n\n/**\n * Processes the content of a CSV file and returns the processed content.\n *\n * The processed content is a string where each row is prepended with the header row.\n *\n * @param csvContent - The content of the CSV file as a string.\n * @returns The processed content of the CSV file.\n */\nfunction processCSV(csvContent: string): string {\n\t// Split the content into rows\n\tconst rows = csvContent.split('\\n');\n\n\t// Extract the header row\n\tconst header = rows[0].replace('\\r', '');\n\n\t// Process each data row and join them into a single string\n\tconst processedContent = rows\n\t\t.slice(1)\n\t\t.map(row => {\n\t\t\t// Skip empty rows and rows with only commas\n\t\t\tif (row.trim() === '' || /^[,]+$/.test(row.trim())) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\treturn header + '\\n' + row;\n\t\t})\n\t\t.join('\\n\\n');\n\n\treturn processedContent;\n}\n","/**\n * Lib file for memory module\n *\n * All functions return {data: any|null, error: string|null}\n */\nimport * as p from '@clack/prompts';\nimport fs from 'fs';\nimport type { Message } from 'types/pipe';\nimport { fromZodError } from 'zod-validation-error';\nimport { defaultRagPrompt, MEMORYSETS } from './constants';\nimport {\n\tcosineSimilaritySearch,\n\tgetDocumentsFromMemory,\n\ttype SimilarChunk\n} from './db/lib';\n// import { generateLocalEmbeddings } from './generate-local-embeddings';\nimport { dlog } from '@/dev/utils/dlog';\nimport { memoryDocSchema, memoryNameSchema } from 'types/memory';\nimport { loadConfig } from '../config/config-handler';\nimport { logger } from '../logger-utils';\nimport { generateLocalEmbeddings } from './generate-local-embeddings';\nimport { getOpenAIEmbeddings } from './generate-openai-embeddings';\n\nexport async function checkDirectoryExists(directoryPath: string) {\n\ttry {\n\t\tawait fs.promises.access(directoryPath);\n\t\treturn {\n\t\t\tdata: true,\n\t\t\terror: null\n\t\t};\n\t} catch (error: any) {\n\t\tconsole.log('utils/memory/lib.ts: checkDirectoryExists: error:', error);\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: getErrorMsg(error, 'Error checking directory exists')\n\t\t};\n\t}\n}\n\nexport const getErrorMsg = (error: any, defaultMsg: string) => {\n\tconst isErrorMessage = error instanceof Error;\n\tconst errorMessage = isErrorMessage\n\t\t? error.message.trim() || defaultMsg\n\t\t: defaultMsg;\n\treturn errorMessage;\n};\n\n/**\n * Formats the given number of bytes into a human-readable string representation.\n * @param bytes - The number of bytes to format.\n * @returns A string representing the formatted size.\n */\nexport function formatDocSize(bytes: number): string {\n\tif (bytes === 0) return '0 bytes';\n\n\tif (bytes < 1024) {\n\t\treturn bytes.toFixed(2) + ' bytes';\n\t} else if (bytes < 1024 * 1024) {\n\t\tconst fileSizeInKB = bytes / 1024;\n\t\treturn fileSizeInKB.toFixed(2) + ' KB';\n\t} else {\n\t\tconst fileSizeInMB = bytes / (1024 * 1024);\n\t\treturn fileSizeInMB.toFixed(2) + ' MB';\n\t}\n}\n\n/**\n * Validates the given memory name.\n *\n * @param memoryName - The name of the memory to validate.\n * @returns The validated memory name.\n * Logs error and exits process if the memory name is invalid.\n */\nexport const validateMemoryName = (memoryName: string) => {\n\tconst validatedName = memoryNameSchema.safeParse(memoryName);\n\tif (!validatedName.success) {\n\t\tconst err = fromZodError(validatedName.error).message;\n\t\tp.cancel(`Invalid memory name: ${err}`);\n\t\tprocess.exit(1);\n\t}\n\treturn validatedName.data;\n};\n\n/**\n * Validates the document embedding schema using the provided memory and document names.\n *\n * @param {Object} params - The parameters for the function.\n * @param {string} params.memoryName - The name of the memory.\n * @param {string} params.documentName - The name of the document.\n * @returns {Object} The validated data if the input is valid.\n * @throws Will terminate the process if the input is invalid.\n */\nexport const validateMemoryDocNames = ({\n\tmemoryName,\n\tdocumentName\n}: {\n\tmemoryName: string;\n\tdocumentName: string;\n}) => {\n\tconst validatedData = memoryDocSchema.safeParse({\n\t\tmemoryName,\n\t\tdocumentName\n\t});\n\tif (!validatedData.success) {\n\t\tconst err = fromZodError(validatedData.error).message;\n\t\tp.cancel(`Invalid input: ${err}`);\n\t\tprocess.exit(1);\n\t}\n\treturn validatedData.data;\n};\n\nexport const getAugmentedContext = ({\n\tsimilarChunks,\n\tmessages\n}: {\n\tsimilarChunks: SimilarChunk[];\n\tmessages: Message[];\n}) => {\n\tif (similarChunks.length === 0) return '';\n\n\tconst memoryContext = similarChunks\n\t\t.map(chunk => `${chunk.text} \\n\\n Source: ${chunk.attributes.docName}`)\n\t\t.join('\\n\\n');\n\n\t// Extract Rag prompt from the messages.\n\tconst ragMsg = messages.find(m => m.role === 'system' && m.name === 'rag');\n\t// If there is no rag prompt, use the default rag prompt.\n\tconst ragPrompt = ragMsg?.content || defaultRagPrompt;\n\n\tconst contextContent = `\"\"\"CONTEXT:\\n ${memoryContext}\"\"\"`;\n\tconst augmentedContext = `\"\"\"${ragPrompt}\"\"\" \\n\\n ${contextContent}`;\n\n\treturn augmentedContext;\n};\n\nexport const addContextFromMemory = async ({\n\tmessages,\n\tmemoryNames\n}: {\n\tmessages: Message[];\n\tmemoryNames: string[];\n}) => {\n\ttry {\n\t\t// Check if there are no memory names.\n\t\tconst isMemoryAttached = memoryNames.length > 0;\n\t\tlogger('memory', isMemoryAttached, 'Memory attached');\n\n\t\t// Check if there are no messages.\n\t\tconst messagesExist = messages.length > 0;\n\n\t\t// Return the messages if there are no memory names or messages.\n\t\tif (!isMemoryAttached || !messagesExist) return;\n\n\t\t// This will be the user prompt.\n\t\tconst lastUserMsg = [...messages]\n\t\t\t.reverse()\n\t\t\t.find(m => m.role === 'user');\n\t\tconst userPrompt = lastUserMsg?.content;\n\n\t\t// If there is no user prompt, return the messages.\n\t\tif (!userPrompt) return;\n\n\t\t// 1- Generate the embeddings of the user prompt.\n\t\t// Read config to determine which embedding to use.\n\t\tconst config = await loadConfig();\n\t\tconst useLocalEmbeddings = config.memory?.useLocalEmbeddings || false;\n\n\t\tlet embeddings = [];\n\t\tif (useLocalEmbeddings) {\n\t\t\t// Use local embeddings\n\t\t\tdlog('Generating local embeddings');\n\t\t\tembeddings = await generateLocalEmbeddings([userPrompt]);\n\t\t} else {\n\t\t\t// Use OpenAI embeddings\n\t\t\tdlog('Generating OpenAI embeddings');\n\t\t\tembeddings = await getOpenAIEmbeddings([userPrompt]);\n\t\t}\n\n\t\t// 2- Get all the memorysets from the db.\n\t\tconst memoryChunks = await getDocumentsFromMemory(memoryNames);\n\t\tif (memoryChunks.length === 0) return;\n\n\t\t// 3- Get similar chunks from the memorysets.\n\t\tconst similarChunks = cosineSimilaritySearch({\n\t\t\tchunks: memoryChunks,\n\t\t\tqueryEmbedding: embeddings[0].embedding,\n\t\t\ttopK: MEMORYSETS.MAX_CHUNKS_ATTACHED_TO_LLM\n\t\t});\n\t\tif (similarChunks.length === 0) return;\n\t\tlogger('memory.similarChunks', similarChunks);\n\n\t\treturn similarChunks;\n\t} catch (error: any) {\n\t\tdlog('utils/memory/lib.ts: addContextFromMemory: error:', error);\n\t}\n};\n\nexport const validateEmbedDocInput = ({\n\tmemoryName,\n\tdocumentName\n}: {\n\tmemoryName: string;\n\tdocumentName: string;\n}) => {\n\tconst validatedName = memoryNameSchema.safeParse(memoryName);\n\tif (!validatedName.success) {\n\t\tconst err = fromZodError(validatedName.error).message;\n\t\tp.cancel(`Invalid memory name: ${err}`);\n\t\tprocess.exit(1);\n\t}\n\treturn validatedName.data;\n};\n","import * as p from '@clack/prompts';\nimport cosineSimilarity from 'compute-cosine-similarity';\nimport fs from 'fs/promises';\nimport { Low } from 'lowdb';\nimport { JSONFile } from 'lowdb/node';\nimport path from 'path';\nimport color from 'picocolors';\nimport { z } from 'zod';\n\n// Schema definitions\nconst ChunkSchema = z.object({\n\tid: z.string().uuid(),\n\ttext: z.string().trim().min(1),\n\tembedding: z.array(z.number())\n});\n\ntype Chunk = z.infer<typeof ChunkSchema>;\n\ninterface Document {\n\tname: string;\n\tchunkIds: string[];\n}\n\ninterface Schema {\n\tdocuments: { [name: string]: Document };\n\tchunks: { [name: string]: Chunk };\n}\n\nconst defaultData: Schema = {\n\tdocuments: {},\n\tchunks: {}\n};\n\ninterface MemoryChunk {\n\ttext: string;\n\tembedding: number[];\n\tattributes: {\n\t\tmemoryName: string;\n\t\tdocName: string;\n\t};\n}\n\nexport interface SimilarChunk extends Omit<MemoryChunk, 'embedding'> {\n\tsimilarity: number;\n}\n\n// Utility functions\n\n// Create a new database\n// basePath. The path to\nexport async function createDb(memoryName: string): Promise<Low<Schema>> {\n\tconst baseDir = path.join(process.cwd(), '.baseai', 'db');\n\tconst dbFilePath = path.join(baseDir, `${memoryName}.json`);\n\n\t// Ensure the directory exists\n\tawait fs.mkdir(baseDir, { recursive: true });\n\n\t// Check if the file exists, if not, create it with default data\n\ttry {\n\t\tawait fs.access(dbFilePath);\n\t} catch (error) {\n\t\t// File doesn't exist, create it with default data\n\t\tawait fs.writeFile(dbFilePath, JSON.stringify(defaultData, null, 2));\n\t}\n\n\tconst adapter = new JSONFile<Schema>(dbFilePath);\n\tconst db = new Low(adapter, defaultData);\n\n\t// Read the existing data or initialize with default\n\tawait db.read();\n\n\t// If the file was empty or invalid JSON, write the default data\n\tif (db.data === null) {\n\t\tdb.data = defaultData;\n\t\tawait db.write();\n\t}\n\n\treturn db;\n}\n\n// Read an existing database\nexport async function readDb(dbPath: string): Promise<Low<Schema>> {\n\tconst adapter = new JSONFile<Schema>(dbPath);\n\tconst db = new Low(adapter, defaultData);\n\tawait db.read();\n\treturn db;\n}\n\n// Delete a database\nexport async function deleteDb(dbPath: string): Promise<void> {\n\ttry {\n\t\tawait fs.unlink(dbPath);\n\t\tconsole.log(`Database at ${dbPath} has been deleted.`);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\tconsole.log(`No database found at ${dbPath}. Nothing to delete.`);\n\t\t} else {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\n// Load a database\nexport async function loadDb(memoryName: string) {\n\ttry {\n\t\tconst memoryDbPath = getMemoryDbPath(memoryName);\n\t\tawait fs.access(memoryDbPath);\n\t\treturn await readDb(memoryDbPath);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\treturn await createDb(memoryName);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n// CRUD operations for documents\nexport async function addDocument({\n\tdb,\n\tdocName\n}: {\n\tdb: Low<Schema>;\n\tdocName: string;\n}): Promise<void> {\n\tif (db.data.documents[docName]) {\n\t\tp.log.info(`[SKIPPED] DOC: ${color.cyan(docName)} already exists.`);\n\t\treturn;\n\t}\n\tdb.data.documents[docName] = { name: docName, chunkIds: [] };\n\tawait db.write();\n}\n\nexport function getDocument(\n\tdb: Low<Schema>,\n\tdocName: string\n): Document | undefined {\n\treturn db.data.documents[docName];\n}\n\nexport async function deleteDocumentFromDB({\n\tdb,\n\tdocName\n}: {\n\tdb: Low<Schema>;\n\tdocName: string;\n}): Promise<void> {\n\tif (!db.data.documents[docName]) {\n\t\tthrow new Error(`Document with name \"${docName}\" does not exist`);\n\t}\n\n\t// Delete all chunks associated with the document\n\tfor (const chunkId of db.data.documents[docName].chunkIds) {\n\t\tdelete db.data.chunks[chunkId];\n\t}\n\n\tdelete db.data.documents[docName];\n\tawait db.write();\n}\n\nexport async function addChunksBulk(\n\t{\n\t\tdb,\n\t\tdocName,\n\t\tchunks\n\t}: { db: Low<Schema>; docName: string; chunks: Omit<Chunk, 'id'>[] } // Array of chunks, each omitting the id field\n): Promise<void> {\n\tif (!db.data.documents[docName]) {\n\t\tthrow new Error(`Document with name \"${docName}\" does not exist`);\n\t}\n\n\tfor (const chunk of chunks) {\n\t\tconst id = crypto.randomUUID();\n\t\tconst newChunk = ChunkSchema.parse({ ...chunk, id });\n\t\tdb.data.chunks[id] = newChunk;\n\t\tdb.data.documents[docName].chunkIds.push(id);\n\t}\n\n\tawait db.write();\n}\n\nexport async function getDocumentsFromMemory(\n\tmemoryNames: string[]\n): Promise<MemoryChunk[]> {\n\tconst memoryChunks: MemoryChunk[] = [];\n\n\t// Load each memory and get the documents\n\tfor (const memoryName of memoryNames) {\n\t\t// Load the memory\n\t\tconst db: Low<Schema> = await loadDb(memoryName);\n\n\t\t// Process the documents\n\t\tfor (const [docName, document] of Object.entries(db.data.documents)) {\n\t\t\t// Get the chunks for the document\n\t\t\tconst chunks = document.chunkIds.map(id => {\n\t\t\t\tconst chunk = db.data.chunks[id];\n\t\t\t\treturn {\n\t\t\t\t\ttext: chunk.text,\n\t\t\t\t\tembedding: chunk.embedding,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\tmemoryName,\n\t\t\t\t\t\tdocName\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t});\n\n\t\t\t// Add the processed document to the list\n\t\t\tmemoryChunks.push(...chunks);\n\t\t}\n\t}\n\n\t//  Return the processed documents\n\treturn memoryChunks;\n}\n\nexport function cosineSimilaritySearch({\n\tchunks,\n\tqueryEmbedding,\n\ttopK\n}: {\n\tchunks: MemoryChunk[];\n\tqueryEmbedding: number[];\n\ttopK: number;\n}): SimilarChunk[] {\n\t// Return empty array if topK is invalid or no chunks are provided\n\tif (topK <= 0 || chunks.length === 0) {\n\t\treturn [];\n\t}\n\n\t// Calculate cosine similarity for each chunk\n\tconst chunksWithCosineSimilarity: SimilarChunk[] = chunks.map(chunk => ({\n\t\ttext: chunk.text,\n\t\tattributes: chunk.attributes,\n\t\tsimilarity: cosineSimilarity(chunk.embedding, queryEmbedding) || 0\n\t}));\n\n\t// Sort chunks by similarity (descending order)\n\tchunksWithCosineSimilarity.sort((a, b) => b.similarity - a.similarity);\n\n\t// Return top K results\n\treturn chunksWithCosineSimilarity.slice(0, topK);\n}\n\n// Get the path of the db file for a memory\nexport function getMemoryDbPath(memoryName: string): string {\n\t// Process.cwd() returns the current working directory of the Node.js process.\n\t// This is the directory from which the script is run. It is always the root of the project.\n\n\t// Path is cwd()/.baseai/db/{memoryName}.json\n\tconst projectRootPath = process.cwd();\n\n\t// Db file path\n\tconst memoryDBPath = path.join(\n\t\tprojectRootPath,\n\t\t'.baseai',\n\t\t'db',\n\t\t`${memoryName}.json`\n\t);\n\n\treturn memoryDBPath;\n}\n","import { z } from 'zod';\n\nexport const memoryNameSchema = z\n\t.string()\n\t.min(3, 'Memory name must be at least 3 characters long')\n\t.max(50, 'Memory name must not exceed 50 characters')\n\t.regex(\n\t\t/^[a-zA-Z0-9.-]+$/,\n\t\t'Memory name can only contain letters, numbers, dots, and hyphens'\n\t);\n\nexport const docNameSchema = z.string().trim().min(1);\n\nexport const memoryDocSchema = z.object({\n\tmemoryName: memoryNameSchema,\n\tdocumentName: docNameSchema\n});\n\nexport const gitConfigSchema = z.object({\n\tenabled: z.boolean(),\n\tinclude: z\n\t\t.array(z.string().trim().min(1, 'Include pattern must not be empty'))\n\t\t.min(1, 'At least one include pattern must be specified')\n\t\t.describe('Glob patterns to include files in the memory'),\n\tgitignore: z.boolean().optional().default(true),\n\tdeployedAt: z.string().trim().optional().default(''),\n\tembeddedAt: z.string().trim().optional().default('')\n});\n\nexport const documentSchema = z.object({\n\tmeta: z\n\t\t.function()\n\t\t.args(\n\t\t\tz.object({\n\t\t\t\tname: z.string(),\n\t\t\t\tsize: z.string(),\n\t\t\t\tcontent: z.string(),\n\t\t\t\tblob: z.instanceof(Blob),\n\t\t\t\tpath: z.string(),\n\t\t\t})\n\t\t)\n\t\t.returns(z.record(z.string()))\n\t\t.optional()\n});\n\nexport const memoryConfigSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\tgit: gitConfigSchema,\n\tdocuments: documentSchema.optional()\n});\n\nexport type GitConfigI = z.infer<typeof gitConfigSchema>;\n\nexport type MemoryConfigI = z.infer<typeof memoryConfigSchema>;\nexport type DocumentConfigI = z.infer<typeof documentSchema>;\n\nexport type MemoryI = MemoryConfigI;\n","import * as p from '@clack/prompts';\nimport type { LogCategories } from 'types/config';\nimport Logger from './logger';\n\nlet loggerInstance: Logger | null = null;\nlet initializationPromise: Promise<Logger> | null = null;\n\nexport const initLogger = async (): Promise<void> => {\n\tif (!initializationPromise) {\n\t\tinitializationPromise = Logger.initialize();\n\t}\n\tloggerInstance = await initializationPromise;\n};\n\nconst getLogger = (): Logger => {\n\tif (!loggerInstance) {\n\t\tp.cancel('Logger has not been initialized. Call initLogger() first.');\n\t\tprocess.exit(1);\n\t}\n\treturn loggerInstance;\n};\n\nexport const logger = (\n\tcategory: LogCategories,\n\tvalue?: unknown,\n\tlogHeader?: string\n) => {\n\tgetLogger().log(category, value, logHeader);\n};\n","import chalk from 'chalk';\nimport util from 'util';\nimport { loadConfig } from './config/config-handler';\nimport type { LogCategories, LoggerConfig } from 'types/config';\nimport sym from 'log-symbols';\nconst blueI = chalk.blue.inverse;\n\nconst sensitiveWords = [\n\t'sensitive',\n\t'secret',\n\t'hide',\n\t'private',\n\t'password',\n\t'token',\n\t'key',\n\t'auth',\n\t'authorization',\n\t'redact'\n];\n\nclass Logger {\n\tprivate static instance: Logger;\n\tprivate config: LoggerConfig;\n\n\tprivate constructor(config: LoggerConfig) {\n\t\tthis.config = config;\n\t}\n\n\tpublic static async initialize(): Promise<Logger> {\n\t\tif (!Logger.instance) {\n\t\t\tconst baseAIConfig = await loadConfig();\n\t\t\tLogger.instance = new Logger(baseAIConfig.log);\n\t\t}\n\t\treturn Logger.instance;\n\t}\n\n\tprivate formatValue(value: unknown): string {\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\treturn util.inspect(value, { colors: true, depth: null });\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\treturn chalk.green(`\"${value}\"`);\n\t\t}\n\t\tif (typeof value === 'number') {\n\t\t\treturn chalk.yellow(value.toString());\n\t\t}\n\t\tif (typeof value === 'boolean') {\n\t\t\treturn chalk.cyan(value.toString());\n\t\t}\n\t\treturn String(value);\n\t}\n\n\tprivate isSensitiveData(key: string): boolean {\n\t\treturn sensitiveWords.some(word => key.toLowerCase().includes(word));\n\t}\n\n\tprivate formatAndRedactSensitiveData(\n\t\tvalue: unknown,\n\t\tisSensitive: boolean\n\t): string {\n\t\treturn isSensitive && !this.config.logSensitiveData\n\t\t\t? chalk.red('======REDACTED======')\n\t\t\t: this.formatValue(value);\n\t}\n\n\tprivate isCategoryEnabled(category: LogCategories): boolean {\n\t\tconst parts = category.split('.');\n\t\tlet partialCategory = '';\n\n\t\tfor (const part of parts) {\n\t\t\tpartialCategory += (partialCategory ? '.' : '') + part;\n\t\t\tif (partialCategory in this.config) {\n\t\t\t\tconst value = this.config[partialCategory as LogCategories];\n\t\t\t\tif (typeof value === 'boolean') {\n\t\t\t\t\tif (value === false) {\n\t\t\t\t\t\t// console.log(\n\t\t\t\t\t\t// \t`Category ${category} is false due to ${partialCategory}`\n\t\t\t\t\t\t// );\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// console.log(`Category ${category} is true (default or explicitly set)`);\n\t\treturn true;\n\t}\n\n\tprivate logValue(\n\t\tcategory: string,\n\t\tvalue: unknown,\n\t\tlogHeader?: string\n\t): void {\n\t\tconst formattedValue = this.formatAndRedactSensitiveData(\n\t\t\tvalue,\n\t\t\tthis.isSensitiveData(logHeader || category)\n\t\t);\n\t\tconst header = logHeader ? `${chalk.blue.bold(logHeader)}` : '';\n\t\tconsole.log(\n\t\t\t`\\n${sym.info} ${blueI(` ${category} `)} ${header}\\n${formattedValue}`\n\t\t);\n\t}\n\n\tpublic log(\n\t\tcategory: LogCategories,\n\t\tvalue: unknown,\n\t\tlogHeader?: string\n\t): void {\n\t\tif (!this.config.isEnabled || !this.isCategoryEnabled(category)) return;\n\n\t\tthis.logValue(category, value, logHeader);\n\t}\n}\n\nexport default Logger;\n","import { MEMORYSETS } from './constants';\nimport * as p from '@clack/prompts';\n\nexport async function generateLocalEmbeddings(chunks: string[]): Promise<\n\t{\n\t\tembedding: number[];\n\t}[]\n> {\n\ttry {\n\t\t// Verify that ollama is running and emebeddings model is enabled.\n\t\tawait getOllamaEmbeddings('test');\n\n\t\t// Generate embeddings for each chunk\n\t\tconst embeddingsPromise = await Promise.all(\n\t\t\tchunks.map(chunk => getOllamaEmbeddings(chunk))\n\t\t);\n\n\t\t// Extract the embeddings from the response\n\t\tconst embeddings = embeddingsPromise.map(\n\t\t\tembedding => embedding.embedding\n\t\t);\n\n\t\tconst openAIEmbeddingsFormat = embeddings.map(embedding => ({\n\t\t\tembedding\n\t\t}));\n\n\t\treturn openAIEmbeddingsFormat;\n\t} catch (error) {\n\t\tconsole.error('Error generating embeddings:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Fetches embeddings from the Ollama API using the provided prompt.\n *\n * @param {string} prompt - The input string for which embeddings are to be generated.\n * @returns {Promise<any>} A promise that resolves to the embeddings data.\n * @throws Will throw an error if the fetch operation fails or the response is not ok.\n */\nasync function getOllamaEmbeddings(prompt: string): Promise<any> {\n\tconst url = MEMORYSETS.OLLAMA_EMBEDDINGS_ENDPOINT;\n\n\tconst body = JSON.stringify({\n\t\tmodel: MEMORYSETS.OLLAMA_EMBEDDINGS_MODEL,\n\t\tprompt: prompt\n\t});\n\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json'\n\t\t\t},\n\t\t\tbody: body\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`Error: ${response.statusText}`);\n\t\t}\n\n\t\tconst data = await response.json();\n\t\treturn data;\n\t} catch (error) {\n\t\tconsole.error();\n\t\tp.cancel(\n\t\t\t`Error generating embeddings with Ollama. Please ensure that Ollama is running and the embeddings '${MEMORYSETS.OLLAMA_EMBEDDINGS_MODEL}' model is enabled.`\n\t\t);\n\t\tprocess.exit(1);\n\t\tthrow error;\n\t}\n}\n","import * as p from '@clack/prompts';\nimport { getEncoding } from 'js-tiktoken';\nimport OpenAI from 'openai';\nimport { MEMORYSETS } from './constants';\n\nexport const getOpenAIEmbeddings = async (\n\tchunks: string[]\n): Promise<OpenAI.Embeddings.Embedding[]> => {\n\tconst openAiKey = process.env.OPENAI_API_KEY;\n\n\tif (!openAiKey) {\n\t\tp.cancel(\n\t\t\t'OpenAI key not found. Please set the OPENAI_API_KEY environment variable. Only required locally, in production, add it to your keysets https://langbase.com/docs/features/keysets'\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tconst openaiAPIClient = new OpenAI({\n\t\t\tapiKey: openAiKey\n\t\t});\n\n\t\t// Verify that each input has tokens less than the limit.\n\t\tconst enc = getEncoding('cl100k_base');\n\t\tlet totalTokens = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tconst tokens = enc.encode(chunk).length;\n\t\t\ttotalTokens += tokens;\n\t\t\tif (tokens > MEMORYSETS.EMBEDDING_MODEL_TOKENS_LIMIT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Input exceeds the maximum token limit of ${MEMORYSETS.EMBEDDING_MODEL_TOKENS_LIMIT}.`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst openAiEmbeddings: OpenAI.Embeddings.Embedding[] = [];\n\t\tconst batchSize = MEMORYSETS.EMBEDDING_MAX_BATCH_SIZE; // OpenAI limit is 2048.\n\t\tfor (let i = 0; i < chunks.length; i += batchSize) {\n\t\t\tconst batch = chunks.slice(i, i + batchSize);\n\t\t\tconst { data: openAiEmbeddingsBatch } =\n\t\t\t\tawait openaiAPIClient.embeddings.create({\n\t\t\t\t\tmodel: MEMORYSETS.EMBEDDING_MODEL,\n\t\t\t\t\tdimensions: MEMORYSETS.EMBEDDING_DIMENSIONS,\n\t\t\t\t\tinput: batch,\n\t\t\t\t\tencoding_format: MEMORYSETS.EMBEDDING_ENCODING_FORMAT\n\t\t\t\t});\n\t\t\topenAiEmbeddings.push(...openAiEmbeddingsBatch);\n\t\t}\n\n\t\treturn openAiEmbeddings;\n\t} catch (error: any) {\n\t\tconsole.error('Error:', error);\n\t\tthrow new Error('Error getting OpenAI embeddings');\n\t}\n};\n","import fs from 'fs/promises';\nimport path from 'path';\nimport * as p from '@clack/prompts';\nimport { memoryConfigSchema, type MemoryConfigI } from 'types/memory';\nimport {\n\tgenerateUpgradeInstructions,\n\tisOldMemoryConfigFormat,\n\ttype OldMemoryConfig\n} from './handle-old-memory-config';\n\nfunction extractConfigObject(fileContents: string): unknown {\n\ttry {\n\t\t// Remove import statements and exports\n\t\tconst cleanedContent = fileContents\n\t\t\t.replace(/import\\s+.*?['\"];?\\s*/g, '')\n\t\t\t.replace(/export\\s+default\\s+/, '');\n\n\t\t// First try to match a function that returns an object directly with parentheses\n\t\tlet match = cleanedContent.match(\n\t\t\t/(?:const\\s+)?(\\w+)\\s*=\\s*\\(\\s*\\)\\s*(?::\\s*\\w+)?\\s*=>\\s*\\(({[\\s\\S]*?})\\)/\n\t\t);\n\n\t\t// If no direct parentheses match, try to match function with return statement\n\t\tif (!match) {\n\t\t\tmatch = cleanedContent.match(\n\t\t\t\t/(?:const\\s+)?(\\w+)\\s*=\\s*\\(\\s*\\)\\s*(?::\\s*\\w+)?\\s*=>\\s*\\{[\\s\\S]*?return\\s+({[\\s\\S]*?})\\s*;\\s*\\}/\n\t\t\t);\n\t\t}\n\n\t\t// If still no match, try to match direct object assignment\n\t\tif (!match) {\n\t\t\tmatch = cleanedContent.match(\n\t\t\t\t/(?:const\\s+)?(?:memory|\\w+)\\s*=\\s*({[\\s\\S]*?});?$/m\n\t\t\t);\n\t\t}\n\n\t\tif (!match) {\n\t\t\tthrow new Error('Unable to find memory object definition');\n\t\t}\n\n\t\t// The object literal will be in the last capture group\n\t\tconst memoryObjStr = match[match.length - 1];\n\n\t\t// Create a new Function that returns the object literal\n\t\tconst fn = new Function(`return ${memoryObjStr}`);\n\t\treturn fn();\n\t} catch (error) {\n\t\tconsole.error('Parsing error:', error);\n\t\tconsole.error('File contents:', fileContents);\n\t\tthrow new Error(\n\t\t\t`Failed to extract config: ${error instanceof Error ? error.message : 'Unknown error'}`\n\t\t);\n\t}\n}\n\nexport default async function loadMemoryConfig(\n\tmemoryName: string\n): Promise<MemoryConfigI> {\n\ttry {\n\t\tconst memoryDir = path.join(\n\t\t\tprocess.cwd(),\n\t\t\t'baseai',\n\t\t\t'memory',\n\t\t\tmemoryName\n\t\t);\n\t\tconst indexFilePath = path.join(memoryDir, 'index.ts');\n\n\t\tawait fs.access(indexFilePath);\n\t\tconst fileContents = await fs.readFile(indexFilePath, 'utf-8');\n\t\tconst configObj = extractConfigObject(fileContents);\n\n\t\t// Try to parse with new schema first\n\t\ttry {\n\t\t\treturn memoryConfigSchema.parse(configObj);\n\t\t} catch (parseError) {\n\t\t\tif (!configObj) throw parseError;\n\n\t\t\t// If parsing fails, check if it's an old format\n\t\t\tif (isOldMemoryConfigFormat(configObj)) {\n\t\t\t\tp.note(\n\t\t\t\t\tgenerateUpgradeInstructions(configObj as OldMemoryConfig)\n\t\t\t\t);\n\t\t\t\tp.cancel(\n\t\t\t\t\t'Deployment cancelled. Please update your memory config file to the new format.'\n\t\t\t\t);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\t// If it's neither new nor old format, throw the original error\n\t\t\tthrow parseError;\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tp.cancel(`Failed to load memory '${memoryName}': ${error.message}`);\n\t\t} else {\n\t\t\tp.cancel(`Failed to load memory '${memoryName}': Unknown error`);\n\t\t}\n\t\tprocess.exit(1);\n\t}\n}\n","/**\n * Represents the old memory configuration format for backward compatibility.\n */\nexport interface OldMemoryConfig {\n\tname: string;\n\tdescription?: string;\n\tconfig?: OldConfigObject;\n}\n\ninterface OldConfigObject {\n\tuseGitRepo: boolean;\n\tdirToTrack: string;\n\textToTrack: string[] | ['*'];\n\tdeployedCommitHash?: string;\n\tembeddedCommitHash?: string;\n}\n\n/**\n * Type guard to check if an object is of type `OldConfigObject`.\n *\n * @param obj - The object to check.\n * @returns `true` if the object is an `OldConfigObject`, otherwise `false`.\n */\nfunction isOldConfigObject(obj: unknown): obj is OldConfigObject {\n\treturn (\n\t\ttypeof obj === 'object' &&\n\t\tobj !== null &&\n\t\t'useGitRepo' in obj &&\n\t\ttypeof (obj as OldConfigObject).useGitRepo === 'boolean' &&\n\t\t'dirToTrack' in obj &&\n\t\ttypeof (obj as OldConfigObject).dirToTrack === 'string' &&\n\t\t'extToTrack' in obj &&\n\t\tArray.isArray((obj as OldConfigObject).extToTrack)\n\t);\n}\n\n/**\n * Checks if an object conforms to the old memory configuration format.\n *\n * @param obj - The object to check.\n * @returns `true` if the object is in the old memory configuration format, otherwise `false`.\n */\nexport function isOldMemoryConfigFormat(obj: unknown): boolean {\n\tif (\n\t\ttypeof obj !== 'object' ||\n\t\tobj === null ||\n\t\t!('name' in obj) ||\n\t\t!('config' in obj)\n\t) {\n\t\treturn false;\n\t}\n\n\tconst typedObj = obj as { name: unknown; config: unknown };\n\n\treturn (\n\t\ttypeof typedObj.name === 'string' &&\n\t\t(typedObj.config === undefined || isOldConfigObject(typedObj.config))\n\t);\n}\n\n/**\n * Generates upgrade instructions for converting an old memory configuration to the new format.\n *\n * @param oldConfig - The old memory configuration.\n * @returns A string containing the upgrade instructions.\n */\nexport function generateUpgradeInstructions(\n\toldConfig: OldMemoryConfig\n): string {\n\tif (!oldConfig.config) {\n\t\treturn 'Invalid memory config.';\n\t}\n\n\tconst newConfigExample = {\n\t\tname: oldConfig.name,\n\t\tdescription: oldConfig.description || 'Your memory description',\n\t\tgit: {\n\t\t\tenabled: oldConfig.config.useGitRepo,\n\t\t\tinclude:\n\t\t\t\toldConfig.config.extToTrack[0] === '*'\n\t\t\t\t\t? [`${oldConfig.config.dirToTrack}/**/*`]\n\t\t\t\t\t: oldConfig.config.extToTrack.map(\n\t\t\t\t\t\t\text => `${oldConfig.config?.dirToTrack}/**/*${ext}`\n\t\t\t\t\t\t),\n\t\t\tgitignore: true,\n\t\t\tdeployedAt: oldConfig.config.deployedCommitHash || '',\n\t\t\tembeddedAt: oldConfig.config.embeddedCommitHash || ''\n\t\t}\n\t};\n\n\treturn `\nYour memory config is using an outdated format in baseai/memory/${oldConfig.name}/index.ts. Please update the file to this new format:\n\n${JSON.stringify(newConfigExample, null, 2)}\n\nKey changes:\n- Removed nested 'config' object structure\n- Git-related fields are now grouped under a 'git' object\n- 'useGitRepo' is now 'git.enabled'\n- 'dirToTrack' and 'extToTrack' are combined into 'git.include' glob patterns\n- 'deployedCommitHash' is now 'git.deployedAt'\n- 'embeddedCommitHash' is now 'git.embeddedAt'\n- Added new 'git.gitignore' field (defaults to true)\n\nFor more information, refer to the documentation: https://baseai.dev/docs/guides/memory-from-git\n`;\n}\n","import chalk from 'chalk';\nimport Table from 'cli-table3';\nimport * as p from '@clack/prompts';\n\n/**\n * Prints a diff table comparing localDocs and prodDocs.\n * \n * @param localDocs - The array of local documents.\n * @param prodDocs - The array of production documents.\n */\nexport function printDiffTable(localDocs: string[], prodDocs: string[]) {\n\tconst allItems = new Set([...localDocs, ...prodDocs]);\n\tconst tableData = Array.from(allItems).map(item => [\n\t\tlocalDocs.includes(item) ? item : '',\n\t\tprodDocs.includes(item) ? item : ''\n\t]);\n\n\tconst table = new Table({\n\t\thead: [chalk.cyan('Local'), chalk.cyan('Prod')],\n\t\tchars: {\n\t\t\ttop: '═',\n\t\t\t'top-mid': '╤',\n\t\t\t'top-left': '╔',\n\t\t\t'top-right': '╗',\n\t\t\tbottom: '═',\n\t\t\t'bottom-mid': '╧',\n\t\t\t'bottom-left': '╚',\n\t\t\t'bottom-right': '╝',\n\t\t\tleft: '║',\n\t\t\t'left-mid': '╟',\n\t\t\tmid: '─',\n\t\t\t'mid-mid': '┼',\n\t\t\tright: '║',\n\t\t\t'right-mid': '╢',\n\t\t\tmiddle: '│'\n\t\t}\n\t});\n\n\ttableData.forEach(row => table.push(row));\n\n\tp.log.message(`Prod and local are out of sync.`);\n\tp.log.message(`\\n${table.toString()}`);\n}\n","import build, { buildMemory } from '@/build';\nimport { OLLAMA } from '@/dev/data/models';\nimport { dlog } from '@/dev/utils/dlog';\nimport { cyan, dim, dimItalic, green } from '@/utils/formatting';\nimport { heading } from '@/utils/heading';\nimport { compareDocumentLists } from '@/utils/memory/compare-docs-list';\nimport { MEMORYSETS } from '@/utils/memory/constants';\nimport {\n\tgetMemoryFileNames,\n\tloadMemoryFiles,\n\ttype MemoryDocumentI\n} from '@/utils/memory/load-memory-files';\nimport { printDiffTable } from '@/utils/memory/print-diff-table';\nimport * as p from '@clack/prompts';\nimport fs from 'fs/promises';\nimport fetch from 'node-fetch';\nimport path from 'path';\nimport color from 'picocolors';\nimport { type MemoryI } from 'types/memory';\nimport type { Pipe, PipeOld } from 'types/pipe';\nimport {\n\thandleGitSyncMemories,\n\tupdateDeployedCommitHash\n} from '@/utils/memory/git-sync/handle-git-sync-memories';\nimport { handleSingleDocDeploy } from './document';\nimport {\n\tgenerateUpgradeInstructions,\n\tisOldMemoryConfigFormat\n} from '@/utils/memory/handle-old-memory-config';\nimport {\n\tretrieveAuthentication,\n\ttype Account\n} from '@/utils/retrieve-credentials';\n\ninterface ErrorResponse {\n\terror?: { message: string };\n}\n\ntype Spinner = ReturnType<typeof p.spinner>;\n\nasync function deploy({\n\toverwrite = false\n}: {\n\toverwrite: boolean;\n}): Promise<void> {\n\tconst spinner = p.spinner();\n\n\tp.intro(heading({ text: 'DEPLOY', sub: 'Deploy your BaseAI project' }));\n\n\ttry {\n\t\t// Build Pipes and Memory.\n\t\tawait build({ calledAsCommand: false });\n\t\tconst buildDir = path.join(process.cwd(), '.baseai');\n\n\t\tconst pipesDir = path.join(buildDir, 'pipes');\n\t\tconst pipes = await readPipesDirectory({ spinner, pipesDir });\n\t\tif (!pipes) {\n\t\t\tp.outro(\n\t\t\t\t`No pipes found. Skipping deployment of pipes. \\nAdd a pipe by running: ${cyan(`npx baseai@latest pipe`)} command`\n\t\t\t);\n\t\t}\n\n\t\tconst memoryDir = path.join(buildDir, 'memory');\n\t\tconst memory = await readMemoryDirectory({\n\t\t\tspinner,\n\t\t\tmemoryDir\n\t\t});\n\n\t\tconst toolsDir = path.join(buildDir, 'tools');\n\t\tconst tools = await readToolsDirectory({ spinner, toolsDir });\n\n\t\tconst account = await retrieveAuthentication({ spinner });\n\t\tif (!account) {\n\t\t\tp.outro(\n\t\t\t\t`No account found. Skipping deployment. \\n Run: ${cyan('npx baseai@latest auth')}`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tif (memory && memory.length > 0) {\n\t\t\tawait deployMemories({\n\t\t\t\tspinner,\n\t\t\t\tmemory,\n\t\t\t\tmemoryDir,\n\t\t\t\taccount,\n\t\t\t\toverwrite\n\t\t\t});\n\t\t}\n\t\tif (pipes) await deployPipes({ spinner, pipes, pipesDir, account });\n\n\t\tp.outro(\n\t\t\theading({ text: 'DEPLOYED', sub: 'successfully', green: true })\n\t\t);\n\n\t\tp.log.warning(\n\t\t\tdimItalic(\n\t\t\t\t`Make sure ${cyan(`LANGBASE_API_KEY`)} exists in your production environment.`\n\t\t\t)\n\t\t);\n\n\t\tp.log.info(\n\t\t\t`${dim(`Successfully deployed:`)}\n${dim(`- ${green(pipes?.length)} pipe${pipes?.length !== 1 ? 's' : ''}\n- ${green(tools?.length ?? 0)} tool${tools?.length !== 1 ? 's' : ''}\n- ${green(memory?.length ?? 0)} memory${memory?.length !== 1 ? 'sets' : ''}`)}`\n\t\t);\n\t} catch (error) {\n\t\thandleError({\n\t\t\tspinner,\n\t\t\tmessage: 'An unexpected error occurred',\n\t\t\terror\n\t\t});\n\t}\n}\n\nasync function readPipesDirectory({\n\tspinner,\n\tpipesDir\n}: {\n\tspinner: Spinner;\n\tpipesDir: string;\n}): Promise<string[] | null> {\n\tspinner.start('Reading pipes directory');\n\ttry {\n\t\tconst files = await fs.readdir(pipesDir);\n\t\t// Filter out non-json files\n\t\tconst pipes = files.filter(file => path.extname(file) === '.json');\n\n\t\tspinner.stop(\n\t\t\t`Found ${pipes.length} pipe${pipes.length !== 1 ? 's' : ''}`\n\t\t);\n\t\treturn pipes;\n\t} catch (error) {\n\t\thandleDirectoryReadError({ spinner, dir: pipesDir, error });\n\t\treturn null;\n\t}\n}\n\nasync function readToolsDirectory({\n\tspinner,\n\ttoolsDir\n}: {\n\tspinner: Spinner;\n\ttoolsDir: string;\n}): Promise<string[] | null> {\n\tspinner.start('Reading tools directory');\n\ttry {\n\t\tconst files = await fs.readdir(toolsDir);\n\t\t// Filter out non-json files\n\t\tconst tools = files.filter(file => path.extname(file) === '.json');\n\n\t\tspinner.stop(\n\t\t\t`Found ${tools.length} tool${tools.length !== 1 ? 's' : ''}`\n\t\t);\n\t\treturn tools;\n\t} catch (error) {\n\t\thandleDirectoryReadError({ spinner, dir: toolsDir, error });\n\t\treturn null;\n\t}\n}\n\nasync function deployPipes({\n\tspinner,\n\tpipes,\n\tpipesDir,\n\taccount\n}: {\n\tspinner: Spinner;\n\tpipes: string[];\n\tpipesDir: string;\n\taccount: Account;\n}): Promise<void> {\n\tfor (const pipe of pipes) {\n\t\tif (path.extname(pipe) === '.json') {\n\t\t\tawait new Promise(resolve => setTimeout(resolve, 500)); // To avoid rate limiting\n\t\t\tawait deployPipe({ spinner, pipe, pipesDir, account });\n\t\t}\n\t}\n}\n\nasync function deployPipe({\n\tspinner,\n\tpipe,\n\tpipesDir,\n\taccount\n}: {\n\tspinner: Spinner;\n\tpipe: string;\n\tpipesDir: string;\n\taccount: Account;\n}): Promise<void> {\n\tconst filePath = path.join(pipesDir, pipe);\n\tspinner.start(`Processing pipe: ${pipe}`);\n\ttry {\n\t\tconst pipeContent = await fs.readFile(filePath, 'utf-8');\n\t\tconst pipeObject = JSON.parse(pipeContent) as Pipe;\n\n\t\tif (!pipeObject) {\n\t\t\thandleInvalidConfig({ spinner, name: pipe, type: 'pipe' });\n\t\t\treturn;\n\t\t}\n\n\t\tspinner.stop(`Processed pipe: ${pipe}`);\n\t\tspinner.start(`Deploying pipe: ${pipeObject.name}`);\n\n\t\tif (pipeObject.model.includes(OLLAMA)) {\n\t\t\tspinner.stop(\n\t\t\t\t`Local Ollama model found: ${pipeObject.model}. It can not be deployed.`\n\t\t\t);\n\t\t\tspinner.start(\n\t\t\t\t`Replacing Ollama model with OpenAI gpt-4o-mini model for deployment.`\n\t\t\t);\n\t\t\tpipeObject.model = 'openai:gpt-4o-mini';\n\t\t}\n\n\t\ttry {\n\t\t\t// Wait for 500 ms to avoid rate limiting\n\t\t\tawait new Promise(resolve => setTimeout(resolve, 500));\n\t\t\tconst newPipe = await upsertPipe({\n\t\t\t\tpipe: pipeObject,\n\t\t\t\taccount\n\t\t\t});\n\t\t\tspinner.stop(`Successfully deployed pipe: ${newPipe.name}`);\n\t\t} catch (error) {\n\t\t\thandleDeploymentError({\n\t\t\t\tspinner,\n\t\t\t\tname: pipeObject.name,\n\t\t\t\terror,\n\t\t\t\ttype: 'pipe'\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\thandleFileProcessingError({ spinner, name: pipe, error });\n\t}\n}\n\nfunction getApiUrls(pipeName: string) {\n\treturn {\n\t\tcreateUrl: `https://api.langbase.com/v1/pipes`,\n\t\tupdateUrl: `https://api.langbase.com/v1/pipes/${pipeName}`\n\t};\n}\n\nasync function upsertPipe({ pipe, account }: { pipe: Pipe; account: Account }) {\n\tconst { createUrl } = getApiUrls(pipe.name);\n\n\ttry {\n\t\tconst createResponse = await fetch(createUrl, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\tAuthorization: `Bearer ${account.apiKey}`\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\t...pipe,\n\t\t\t\tupsert: true\n\t\t\t})\n\t\t});\n\n\t\tif (createResponse.ok) {\n\t\t\treturn (await createResponse.json()) as any;\n\t\t}\n\n\t\tconst errorData = (await createResponse.json()) as ErrorResponse;\n\n\t\tthrow new Error(\n\t\t\t`HTTP error! status: ${createResponse.status}, message: ${errorData.error?.message}`\n\t\t);\n\t} catch (error) {\n\t\tconsole.error('Error in createNewPipe:', error);\n\t\tthrow error;\n\t}\n}\n\nasync function updateExistingPipe({\n\tupdateUrl,\n\tpipe,\n\taccount\n}: {\n\tupdateUrl: string;\n\tpipe: PipeOld;\n\taccount: Account;\n}): Promise<PipeOld> {\n\tp.log.info(`Pipe \"${pipe.name}\" already exists. Updating instead.`);\n\n\tconst updateResponse = await fetch(updateUrl, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAuthorization: `Bearer ${account.apiKey}`\n\t\t},\n\t\tbody: JSON.stringify(pipe)\n\t});\n\n\tif (!updateResponse.ok) {\n\t\tconst error = await updateResponse.text();\n\t\tthrow new Error(\n\t\t\t`HTTP error! status: ${updateResponse.status}, message: ${error}`\n\t\t);\n\t}\n\n\treturn (await updateResponse.json()) as PipeOld;\n}\n\nexport function handleError({\n\tspinner,\n\tmessage,\n\terror\n}: {\n\tspinner: Spinner;\n\tmessage: string;\n\terror: unknown;\n}): void {\n\tspinner.stop(message);\n\tp.log.error(`${message}: ${(error as Error).message}`);\n}\n\nfunction handleDirectoryReadError({\n\tspinner,\n\tdir,\n\terror\n}: {\n\tspinner: Spinner;\n\tdir: string;\n\terror: unknown;\n}): void {\n\tspinner.stop('Failed to read build directory');\n\tif ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\tp.log.error(`BaseAI Directory not found: ${dir}`);\n\t\tp.log.info(\n\t\t\t`Run from the root of your project where the ${color.cyan('baseai')} directory is located.`\n\t\t);\n\t} else {\n\t\tp.log.error(`Error reading directory: ${(error as Error).message}`);\n\t}\n}\n\nexport function handleInvalidConfig({\n\tspinner,\n\tname,\n\ttype\n}: {\n\tspinner: Spinner;\n\tname: string;\n\ttype: 'pipe' | 'memory';\n}): void {\n\tspinner.stop(`Failed to extract ${type} configuration from ${name}`);\n\tp.log.error(`Invalid ${type} configuration`);\n}\n\nexport function handleDeploymentError({\n\tspinner,\n\terror,\n\tname,\n\ttype\n}: {\n\tspinner: Spinner;\n\tname: string;\n\terror: unknown;\n\ttype: 'pipe' | 'memory';\n}): void {\n\tspinner.stop(`Failed to deploy ${type}: ${name}`);\n\tp.log.error(`Deployment error: ${(error as Error).message}`);\n\tprocess.exit(0);\n}\n\nfunction handleFileProcessingError({\n\tspinner,\n\tname,\n\terror\n}: {\n\tspinner: Spinner;\n\tname: string;\n\terror: unknown;\n}): void {\n\tspinner.stop(`Error processing ${name}`);\n\tp.log.error(`File processing error: ${(error as Error).message}`);\n}\n\nexport async function readMemoryDirectory({\n\tspinner,\n\tmemoryDir\n}: {\n\tspinner: Spinner;\n\tmemoryDir: string;\n}): Promise<string[] | null> {\n\tspinner.start('Reading memory directory');\n\ttry {\n\t\tconst memory = await fs.readdir(memoryDir);\n\t\tspinner.stop();\n\t\treturn memory;\n\t} catch (error) {\n\t\thandleDirectoryReadError({ spinner, dir: memoryDir, error });\n\t\treturn null;\n\t}\n}\n\nasync function deployMemories({\n\tspinner,\n\tmemory,\n\tmemoryDir,\n\taccount,\n\toverwrite\n}: {\n\tspinner: Spinner;\n\tmemory: string[];\n\tmemoryDir: string;\n\taccount: Account;\n\toverwrite: boolean;\n}): Promise<void> {\n\tfor (const memoryName of memory) {\n\t\tawait deployMemory({\n\t\t\tspinner,\n\t\t\tmemoryName,\n\t\t\tmemoryDir,\n\t\t\taccount,\n\t\t\toverwrite\n\t\t});\n\t}\n}\n\nexport async function deployMemory({\n\tspinner,\n\tmemoryName,\n\tmemoryDir,\n\taccount,\n\toverwrite\n}: {\n\tspinner: Spinner;\n\tmemoryName: string;\n\tmemoryDir: string;\n\taccount: Account;\n\toverwrite: boolean;\n}): Promise<void> {\n\tconst filePath = path.join(memoryDir, memoryName);\n\tconst memoryNameWithoutExt = memoryName.split('.')[0]; // Remove .json extension\n\n\tspinner.start(`Processing memory: ${memoryNameWithoutExt}`);\n\ttry {\n\t\tconst memoryContent = await fs.readFile(filePath, 'utf-8');\n\t\tconst memoryObject = JSON.parse(memoryContent) as MemoryI;\n\n\t\tif (!memoryObject) {\n\t\t\thandleInvalidConfig({ spinner, name: memoryName, type: 'memory' });\n\t\t\treturn;\n\t\t}\n\n\t\tp.log.step(`Processing documents for memory: ${memoryNameWithoutExt}`);\n\n\t\tif (isOldMemoryConfigFormat(memoryObject)) {\n\t\t\tp.note(generateUpgradeInstructions(memoryObject));\n\t\t\tp.cancel(\n\t\t\t\t'Deployment cancelled. Please update your memory config file to the new format.'\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tlet filesToDeploy: string[] = [];\n\t\tlet filesToDelete: string[] = [];\n\t\tlet memoryDocs: MemoryDocumentI[] = [];\n\n\t\t// Git sync memories\n\t\tif (memoryObject.git.enabled) {\n\t\t\t// Get names of files to deploy, i.e., changed or new files\n\t\t\tconst {\n\t\t\t\tfilesToDeploy: gitFilesToDeploy,\n\t\t\t\tfilesToDelete: gitFilesToDelete\n\t\t\t} = await handleGitSyncMemories({\n\t\t\t\tmemoryName: memoryNameWithoutExt,\n\t\t\t\tconfig: memoryObject,\n\t\t\t\taccount\n\t\t\t});\n\n\t\t\tfilesToDeploy = gitFilesToDeploy;\n\t\t\tfilesToDelete = gitFilesToDelete;\n\n\t\t\t// Load all documents contents for the memory\n\t\t\tmemoryDocs = await loadMemoryFiles(memoryNameWithoutExt);\n\n\t\t\t// Filter memoryDocs to only include documents in filesToDeploy\n\t\t\t// i.e., changed or new files\n\t\t\tmemoryDocs = memoryDocs.filter(doc =>\n\t\t\t\tfilesToDeploy.includes(doc.name)\n\t\t\t);\n\t\t} else {\n\t\t\t// Non-git sync memories\n\t\t\tmemoryDocs = await loadMemoryFiles(memoryNameWithoutExt);\n\t\t\tfilesToDeploy = memoryDocs.map(doc => doc.name);\n\t\t}\n\n\t\tif (filesToDeploy.length === 0) {\n\t\t\tspinner.stop(\n\t\t\t\t`No documents to deploy for memory: ${memoryNameWithoutExt}. Skipping.`\n\t\t\t);\n\t\t}\n\n\t\tspinner.stop(`Processed memory: ${memoryName.split('.')[0]}`);\n\t\tspinner.start(`Deploying memory: ${memoryObject.name.split('.')[0]}`);\n\n\t\ttry {\n\t\t\tawait upsertMemory({\n\t\t\t\tmemory: memoryObject,\n\t\t\t\tdocuments: memoryDocs,\n\t\t\t\taccount,\n\t\t\t\toverwrite,\n\t\t\t\tisGitSync: memoryObject.git.enabled,\n\t\t\t\tdocsToDelete: filesToDelete\n\t\t\t});\n\t\t\tspinner.stop(`Deployment finished memory: ${memoryObject.name}`);\n\t\t} catch (error) {\n\t\t\tdlog('Error in upsertMemory:', error);\n\t\t\tthrow error;\n\t\t}\n\t} catch (error) {\n\t\thandleDeploymentError({\n\t\t\tspinner,\n\t\t\tname: memoryName,\n\t\t\terror,\n\t\t\ttype: 'memory'\n\t\t});\n\t\tspinner.stop(`Error processing memory: ${memoryName}`);\n\t\tthrow error;\n\t}\n}\n\nexport async function upsertMemory({\n\tmemory,\n\tdocuments,\n\taccount,\n\toverwrite,\n\tisGitSync = false,\n\tdocsToDelete = []\n}: {\n\tmemory: MemoryI;\n\tdocuments: MemoryDocumentI[];\n\taccount: Account;\n\toverwrite: boolean;\n\tisGitSync?: boolean;\n\tdocsToDelete?: string[];\n}): Promise<void> {\n\tconst { createMemory } = getMemoryApiUrls({\n\t\tmemoryName: memory.name\n\t});\n\n\ttry {\n\t\tawait new Promise(resolve => setTimeout(resolve, 800)); // To avoid rate limiting\n\t\tconst createResponse = await fetch(createMemory, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\tAuthorization: `Bearer ${account.apiKey}`\n\t\t\t},\n\t\t\tbody: JSON.stringify(memory)\n\t\t});\n\n\t\tif (!createResponse.ok) {\n\t\t\tconst errorData = (await createResponse.json()) as ErrorResponse;\n\n\t\t\t// If memory already exists, handle it.\n\t\t\tif (errorData.error?.message.includes('already exists')) {\n\t\t\t\tif (!isGitSync) {\n\t\t\t\t\t// Show that Memory already exists\n\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t`Memory \"${memory.name}\" already exists in production.`\n\t\t\t\t\t);\n\t\t\t\t\tawait handleExistingMemoryDeploy({\n\t\t\t\t\t\tmemory,\n\t\t\t\t\t\taccount,\n\t\t\t\t\t\tdocuments,\n\t\t\t\t\t\toverwrite\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// If Git-sync memory, update the existing memory\n\t\t\t\tif (isGitSync) {\n\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t`Memory \"${memory.name}\" already exists. Updating changed documents.`\n\t\t\t\t\t);\n\t\t\t\t\tawait handleGitSyncMemoryDeploy({\n\t\t\t\t\t\tmemory,\n\t\t\t\t\t\taccount,\n\t\t\t\t\t\tdocuments,\n\t\t\t\t\t\toverwrite\n\t\t\t\t\t});\n\n\t\t\t\t\tif (docsToDelete?.length > 0) {\n\t\t\t\t\t\tawait deleteDocumentsFromMemory({\n\t\t\t\t\t\t\tdocuments: docsToDelete,\n\t\t\t\t\t\t\tname: memory.name,\n\t\t\t\t\t\t\taccount\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tawait updateDeployedCommitHash(memory.name);\n\n\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t`Updated deployed commit hash for memory: ${memory.name}`\n\t\t\t\t\t);\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Throw error if not already exists\n\t\t\tthrow new Error(\n\t\t\t\t`HTTP error! status: ${createResponse.status}, message: ${errorData.error?.message}`\n\t\t\t);\n\t\t}\n\n\t\tdlog('Memory created successfully');\n\n\t\t// Upload documents\n\t\tconst { name } = (await createResponse.json()) as MemoryI;\n\t\tawait uploadDocumentsToMemory({ documents, name, account });\n\n\t\tif (isGitSync) {\n\t\t\tif (docsToDelete?.length > 0) {\n\t\t\t\tawait deleteDocumentsFromMemory({\n\t\t\t\t\tdocuments: docsToDelete,\n\t\t\t\t\tname: memory.name,\n\t\t\t\t\taccount\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait updateDeployedCommitHash(memory.name);\n\t\t\tp.log.info(\n\t\t\t\t`Updated deployed commit hash for memory: ${memory.name}`\n\t\t\t);\n\t\t}\n\t} catch (error) {\n\t\tdlog('Error in createNewMemory:', error);\n\t\tthrow error;\n\t}\n}\n\nexport async function uploadDocumentsToMemory({\n\tdocuments,\n\tname,\n\taccount\n}: {\n\tdocuments: MemoryDocumentI[];\n\tname: string;\n\taccount: Account;\n}) {\n\tfor (const doc of documents) {\n\t\ttry {\n\t\t\tp.log.message(`Uploading document: ${doc.name} ....`);\n\t\t\tawait new Promise(resolve => setTimeout(resolve, 800)); // To avoid rate limiting\n\t\t\tconst signedUrl = await getSignedUploadUrl({\n\t\t\t\tdocumentName: doc.name,\n\t\t\t\tmemoryName: name,\n\t\t\t\taccount,\n\t\t\t\tmeta: doc.meta\n\t\t\t});\n\n\t\t\tconst uploadResponse = await uploadDocument(signedUrl, doc.blob);\n\t\t\tdlog(`Upload response status: ${uploadResponse.status}`);\n\n\t\t\tp.log.message(`Uploaded document: ${doc.name}`);\n\t\t} catch (error) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nexport async function deleteDocumentsFromMemory({\n\tdocuments,\n\tname,\n\taccount\n}: {\n\tdocuments: string[];\n\tname: string;\n\taccount: Account;\n}) {\n\tp.log.info(`Deleting documents from memory: ${name}`);\n\n\tfor (const doc of documents) {\n\t\ttry {\n\t\t\tp.log.message(`Deleting document: ${doc} ....`);\n\t\t\tawait new Promise(resolve => setTimeout(resolve, 800)); // To avoid rate limiting\n\n\t\t\tconst deleteResponse = await deleteDocument({\n\t\t\t\tdocumentName: doc,\n\t\t\t\tmemoryName: name,\n\t\t\t\taccount\n\t\t\t});\n\n\t\t\tdlog(`Delete response status: ${deleteResponse.status}`);\n\n\t\t\tp.log.message(`Deleted document: ${doc}`);\n\t\t} catch (error) {\n\t\t\tthrow error;\n\t\t}\n\t}\n\tp.log.info(`Deleted documents from memory: ${name}`);\n}\n\nexport async function handleExistingMemoryDeploy({\n\tmemory,\n\taccount,\n\tdocuments,\n\toverwrite\n}: {\n\tmemory: MemoryI;\n\taccount: Account;\n\tdocuments: MemoryDocumentI[];\n\toverwrite: boolean;\n}) {\n\tp.log.info(`Fetching \"${memory.name}\" memory documents.`);\n\n\t// Fetch the existing documents and compare with the local documents\n\tconst prodDocs = await listMemoryDocuments({\n\t\taccount,\n\t\tmemoryName: memory.name\n\t});\n\n\t// Get the list of local document names\n\tconst localDocs = await getMemoryFileNames(memory.name);\n\n\t// Compare the documents\n\tconst {\n\t\tareListsSame,\n\t\tisProdSubsetOfLocal,\n\t\tisProdSupersetOfLocal,\n\t\tareMutuallyExclusive,\n\t\tareOverlapping\n\t} = compareDocumentLists({\n\t\tlocalDocs,\n\t\tprodDocs\n\t});\n\n\t// If the user wants to overwrite, overwrite the memory.\n\tif (overwrite) {\n\t\tawait overwriteMemory({ memory, documents, account });\n\t\treturn true;\n\t}\n\n\t// If the lists are the same, do nothing and skip deployment.\n\tif (areListsSame) {\n\t\tp.log.info(\n\t\t\t`Documents in local and prod are the same. Skipping deployment for memory: \"${memory.name}\".`\n\t\t);\n\n\t\treturn true;\n\t}\n\n\t// If prod is a subset of local, upload the missing documents.\n\tif (isProdSubsetOfLocal) {\n\t\tawait uploadMissingDocumentsToMemory({\n\t\t\tmemory,\n\t\t\tprodDocs,\n\t\t\tdocuments,\n\t\t\taccount\n\t\t});\n\t\treturn true;\n\t}\n\n\t// If prod is a superset of local or the lists are mutually exclusive, ask the user whether to overwrite.\n\tif (isProdSupersetOfLocal || areMutuallyExclusive || areOverlapping) {\n\t\tawait handleProdSupersetOfLocal({\n\t\t\tmemory,\n\t\t\tlocalDocs,\n\t\t\tprodDocs,\n\t\t\tdocuments,\n\t\t\taccount\n\t\t});\n\t\treturn true;\n\t}\n}\n\nasync function handleProdSupersetOfLocal({\n\tmemory,\n\tlocalDocs,\n\tprodDocs,\n\tdocuments,\n\taccount\n}: {\n\tmemory: MemoryI;\n\tlocalDocs: string[];\n\tprodDocs: string[];\n\tdocuments: MemoryDocumentI[];\n\taccount: Account;\n}) {\n\t// Show the diff table.\n\tprintDiffTable(localDocs, prodDocs);\n\n\t// Inform user, Memory deploy is currently in beta and can currently only overwrite the prod memory.\n\tp.log.warning(\n\t\t`Memory deploy is currently in beta. We only support overwriting the prod memory on Langbase.com.`\n\t);\n\n\t// Ask user to overwrite.\n\tconst shouldOverwrite = await p.confirm({\n\t\tmessage:\n\t\t\t'Do you want to overwrite the prod memory? This will delete all prod documents.',\n\t\tinitialValue: false\n\t});\n\n\tif (!shouldOverwrite) {\n\t\tp.log.message(`Skipping memory deployment for \"${memory.name}\".`);\n\t\treturn;\n\t}\n\n\t// Overwrite the prod memory\n\tawait overwriteMemory({ memory, documents, account });\n}\n\nasync function uploadMissingDocumentsToMemory({\n\tmemory,\n\tprodDocs,\n\tdocuments,\n\taccount\n}: {\n\tmemory: MemoryI;\n\tprodDocs: string[];\n\tdocuments: MemoryDocumentI[];\n\taccount: Account;\n}) {\n\tp.log.info(\n\t\t`Prod has missing documents. Uploading new documents to ${memory.name}.`\n\t);\n\tconst missingDocs = documents.filter(doc => {\n\t\tconst isMissing = !prodDocs.includes(doc.name);\n\t\tif (!isMissing) {\n\t\t\tp.log.message(`Document \"${doc.name}\" already exists. Skipping.`);\n\t\t}\n\t\treturn isMissing;\n\t});\n\n\t// wait for 500 ms to avoid rate limiting\n\tawait new Promise(resolve => setTimeout(resolve, 500));\n\tawait uploadDocumentsToMemory({\n\t\tdocuments: missingDocs,\n\t\tname: memory.name,\n\t\taccount\n\t});\n}\n\nexport async function listMemoryDocuments({\n\taccount,\n\tmemoryName\n}: {\n\taccount: Account;\n\tmemoryName: string;\n}) {\n\tconst { listDocuments } = getMemoryApiUrls({\n\t\tmemoryName: memoryName\n\t});\n\n\t// Wait 500 ms to avoid rate limiting\n\tawait new Promise(resolve => setTimeout(resolve, 500));\n\tconst listResponse = await fetch(listDocuments, {\n\t\tmethod: 'GET',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAuthorization: `Bearer ${account.apiKey}`\n\t\t}\n\t});\n\n\tif (!listResponse.ok) {\n\t\tconst errorData = (await listResponse.json()) as ErrorResponse;\n\n\t\tconst errorMsg = errorData.error?.message;\n\n\t\tif (errorMsg?.includes('Invalid memory name.')) {\n\t\t\tp.log.info(`Memory \"${memoryName}\" does not exist in production.`);\n\t\t\treturn [];\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t`HTTP error! status: ${listResponse.status}, message: ${errorMsg}`\n\t\t);\n\t}\n\n\tconst res = (await listResponse.json()) as { name: string }[];\n\tconst documents = res.map((doc: { name: string }) => doc.name);\n\treturn documents;\n}\n\nasync function getSignedUploadUrl({\n\tdocumentName,\n\tmemoryName,\n\taccount,\n\tmeta\n}: {\n\tdocumentName: string;\n\tmemoryName: string;\n\taccount: Account;\n\tmeta: Record<string, string>;\n}): Promise<string> {\n\tconst { uploadDocument } = getMemoryApiUrls({\n\t\tmemoryName\n\t});\n\n\ttry {\n\t\tconst response = await fetch(uploadDocument, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\tAuthorization: `Bearer ${account.apiKey}`\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tmeta,\n\t\t\t\tmemoryName,\n\t\t\t\tfileName: documentName\n\t\t\t})\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst errorData = (await response.json()) as ErrorResponse;\n\t\t\tthrow new Error(\n\t\t\t\t`HTTP error! status: ${response.status}, message: ${errorData.error?.message}`\n\t\t\t);\n\t\t}\n\t\tconst { signedUrl } = (await response.json()) as { signedUrl: string };\n\n\t\tif (!signedUrl) {\n\t\t\tthrow new Error('Invalid signedUrl received from API');\n\t\t}\n\n\t\treturn signedUrl;\n\t} catch (error) {\n\t\tdlog('Error in getSignedUploadUrl:', error);\n\t\tthrow error;\n\t}\n}\n\nasync function deleteDocument({\n\tdocumentName,\n\tmemoryName,\n\taccount\n}: {\n\tdocumentName: string;\n\tmemoryName: string;\n\taccount: Account;\n}) {\n\tconst { deleteDocument } = getMemoryApiUrls({\n\t\tmemoryName,\n\t\tdocumentName\n\t});\n\n\ttry {\n\t\tconst response = await fetch(deleteDocument, {\n\t\t\tmethod: 'DELETE',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\tAuthorization: `Bearer ${account.apiKey}`\n\t\t\t}\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst errorData = (await response.json()) as ErrorResponse;\n\t\t\tthrow new Error(\n\t\t\t\t`HTTP error! status: ${response.status}, message: ${errorData.error?.message}`\n\t\t\t);\n\t\t}\n\n\t\treturn response;\n\t} catch (error) {\n\t\tdlog('Error in deleteDocument:', error);\n\t\tthrow error;\n\t}\n}\n\nasync function uploadDocument(signedUrl: string, document: Blob) {\n\tlet mimeType = document.type;\n\n\t// Check if the MIME type is supported.\n\tconst isSupportedMimeType =\n\t\tMEMORYSETS.ACCEPTED_MIME_TYPES.includes(mimeType);\n\n\t// If not, default to text/plain.\n\tif (!isSupportedMimeType) {\n\t\tdlog(`Unsupported MIME type ${mimeType}. Defaulting to text/plain`);\n\t\tmimeType = 'text/plain';\n\t}\n\n\ttry {\n\t\tconst response = await fetch(signedUrl, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': mimeType\n\t\t\t},\n\t\t\tbody: document\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst error = await response.text();\n\t\t\tthrow new Error(\n\t\t\t\t`HTTP error! status: ${response.status}, message: ${error}`\n\t\t\t);\n\t\t}\n\n\t\treturn response;\n\t} catch (error) {\n\t\tdlog('Error in uploadDocument:', error);\n\t\tthrow error;\n\t}\n}\n\nexport function getMemoryApiUrls({\n\tmemoryName,\n\tdocumentName\n}: {\n\tmemoryName: string;\n\tdocumentName?: string;\n}) {\n\t// Base URL\n\tconst baseUrl = `https://api.langbase.com/v1`;\n\n\t// Create memory URL\n\tconst createMemory = `${baseUrl}/memory`;\n\n\t// Delete memory URL\n\tconst deleteMemory = `${baseUrl}/memory/${memoryName}`;\n\n\t// Upload document URL\n\tconst uploadDocument = `${baseUrl}/memory/documents`;\n\n\t// List documents URL\n\tconst listDocuments = `${baseUrl}/memory/${memoryName}/documents`;\n\n\t// Delete document URL\n\tconst deleteDocument = `${baseUrl}/memory/${memoryName}/documents/${documentName}`;\n\n\treturn {\n\t\tlistDocuments,\n\t\tdeleteMemory,\n\t\tdeleteDocument,\n\t\tcreateMemory,\n\t\tuploadDocument\n\t};\n}\n\nasync function overwriteMemory({\n\tmemory,\n\tdocuments,\n\taccount\n}: {\n\tmemory: MemoryI;\n\tdocuments: MemoryDocumentI[];\n\taccount: Account;\n}): Promise<void> {\n\tp.log.message(\n\t\t`Overwriting memory \"${memory.name}\" in prod at Langbase.com with local documents.`\n\t);\n\n\t// Delete old memory.\n\tdlog(`Deleting old memory: ${memory.name}`);\n\tconst { deleteMemory } = getMemoryApiUrls({\n\t\tmemoryName: memory.name\n\t});\n\n\t// Wait 500 ms to avoid rate limiting\n\tawait new Promise(resolve => setTimeout(resolve, 500));\n\tconst deleteResponse = await fetch(deleteMemory, {\n\t\tmethod: 'DELETE',\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${account.apiKey}`\n\t\t}\n\t});\n\n\tif (!deleteResponse.ok) {\n\t\tconst error = await deleteResponse.text();\n\t\tthrow new Error(\n\t\t\t`HTTP error! status: ${deleteResponse.status}, message: ${error}`\n\t\t);\n\t}\n\n\tp.log.message(`Overwriting memory: ${memory.name}`);\n\n\t// Reuse same function to create the memory.\n\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\tawait upsertMemory({\n\t\tmemory,\n\t\tdocuments,\n\t\taccount,\n\t\toverwrite: true\n\t});\n}\n\nexport async function handleGitSyncMemoryDeploy({\n\tmemory,\n\taccount,\n\tdocuments,\n\toverwrite\n}: {\n\tmemory: MemoryI;\n\taccount: Account;\n\tdocuments: MemoryDocumentI[];\n\toverwrite: boolean;\n}) {\n\tfor (const doc in documents) {\n\t\tawait new Promise(resolve => setTimeout(resolve, 800)); // To avoid rate limiting\n\t\tawait handleSingleDocDeploy({\n\t\t\tmemory,\n\t\t\taccount,\n\t\t\tdocument: documents[doc],\n\t\t\toverwrite: true // TODO: Implement overwrite for git-sync memories\n\t\t});\n\t}\n}\n\nexport async function deploySingleMemory({\n\tmemoryName,\n\toverwrite\n}: {\n\tmemoryName: string;\n\toverwrite: boolean;\n}): Promise<void> {\n\tconst spinner = p.spinner();\n\n\ttry {\n\t\tp.intro(heading({ text: 'BUILDING', sub: 'baseai...' }));\n\n\t\tawait buildMemory({\n\t\t\tmemoryName: memoryName\n\t\t});\n\n\t\tconsole.log('');\n\t\tp.outro(heading({ text: 'BUILD', sub: 'complete', green: true }));\n\n\t\tp.intro(heading({ text: 'DEPLOY', sub: 'Deploy your BaseAI Memory' }));\n\n\t\tconst buildDir = path.join(process.cwd(), '.baseai');\n\t\tconst memoryDir = path.join(buildDir, 'memory');\n\t\tconst allMemory = await readMemoryDirectory({\n\t\t\tspinner,\n\t\t\tmemoryDir\n\t\t});\n\n\t\t// Check if the memory exists\n\t\tif (!allMemory?.includes(`${memoryName}.json`)) {\n\t\t\tp.log.error(`Memory \"${memoryName}\" not found.`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Retrieve authentication\n\t\tconst account = await retrieveAuthentication({ spinner });\n\t\tif (!account) {\n\t\t\tp.outro(\n\t\t\t\t`No account found. Skipping deployment. \\n Run: ${cyan('npx baseai@latest auth')}`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\t// Call deployMemory function\n\t\tawait deployMemory({\n\t\t\tspinner,\n\t\t\tmemoryName: `${memoryName}.json`,\n\t\t\tmemoryDir,\n\t\t\taccount,\n\t\t\toverwrite\n\t\t});\n\n\t\tp.outro(`Successfully deployed memory: ${memoryName}`);\n\t\tprocess.exit(0);\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\t\tp.log.error(\n\t\t\t\t\t`Directory or file not found. Make sure you're in the correct project directory and the memory exists.`\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tp.log.error(`Error deploying memory: ${error.message}`);\n\t\t\t}\n\t\t} else {\n\t\t\tp.log.error(`An unknown error occurred while deploying memory.`);\n\t\t}\n\t\tprocess.exit(1);\n\t}\n}\n\nexport { deploy };\n","import { execSync } from 'child_process';\nimport * as p from '@clack/prompts';\nimport { saveDeployedCommitHashInMemoryConfig } from './save-deployed-commit-in-config';\nimport { getChangedAndDeletedFilesBetweenCommits } from './get-changed-files-between-commits';\nimport type { MemoryConfigI } from 'types/memory';\nimport { listMemoryDocuments, type Account } from '@/deploy';\nimport { loadMemoryFilesFromCustomDir } from '../load-memory-files';\nimport { listLocalEmbeddedMemoryDocuments } from '../generate-embeddings';\nimport { saveEmbeddedCommitHashInMemoryConfig } from './save-embedded-commit-in-config';\n\nexport async function handleGitSyncMemories({\n\tmemoryName,\n\tconfig,\n\taccount\n}: {\n\tmemoryName: string;\n\tconfig: MemoryConfigI;\n\taccount?: Account; // Undefined for local embed\n}): Promise<{\n\tfilesToDeploy: string[];\n\tfilesToDelete: string[];\n}> {\n\tconst isEmbed = !account;\n\n\t// Check for uncommitted changes\n\ttry {\n\t\tconst hasChanges = execSync('git status --porcelain').toString().trim();\n\t\tif (hasChanges) {\n\t\t\tp.log.error(\n\t\t\t\t`There are uncommitted changes in the Git repository for ${isEmbed ? 'embedding' : 'deploying'} git-synced memory \"${memoryName}\".`\n\t\t\t);\n\t\t\tp.log.info(\n\t\t\t\t`Please commit these changes before ${isEmbed ? 'embedding' : 'deploying'}. Aborting.`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t} catch (error) {\n\t\tp.log.error(\n\t\t\t`Failed to check if there are uncommitted changes: ${error}`\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\tlet filesToDeploy: string[] = [];\n\tlet filesToDelete: string[] = [];\n\n\t// Step 1:\n\t// Fetch the uploaded documents and compare with the local documents\n\t// Handles new files that are not in the prodDocs due to extension and path updates\n\tconst prodDocs = !isEmbed\n\t\t? await listMemoryDocuments({\n\t\t\t\taccount,\n\t\t\t\tmemoryName\n\t\t\t})\n\t\t: await listLocalEmbeddedMemoryDocuments({\n\t\t\t\tmemoryName\n\t\t\t}); // For local embedded docs are prod equivalent\n\n\tconst allFilesWithContent = await loadMemoryFilesFromCustomDir({\n\t\tmemoryName,\n\t\tmemoryConfig: config\n\t});\n\n\tconst allFiles = allFilesWithContent.map(file => file.name);\n\n\t// Get files from allFiles that are not in the prodDocs\n\tconst newFiles = allFiles.filter(\n\t\tfile => !prodDocs.some(doc => doc === file)\n\t);\n\n\t// Step 2.1:\n\t// If there's no deployedCommitHash, user is deploying for the first time\n\t// Deploy all files in the directory\n\tconst lastHashUsed = isEmbed\n\t\t? config.git?.embeddedAt\n\t\t: config.git?.deployedAt;\n\n\tif (!lastHashUsed) {\n\t\tfilesToDeploy = allFiles;\n\t\tp.log.info(\n\t\t\t`Found no previous ${isEmbed ? 'deployed' : 'embedded'} commit. ${isEmbed ? 'Deploying' : 'Embedding'} all ${filesToDeploy.length} files in memory \"${memoryName}\":`\n\t\t);\n\t}\n\t// Step 2.2: Otherwise, get changed files between commits\n\telse {\n\t\tconst { changedFiles, deletedFiles } =\n\t\t\tawait getChangedAndDeletedFilesBetweenCommits({\n\t\t\t\toldCommit: lastHashUsed,\n\t\t\t\tlatestCommit: 'HEAD',\n\t\t\t\tinclude: config.git.include\n\t\t\t});\n\n\t\tfilesToDeploy = changedFiles;\n\t\tfilesToDelete = deletedFiles;\n\n\t\tif (filesToDeploy.length > 0) {\n\t\t\tp.log.info(\n\t\t\t\t`Found ${filesToDeploy.length} changed files for memory \"${memoryName}\":`\n\t\t\t);\n\n\t\t\t// Print the changed file names TODO: Remove because it may clutter the terminal?\n\t\t\tfilesToDeploy.forEach(file => p.log.message(file));\n\t\t} else {\n\t\t\tconst isEmbed = !account;\n\t\t\tp.log.info(\n\t\t\t\t`No file changes detected for memory \"${memoryName}\" since last ${isEmbed ? 'embedding' : 'deployment'}.`\n\t\t\t);\n\t\t}\n\n\t\tif (filesToDelete.length > 0) {\n\t\t\tp.log.info(\n\t\t\t\t`Found ${filesToDelete.length} deleted files for memory \"${memoryName}\":`\n\t\t\t);\n\n\t\t\t// Print the deleted file names TODO: Remove because it may clutter the terminal?\n\t\t\tfilesToDelete.forEach(file => p.log.message(file));\n\t\t} else {\n\t\t\tconst isEmbed = !account;\n\t\t\tp.log.info(\n\t\t\t\t`No deleted file detected for memory \"${memoryName}\" since last ${isEmbed ? 'embedding' : 'deployment'}.`\n\t\t\t);\n\t\t}\n\t}\n\n\t// Step 3\n\t// Combine filesToDeploy with newFiles, avoid duplicates\n\tfilesToDeploy = [...new Set([...filesToDeploy, ...newFiles])];\n\t// Filter the files to be deleted to make sure they are not in filesToDeploy\n\tfilesToDelete = filesToDelete.filter(file => !filesToDeploy.includes(file));\n\n\treturn {\n\t\tfilesToDeploy,\n\t\tfilesToDelete\n\t};\n}\n\nexport async function updateDeployedCommitHash(memoryName: string) {\n\tconst currentCommitHash = execSync('git rev-parse HEAD').toString().trim();\n\tawait saveDeployedCommitHashInMemoryConfig({\n\t\tmemoryName,\n\t\tdeployedCommitHash: currentCommitHash\n\t});\n}\n\nexport async function updateEmbeddedCommitHash(memoryName: string) {\n\tconst currentCommitHash = execSync('git rev-parse HEAD').toString().trim();\n\tawait saveEmbeddedCommitHashInMemoryConfig({\n\t\tmemoryName,\n\t\tembeddedCommitHash: currentCommitHash\n\t});\n}\n","import fs from 'fs/promises';\nimport * as p from '@clack/prompts';\nimport path from 'path';\n\nexport async function saveDeployedCommitHashInMemoryConfig({\n\tmemoryName,\n\tdeployedCommitHash\n}: {\n\tmemoryName: string;\n\tdeployedCommitHash: string;\n}): Promise<void> {\n\ttry {\n\t\tconst memoryDir = path.join(\n\t\t\tprocess.cwd(),\n\t\t\t'baseai',\n\t\t\t'memory',\n\t\t\tmemoryName\n\t\t);\n\t\tconst indexFilePath = path.join(memoryDir, 'index.ts');\n\t\tlet fileContents = await fs.readFile(indexFilePath, 'utf-8');\n\n\t\t// Check if the git block exists\n\t\tif (fileContents.includes('git:')) {\n\t\t\t// Find the git block including its indentation\n\t\t\tconst gitBlockMatch = fileContents.match(/(\\t*)git:\\s*{[^}]*?}/);\n\t\t\tif (gitBlockMatch) {\n\t\t\t\tconst [fullMatch, outerIndent] = gitBlockMatch;\n\t\t\t\tconst innerIndent = outerIndent + '\\t';\n\n\t\t\t\t// Parse existing content\n\t\t\t\tconst contentMatch = fullMatch.match(\n\t\t\t\t\t/{\\s*\\n?\\s*(.*?)\\s*\\n?\\s*}/s\n\t\t\t\t);\n\t\t\t\tlet existingContent = contentMatch ? contentMatch[1] : '';\n\n\t\t\t\tlet contentLines = existingContent\n\t\t\t\t\t.split('\\n')\n\t\t\t\t\t.map(line => line.trim().replace(/,\\s*$/, '')) // Remove trailing commas\n\t\t\t\t\t.filter(Boolean);\n\n\t\t\t\tlet newGitContent: string;\n\n\t\t\t\t// If deployedAt exists, update it while preserving formatting\n\t\t\t\tif (existingContent.includes('deployedAt:')) {\n\t\t\t\t\tcontentLines = contentLines.map(line => {\n\t\t\t\t\t\tif (line.includes('deployedAt:')) {\n\t\t\t\t\t\t\treturn `deployedAt: '${deployedCommitHash}'`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn line;\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Add deployedAt to existing content\n\t\t\t\t\tcontentLines.push(`deployedAt: '${deployedCommitHash}'`);\n\t\t\t\t}\n\n\t\t\t\t// Add commas between lines but not after the last line\n\t\t\t\tnewGitContent = contentLines\n\t\t\t\t\t.map((line, index) => {\n\t\t\t\t\t\tconst isLast = index === contentLines.length - 1;\n\t\t\t\t\t\treturn `${innerIndent}${line}${isLast ? '' : ','}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join('\\n');\n\n\t\t\t\t// Replace the old git block with the new one\n\t\t\t\tfileContents = fileContents.replace(\n\t\t\t\t\t/(\\t*)git:\\s*{[^}]*?}/,\n\t\t\t\t\t`${outerIndent}git: {\\n${newGitContent}\\n${outerIndent}}`\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\t// Add new git config block\n\t\t\tconst match = fileContents.match(\n\t\t\t\t/(?:const\\s+\\w+\\s*=\\s*\\(\\s*\\)\\s*(?::\\s*\\w+)?\\s*=>\\s*\\({[\\s\\S]*?)(}\\))/\n\t\t\t);\n\n\t\t\tif (match) {\n\t\t\t\t// Insert before the closing parenthesis\n\t\t\t\tconst insertPosition =\n\t\t\t\t\tmatch.index! + match[0].length - match[1].length;\n\t\t\t\tconst prefix = fileContents.slice(0, insertPosition);\n\t\t\t\tconst suffix = fileContents.slice(insertPosition);\n\n\t\t\t\t// Match the indentation of nearby properties\n\t\t\t\tconst indentMatch = prefix.match(/\\n(\\t+)[^\\n]+\\n\\s*$/);\n\t\t\t\tconst baseIndent = indentMatch ? indentMatch[1] : '\\t';\n\t\t\t\tconst innerIndent = baseIndent + '\\t';\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t'enabled: false',\n\t\t\t\t\t\"include: ['**/*']\",\n\t\t\t\t\t'gitignore: false',\n\t\t\t\t\t`deployedAt: '${deployedCommitHash}'`\n\t\t\t\t];\n\n\t\t\t\tconst gitConfig = lines\n\t\t\t\t\t.map((line, index) => {\n\t\t\t\t\t\tconst isLast = index === lines.length - 1;\n\t\t\t\t\t\treturn `${innerIndent}${line}${isLast ? '' : ','}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join('\\n');\n\n\t\t\t\tfileContents = `${prefix},\\n${baseIndent}git: {\\n${gitConfig}\\n${baseIndent}}${suffix}`;\n\t\t\t} else {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Could not find appropriate location to insert git config'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Write the updated contents back to the file\n\t\tawait fs.writeFile(indexFilePath, fileContents, 'utf-8');\n\n\t\tp.log.success(`Updated deployedAt hash for memory '${memoryName}'.`);\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tp.cancel(\n\t\t\t\t`Failed to save deployedAt hash for memory '${memoryName}': ${error.message}`\n\t\t\t);\n\t\t} else {\n\t\t\tp.cancel(\n\t\t\t\t`Failed to save deployedAt hash for memory '${memoryName}': Unknown error`\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n","import { execSync } from 'child_process';\n\n/**\n * Retrieves the list of changed and deleted files between two Git commits matching specified glob patterns.\n *\n * @param {Object} params - The parameters for the function.\n * @param {string} params.oldCommit - The old commit reference to compare from.\n * @param {string} [params.latestCommit='HEAD'] - The latest commit reference to compare to. Defaults to 'HEAD'.\n * @param {string[]} params.include - Array of glob patterns to track for changes.\n * @returns {Promise<{ changedFiles: string[]; deletedFiles: string[] }>} - A promise that resolves to an object containing arrays of changed and deleted files.\n * @throws {Error} - Throws an error if the Git command execution fails or if the commit references are invalid.\n */\nexport async function getChangedAndDeletedFilesBetweenCommits({\n\toldCommit,\n\tlatestCommit = 'HEAD',\n\tinclude\n}: {\n\toldCommit: string;\n\tlatestCommit: string;\n\tinclude: string[];\n}): Promise<{ changedFiles: string[]; deletedFiles: string[] }> {\n\ttry {\n\t\t// Validate inputs\n\t\tif (oldCommit === '') {\n\t\t\tthrow new Error('Invalid commit references');\n\t\t}\n\n\t\tif (!Array.isArray(include) || include.length === 0) {\n\t\t\tthrow new Error('Include patterns must be a non-empty array');\n\t\t}\n\n\t\tconst repoPath = process.cwd();\n\n\t\t// Execute the Git commands for changed and deleted files\n\t\tconst changedResult = execSync(\n\t\t\tconstructGitCommand({\n\t\t\t\tinclude,\n\t\t\t\toldCommit,\n\t\t\t\tdiffFilter: 'ACMRT',\n\t\t\t\tlatestCommit\n\t\t\t}),\n\t\t\t{\n\t\t\t\tencoding: 'utf-8',\n\t\t\t\tcwd: repoPath\n\t\t\t}\n\t\t).trim();\n\n\t\tconst deletedResult = execSync(\n\t\t\tconstructGitCommand({\n\t\t\t\tinclude,\n\t\t\t\toldCommit,\n\t\t\t\tdiffFilter: 'D',\n\t\t\t\tlatestCommit\n\t\t\t}),\n\t\t\t{\n\t\t\t\tencoding: 'utf-8',\n\t\t\t\tcwd: repoPath\n\t\t\t}\n\t\t).trim();\n\n\t\t// Process the results\n\t\tconst changedFiles = changedResult\n\t\t\t? changedResult\n\t\t\t\t\t.split('\\n')\n\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t.map(file => file.replace(/\\//g, '-'))\n\t\t\t: [];\n\n\t\tconst deletedFiles = deletedResult\n\t\t\t? deletedResult\n\t\t\t\t\t.split('\\n')\n\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t.map(file => file.replace(/\\//g, '-'))\n\t\t\t: [];\n\n\t\treturn { changedFiles, deletedFiles };\n\t} catch (error) {\n\t\tconsole.error('Error executing Git command:', error);\n\t\tthrow error;\n\t}\n}\n\n// Helper function to construct the Git command for changed files\nconst constructGitCommand = ({\n\tinclude,\n\toldCommit,\n\tdiffFilter,\n\tlatestCommit\n}: {\n\tinclude: string[];\n\toldCommit: string;\n\tdiffFilter: 'ACMRT' | 'D';\n\tlatestCommit: string;\n}) => {\n\tconst baseCommand = `git diff --diff-filter=${diffFilter} --name-only ${oldCommit} ${latestCommit}`;\n\n\t// If there's only one pattern, use it directly\n\tif (include.length === 1) {\n\t\treturn `${baseCommand} -- \"${include[0]}\"`;\n\t}\n\n\t// For multiple patterns, use brace expansion\n\tconst patterns = include.map(pattern => `\"${pattern}\"`).join(' ');\n\treturn `${baseCommand} -- ${patterns}`;\n};\n","import * as p from '@clack/prompts';\nimport figures from 'figures';\nimport color from 'picocolors';\nimport { RecursiveCharacterTextSplitter } from './chunker';\nimport { MEMORYSETS } from './constants';\nimport {\n\taddChunksBulk,\n\taddDocument,\n\tdeleteDocumentFromDB,\n\tgetDocument,\n\tloadDb\n} from './db/lib';\nimport { getOpenAIEmbeddings } from './generate-openai-embeddings';\nimport type { MemoryDocumentI } from './load-memory-files';\nimport { generateLocalEmbeddings } from './generate-local-embeddings';\nimport { loadConfig } from '../config/config-handler';\nimport { dlog } from '@/dev/utils/dlog';\n\nexport async function generateEmbeddings({\n\tmemoryFiles,\n\tmemoryName,\n\toverwrite = false,\n\tuseLocalEmbeddings\n}: {\n\tmemoryFiles: MemoryDocumentI[];\n\tmemoryName: string;\n\toverwrite: boolean;\n\tuseLocalEmbeddings?: boolean;\n}): Promise<string> {\n\tlet memoryDb;\n\tlet totalEmbeddings = 0;\n\tlet totalDocs = memoryFiles.length;\n\tlet successfulDocs = 0;\n\tlet skippedDocs = 0;\n\tlet failedDocs = 0;\n\n\ttry {\n\t\tmemoryDb = await loadDb(memoryName);\n\t} catch (error) {\n\t\tp.cancel(`Failed to load database for memory '${memoryName}'.`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst splitter = new RecursiveCharacterTextSplitter({\n\t\tchunkMaxLength: MEMORYSETS.MIN_CHUNK_LENGTH,\n\t\tchunkOverlap: MEMORYSETS.MIN_CHUNK_OVERLAP\n\t});\n\n\tfor (const { name, content } of memoryFiles) {\n\t\tconst document = getDocument(memoryDb, name);\n\n\t\tif (document && overwrite) {\n\t\t\tp.log.info(\n\t\t\t\t`Removing existing embeddings for DOC: ${color.cyan(name)}`\n\t\t\t);\n\t\t\tawait deleteDocumentFromDB({\n\t\t\t\tdb: memoryDb,\n\t\t\t\tdocName: name\n\t\t\t});\n\t\t}\n\n\t\tif (document && !overwrite) {\n\t\t\tp.log.info(`[SKIPPED] DOC: ${color.cyan(name)} already exists.`);\n\t\t\tskippedDocs++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tp.log.info(`Embedding document: ${name}`);\n\n\t\ttry {\n\t\t\taddDocument({ db: memoryDb, docName: name });\n\n\t\t\tlet chunks;\n\t\t\ttry {\n\t\t\t\tchunks = await splitter.createChunks(content);\n\t\t\t} catch (error) {\n\t\t\t\tp.log.error(\n\t\t\t\t\t`Failed to split document \"${name}\" into chunks. Skipping.`\n\t\t\t\t);\n\t\t\t\tfailedDocs++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet embeddings;\n\t\t\ttry {\n\t\t\t\t// Load the useLocalEmbedding config from the config file.\n\t\t\t\tconst config = await loadConfig();\n\t\t\t\tconst localEmbeddingsConfig =\n\t\t\t\t\tconfig.memory?.useLocalEmbeddings || false;\n\n\t\t\t\t// Read the prop. If prop is present, use it, else use the config.\n\t\t\t\tconst localEmbeddingsEnabled =\n\t\t\t\t\tuseLocalEmbeddings ?? localEmbeddingsConfig;\n\n\t\t\t\tif (localEmbeddingsEnabled) {\n\t\t\t\t\t// Use local embeddings\n\t\t\t\t\tdlog('Generating local embeddings');\n\t\t\t\t\tembeddings = await generateLocalEmbeddings(chunks);\n\t\t\t\t} else {\n\t\t\t\t\t// Use OpenAI embeddings\n\t\t\t\t\tdlog('Generating OpenAI embeddings');\n\t\t\t\t\tembeddings = await getOpenAIEmbeddings(chunks);\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tp.cancel(error.message);\n\t\t\t\tp.log.error(\n\t\t\t\t\t`Failed to generate embeddings for document \"${name}\". Skipping.`\n\t\t\t\t);\n\t\t\t\tfailedDocs++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst chunksWithEmbeddings = chunks.map((chunk, index) => ({\n\t\t\t\ttext: chunk,\n\t\t\t\tembedding: embeddings[index].embedding\n\t\t\t}));\n\n\t\t\ttry {\n\t\t\t\tawait addChunksBulk({\n\t\t\t\t\tdb: memoryDb,\n\t\t\t\t\tdocName: name,\n\t\t\t\t\tchunks: chunksWithEmbeddings\n\t\t\t\t});\n\t\t\t\ttotalEmbeddings += chunksWithEmbeddings.length;\n\t\t\t\tsuccessfulDocs++;\n\t\t\t\tp.log.success(`Successfully embedded document: ${name}`);\n\t\t\t} catch (error) {\n\t\t\t\tp.log.error(\n\t\t\t\t\t`Failed to add chunks for document \"${name}\" to the database. Skipping.`\n\t\t\t\t);\n\t\t\t\tfailedDocs++;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tp.log.error(\n\t\t\t\t`An unexpected error occurred while processing document \"${name}\". Skipping.`\n\t\t\t);\n\t\t\tfailedDocs++;\n\t\t}\n\t}\n\n\tgenerateEmbeddingSummary({\n\t\ttotalDocs,\n\t\tsuccessfulDocs,\n\t\tskippedDocs,\n\t\ttotalEmbeddings\n\t});\n\n\tif (successfulDocs === 0 && skippedDocs === 0) {\n\t\tp.cancel(\n\t\t\t'No documents were successfully embedded or skipped. Process failed.'\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\tif (successfulDocs === 0 && skippedDocs === totalDocs) {\n\t\treturn `All documents were skipped. No new embeddings were generated. \\n${color.dim(\n\t\t\t`${figures.arrowRight} Use --overwrite, -o flag to replace existing embeddings.`\n\t\t)}`;\n\t}\n\n\treturn `All done!`;\n}\n\nfunction generateEmbeddingSummary({\n\ttotalDocs,\n\tsuccessfulDocs,\n\tskippedDocs,\n\ttotalEmbeddings\n}: {\n\ttotalDocs: number;\n\tsuccessfulDocs: number;\n\tskippedDocs: number;\n\ttotalEmbeddings: number;\n}): void {\n\tconst failedDocs = totalDocs - successfulDocs - skippedDocs;\n\tconst maxLabelLength = 'Total embeddings generated:'.length;\n\n\tconst formatLine = (\n\t\tlabel: string,\n\t\tvalue: string,\n\t\ticon: string,\n\t\tvalueColor: (s: string) => string\n\t) => {\n\t\tconst paddedLabel = label.padEnd(maxLabelLength);\n\t\treturn `${icon} ${paddedLabel} ${valueColor(value)}`;\n\t};\n\n\tconst summary = [\n\t\tcolor.bold(color.cyan('Embedding Generation Summary:')),\n\t\t'',\n\t\tformatLine(\n\t\t\t'Total documents:',\n\t\t\t`${totalDocs}`,\n\t\t\tfigures.info,\n\t\t\tcolor.blue\n\t\t),\n\t\t...(skippedDocs > 0\n\t\t\t? [\n\t\t\t\t\tformatLine(\n\t\t\t\t\t\t'Skipped:',\n\t\t\t\t\t\t`${skippedDocs}/${totalDocs} docs`,\n\t\t\t\t\t\tfigures.warning,\n\t\t\t\t\t\tcolor.yellow\n\t\t\t\t\t)\n\t\t\t\t]\n\t\t\t: []),\n\t\tformatLine(\n\t\t\t'Successfully embedded:',\n\t\t\t`${successfulDocs}/${totalDocs} docs`,\n\t\t\tfigures.tick,\n\t\t\tcolor.green\n\t\t),\n\t\t...(failedDocs > 0\n\t\t\t? [\n\t\t\t\t\tformatLine(\n\t\t\t\t\t\t'Failed:',\n\t\t\t\t\t\t`${failedDocs}/${totalDocs} docs`,\n\t\t\t\t\t\tfigures.cross,\n\t\t\t\t\t\tcolor.red\n\t\t\t\t\t)\n\t\t\t\t]\n\t\t\t: []),\n\t\tformatLine(\n\t\t\t'Total embeddings generated:',\n\t\t\t`${totalEmbeddings}`,\n\t\t\tfigures.pointer,\n\t\t\tcolor.magenta\n\t\t),\n\t\t''\n\t].join('\\n');\n\n\tp.log.info(summary);\n}\n\nexport async function listLocalEmbeddedMemoryDocuments({\n\tmemoryName\n}: {\n\tmemoryName: string;\n}) {\n\tconst memoryDb = await loadDb(memoryName);\n\tconst documents = Object.keys(memoryDb.data.documents);\n\treturn documents;\n}\n","export interface ChunkingConfig {\n\tchunkMaxLength: number;\n\tchunkOverlap: number;\n}\n\nclass TextSplitter {\n\tprotected chunkSize: number;\n\tprotected chunkOverlap: number;\n\tprotected keepSeparator: boolean;\n\tprotected lengthFunction: (text: string) => number;\n\n\tconstructor(config: ChunkingConfig) {\n\t\tthis.chunkSize = config.chunkMaxLength;\n\t\tthis.chunkOverlap = config.chunkOverlap;\n\t\tthis.keepSeparator = true;\n\t\tthis.lengthFunction = (text: string) => text.length;\n\n\t\tif (this.chunkOverlap >= this.chunkSize) {\n\t\t\tthrow new Error('Cannot have chunkOverlap >= chunkSize');\n\t\t}\n\t}\n\n\tprotected async splitText(text: string): Promise<string[]> {\n\t\tthrow new Error('splitText method must be implemented in subclass');\n\t}\n\n\tprotected async mergeSplits(\n\t\tsplits: string[],\n\t\tseparator: string\n\t): Promise<string[]> {\n\t\tconst docs: string[] = [];\n\t\tconst currentDoc: string[] = [];\n\t\tlet total = 0;\n\t\tfor (const d of splits) {\n\t\t\tconst _len = await this.lengthFunction(d);\n\t\t\tif (\n\t\t\t\ttotal + _len + (currentDoc.length > 0 ? separator.length : 0) >\n\t\t\t\tthis.chunkSize\n\t\t\t) {\n\t\t\t\tif (total > this.chunkSize) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`Created a chunk of size ${total}, which is longer than the specified ${this.chunkSize}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (currentDoc.length > 0) {\n\t\t\t\t\tconst doc = this.joinDocs(currentDoc, separator);\n\t\t\t\t\tif (doc !== null) {\n\t\t\t\t\t\tdocs.push(doc);\n\t\t\t\t\t}\n\t\t\t\t\twhile (\n\t\t\t\t\t\ttotal > this.chunkOverlap ||\n\t\t\t\t\t\t(total + _len > this.chunkSize && total > 0)\n\t\t\t\t\t) {\n\t\t\t\t\t\ttotal -= await this.lengthFunction(currentDoc[0]);\n\t\t\t\t\t\tcurrentDoc.shift();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentDoc.push(d);\n\t\t\ttotal += _len;\n\t\t}\n\t\tconst doc = this.joinDocs(currentDoc, separator);\n\t\tif (doc !== null) {\n\t\t\tdocs.push(doc);\n\t\t}\n\t\treturn docs;\n\t}\n\n\tprivate joinDocs(docs: string[], separator: string): string | null {\n\t\tconst text = docs.join(separator).trim();\n\t\treturn text === '' ? null : text;\n\t}\n\n\tasync createChunks(content: string): Promise<string[]> {\n\t\tconst chunks = await this.splitText(content);\n\t\treturn chunks.map(chunk => chunk.replace(/\\0/g, ''));\n\t}\n}\n\nexport class RecursiveCharacterTextSplitter extends TextSplitter {\n\tprivate separators: string[] = ['\\n\\n', '\\n', ' ', ''];\n\n\tconstructor(config: ChunkingConfig, separators?: string[]) {\n\t\tsuper(config);\n\t\tif (separators) {\n\t\t\tthis.separators = separators;\n\t\t}\n\t}\n\n\tprotected async splitText(text: string): Promise<string[]> {\n\t\treturn this._splitText(text, this.separators);\n\t}\n\n\tprivate async _splitText(\n\t\ttext: string,\n\t\tseparators: string[]\n\t): Promise<string[]> {\n\t\tconst finalChunks: string[] = [];\n\n\t\tlet separator: string = separators[separators.length - 1];\n\t\tlet newSeparators;\n\t\tfor (let i = 0; i < separators.length; i += 1) {\n\t\t\tconst s = separators[i];\n\t\t\tif (s === '') {\n\t\t\t\tseparator = s;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (text.includes(s)) {\n\t\t\t\tseparator = s;\n\t\t\t\tnewSeparators = separators.slice(i + 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tconst splits = this.splitOnSeparator(text, separator);\n\n\t\tlet goodSplits: string[] = [];\n\t\tconst _separator = this.keepSeparator ? '' : separator;\n\t\tfor (const s of splits) {\n\t\t\tif ((await this.lengthFunction(s)) < this.chunkSize) {\n\t\t\t\tgoodSplits.push(s);\n\t\t\t} else {\n\t\t\t\tif (goodSplits.length) {\n\t\t\t\t\tconst mergedText = await this.mergeSplits(\n\t\t\t\t\t\tgoodSplits,\n\t\t\t\t\t\t_separator\n\t\t\t\t\t);\n\t\t\t\t\tfinalChunks.push(...mergedText);\n\t\t\t\t\tgoodSplits = [];\n\t\t\t\t}\n\t\t\t\tif (!newSeparators) {\n\t\t\t\t\tfinalChunks.push(s);\n\t\t\t\t} else {\n\t\t\t\t\tconst otherInfo = await this._splitText(s, newSeparators);\n\t\t\t\t\tfinalChunks.push(...otherInfo);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (goodSplits.length) {\n\t\t\tconst mergedText = await this.mergeSplits(goodSplits, _separator);\n\t\t\tfinalChunks.push(...mergedText);\n\t\t}\n\t\treturn finalChunks;\n\t}\n\n\tprivate splitOnSeparator(text: string, separator: string): string[] {\n\t\tlet splits;\n\t\tif (separator) {\n\t\t\tif (this.keepSeparator) {\n\t\t\t\tconst regexEscapedSeparator = separator.replace(\n\t\t\t\t\t/[/\\-\\\\^$*+?.()|[\\]{}]/g,\n\t\t\t\t\t'\\\\$&'\n\t\t\t\t);\n\t\t\t\tsplits = text.split(new RegExp(`(?=${regexEscapedSeparator})`));\n\t\t\t} else {\n\t\t\t\tsplits = text.split(separator);\n\t\t\t}\n\t\t} else {\n\t\t\tsplits = text.split('');\n\t\t}\n\t\treturn splits.filter(s => s !== '');\n\t}\n\n\tstatic fromLanguage(\n\t\tlanguage: string,\n\t\tconfig: ChunkingConfig\n\t): RecursiveCharacterTextSplitter {\n\t\tconst separators =\n\t\t\tRecursiveCharacterTextSplitter.getSeparatorsForLanguage(language);\n\t\treturn new RecursiveCharacterTextSplitter(config, separators);\n\t}\n\n\tprivate static getSeparatorsForLanguage(language: string): string[] {\n\t\t// Not needed for now.\n\t\tthrow new Error('getSeparatorsForLanguage method not implemented');\n\t}\n}\n","import fs from 'fs/promises';\nimport * as p from '@clack/prompts';\nimport path from 'path';\n\nexport async function saveEmbeddedCommitHashInMemoryConfig({\n\tmemoryName,\n\tembeddedCommitHash\n}: {\n\tmemoryName: string;\n\tembeddedCommitHash: string;\n}): Promise<void> {\n\ttry {\n\t\tconst memoryDir = path.join(\n\t\t\tprocess.cwd(),\n\t\t\t'baseai',\n\t\t\t'memory',\n\t\t\tmemoryName\n\t\t);\n\t\tconst indexFilePath = path.join(memoryDir, 'index.ts');\n\t\tlet fileContents = await fs.readFile(indexFilePath, 'utf-8');\n\n\t\t// Check if the git block exists\n\t\tif (fileContents.includes('git:')) {\n\t\t\t// Find the git block including its indentation\n\t\t\tconst gitBlockMatch = fileContents.match(/(\\t*)git:\\s*{[^}]*?}/);\n\t\t\tif (gitBlockMatch) {\n\t\t\t\tconst [fullMatch, outerIndent] = gitBlockMatch;\n\t\t\t\tconst innerIndent = outerIndent + '\\t';\n\n\t\t\t\t// Parse existing content\n\t\t\t\tconst contentMatch = fullMatch.match(\n\t\t\t\t\t/{\\s*\\n?\\s*(.*?)\\s*\\n?\\s*}/s\n\t\t\t\t);\n\t\t\t\tlet existingContent = contentMatch ? contentMatch[1] : '';\n\n\t\t\t\tlet contentLines = existingContent\n\t\t\t\t\t.split('\\n')\n\t\t\t\t\t.map(line => line.trim().replace(/,\\s*$/, '')) // Remove trailing commas\n\t\t\t\t\t.filter(Boolean);\n\n\t\t\t\tlet newGitContent: string;\n\n\t\t\t\t// If embeddedAt exists, update it while preserving formatting\n\t\t\t\tif (existingContent.includes('embeddedAt:')) {\n\t\t\t\t\tcontentLines = contentLines.map(line => {\n\t\t\t\t\t\tif (line.includes('embeddedAt:')) {\n\t\t\t\t\t\t\treturn `embeddedAt: '${embeddedCommitHash}'`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn line;\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Add embeddedAt to existing content\n\t\t\t\t\tcontentLines.push(`embeddedAt: '${embeddedCommitHash}'`);\n\t\t\t\t}\n\n\t\t\t\t// Add commas between lines but not after the last line\n\t\t\t\tnewGitContent = contentLines\n\t\t\t\t\t.map((line, index) => {\n\t\t\t\t\t\tconst isLast = index === contentLines.length - 1;\n\t\t\t\t\t\treturn `${innerIndent}${line}${isLast ? '' : ','}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join('\\n');\n\n\t\t\t\t// Replace the old git block with the new one\n\t\t\t\tfileContents = fileContents.replace(\n\t\t\t\t\t/(\\t*)git:\\s*{[^}]*?}/,\n\t\t\t\t\t`${outerIndent}git: {\\n${newGitContent}\\n${outerIndent}}`\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\t// Add new git config block\n\t\t\tconst match = fileContents.match(\n\t\t\t\t/(?:const\\s+\\w+\\s*=\\s*\\(\\s*\\)\\s*(?::\\s*\\w+)?\\s*=>\\s*\\({[\\s\\S]*?)(}\\))/\n\t\t\t);\n\n\t\t\tif (match) {\n\t\t\t\t// Insert before the closing parenthesis\n\t\t\t\tconst insertPosition =\n\t\t\t\t\tmatch.index! + match[0].length - match[1].length;\n\t\t\t\tconst prefix = fileContents.slice(0, insertPosition);\n\t\t\t\tconst suffix = fileContents.slice(insertPosition);\n\n\t\t\t\t// Match the indentation of nearby properties\n\t\t\t\tconst indentMatch = prefix.match(/\\n(\\t+)[^\\n]+\\n\\s*$/);\n\t\t\t\tconst baseIndent = indentMatch ? indentMatch[1] : '\\t';\n\t\t\t\tconst innerIndent = baseIndent + '\\t';\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t'enabled: false',\n\t\t\t\t\t\"include: ['**/*']\",\n\t\t\t\t\t'gitignore: false',\n\t\t\t\t\t`embeddedAt: '${embeddedCommitHash}'`\n\t\t\t\t];\n\n\t\t\t\tconst gitConfig = lines\n\t\t\t\t\t.map((line, index) => {\n\t\t\t\t\t\tconst isLast = index === lines.length - 1;\n\t\t\t\t\t\treturn `${innerIndent}${line}${isLast ? '' : ','}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join('\\n');\n\n\t\t\t\tfileContents = `${prefix},\\n${baseIndent}git: {\\n${gitConfig}\\n${baseIndent}}${suffix}`;\n\t\t\t} else {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Could not find appropriate location to insert git config'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Write the updated contents back to the file\n\t\tawait fs.writeFile(indexFilePath, fileContents, 'utf-8');\n\n\t\tp.log.success(`Updated embeddedAt hash for memory '${memoryName}'.`);\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tp.cancel(\n\t\t\t\t`Failed to save embeddedAt hash for memory '${memoryName}': ${error.message}`\n\t\t\t);\n\t\t} else {\n\t\t\tp.cancel(\n\t\t\t\t`Failed to save embeddedAt hash for memory '${memoryName}': Unknown error`\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n","import * as p from '@clack/prompts';\nimport { checkMemoryExists } from './check-memory-exist';\nimport { loadMemoryFiles } from './load-memory-files';\nimport color from 'picocolors';\nimport { validateMemoryDocNames } from './lib';\n\ntype Spinner = ReturnType<typeof p.spinner>;\n\nexport const isMemoryDocExist = async ({\n\tmemoryName,\n\tdocumentName,\n\tspinner\n}: {\n\tmemoryName: string;\n\tdocumentName: string;\n\tspinner: Spinner;\n}) => {\n\tif (!memoryName) {\n\t\tp.cancel(\n\t\t\t'Memory name is required. Use --memory or -m flag to specify.'\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\tif (!documentName) {\n\t\tp.cancel(\n\t\t\t'Document name is required. Use --document or -d flag to specify.'\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\t// 1- Check memory exists.\n\tconst { memoryName: validMemoryName, documentName: validDocumentName } =\n\t\tvalidateMemoryDocNames({\n\t\t\tmemoryName,\n\t\t\tdocumentName\n\t\t});\n\n\t// 2- Check if memory exists.\n\tawait checkMemoryExists(validMemoryName);\n\n\t// 3- Load memory data.\n\tspinner.start('Loading docs...');\n\tconst memoryFiles = await loadMemoryFiles(validMemoryName);\n\n\tif (memoryFiles.length === 0) {\n\t\tp.cancel(`No valid documents found in memory '${memoryName}'.`);\n\t\tprocess.exit(1);\n\t}\n\n\t// Find the document file.\n\tconst memoryFile = memoryFiles.find(\n\t\tfile => file.name === validDocumentName\n\t);\n\n\tif (!memoryFile) {\n\t\tspinner.stop(`Stopped!`);\n\t\tp.cancel(\n\t\t\t`Doc: ${color.cyan(validDocumentName)} not found in memory ${validMemoryName}`\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\treturn {\n\t\tmemoryFile,\n\t\tvalidMemoryName,\n\t\tvalidDocumentName\n\t};\n};\n","import * as p from '@clack/prompts';\nimport fs from 'fs/promises';\nimport path from 'path';\n\nexport const checkMemoryExists = async (memoryName: string) => {\n\tconst memoryDir = path.join(process.cwd(), 'baseai', 'memory', memoryName);\n\tconst indexFilePath = path.join(memoryDir, 'index.ts');\n\n\ttry {\n\t\tawait fs.access(memoryDir);\n\t} catch (error) {\n\t\tp.cancel(`Memory '${memoryName}' does not exist.`);\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tawait fs.access(indexFilePath);\n\t} catch (error) {\n\t\tp.cancel(\n\t\t\t`Index file for memory '${memoryName}/index.ts' does not exist.`\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\treturn true;\n};\n","import { buildMemory } from '@/build';\nimport { heading } from '@/utils/heading';\nimport { isMemoryDocExist } from '@/utils/memory/check-memory-doc-exists';\nimport * as p from '@clack/prompts';\nimport {\n\thandleDeploymentError,\n\thandleError,\n\thandleInvalidConfig,\n\tlistMemoryDocuments,\n\tuploadDocumentsToMemory,\n} from '.';\nimport path from 'path';\nimport fs from 'fs/promises';\nimport { cyan } from '@/utils/formatting';\nimport {\n\tgetMemoryFileNames,\n\tloadMemoryFiles,\n\ttype MemoryDocumentI\n} from '@/utils/memory/load-memory-files';\nimport type { MemoryI } from 'types/memory';\nimport { compareDocumentLists } from '@/utils/memory/compare-docs-list';\nimport { retrieveAuthentication, type Account } from '@/utils/retrieve-credentials';\n\ntype Spinner = ReturnType<typeof p.spinner>;\n\nexport async function deploySingleDocument({\n\tmemoryName,\n\tdocumentName,\n\toverwrite\n}: {\n\tmemoryName: string;\n\tdocumentName: string;\n\toverwrite: boolean;\n}) {\n\tp.intro(heading({ text: 'DEPLOY', sub: 'Deploy a document' }));\n\n\tconst spinner = p.spinner();\n\ttry {\n\t\tconst { validDocumentName, validMemoryName } = await isMemoryDocExist({\n\t\t\tspinner,\n\t\t\tmemoryName,\n\t\t\tdocumentName\n\t\t});\n\n\t\tspinner.stop('Loaded docs');\n\n\t\tawait buildMemory({ memoryName: validMemoryName });\n\t\tconst buildDir = path.join(process.cwd(), '.baseai');\n\t\tconst memoryDir = path.join(buildDir, 'memory');\n\n\t\tconst account = await retrieveAuthentication({ spinner });\n\t\tif (!account) {\n\t\t\tp.outro(\n\t\t\t\t`No account found. Skipping deployment. \\n Run: ${cyan('npx baseai@latest auth')}`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tawait deployDocument({\n\t\t\taccount,\n\t\t\tspinner,\n\t\t\tmemoryDir,\n\t\t\toverwrite,\n\t\t\tmemoryName: validMemoryName,\n\t\t\tdocumentName: validDocumentName\n\t\t});\n\n\t\tp.outro(\n\t\t\theading({ text: 'DEPLOYED', sub: 'successfully', green: true })\n\t\t);\n\t} catch (error) {\n\t\thandleError({\n\t\t\tspinner,\n\t\t\tmessage: 'An unexpected error occurred',\n\t\t\terror\n\t\t});\n\t}\n}\n\nasync function deployDocument({\n\taccount,\n\tspinner,\n\toverwrite,\n\tmemoryDir,\n\tmemoryName,\n\tdocumentName\n}: {\n\taccount: Account;\n\tspinner: Spinner;\n\tmemoryDir: string;\n\toverwrite: boolean;\n\tmemoryName: string;\n\tdocumentName: string;\n}) {\n\tconst memoryPath = path.join(memoryDir, `${memoryName}.json`);\n\ttry {\n\t\tconst memoryContent = await fs.readFile(memoryPath, 'utf-8');\n\t\tconst memoryObject = JSON.parse(memoryContent);\n\n\t\tif (!memoryObject) {\n\t\t\thandleInvalidConfig({ spinner, name: memoryName, type: 'memory' });\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tp.log.step(`Processing ${documentName} of memory: ${memoryName}`);\n\t\tconst memoryDocs = await loadMemoryFiles(memoryName);\n\n\t\tconst document = memoryDocs.find(doc => doc.name === documentName);\n\n\t\tif (!document) {\n\t\t\tspinner.stop(\n\t\t\t\t`Document ${documentName} not found in memory ${memoryName}`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tawait handleSingleDocDeploy({\n\t\t\tmemory: memoryObject,\n\t\t\taccount,\n\t\t\tdocument,\n\t\t\toverwrite\n\t\t});\n\n\t\tspinner.stop(\n\t\t\t`Finished processing document ${documentName} of memory ${memoryName}`\n\t\t);\n\t} catch (error) {\n\t\thandleDeploymentError({\n\t\t\tspinner,\n\t\t\tname: memoryName,\n\t\t\terror,\n\t\t\ttype: 'memory'\n\t\t});\n\t\tprocess.exit(1);\n\t}\n}\n\nexport async function handleSingleDocDeploy({\n\tmemory,\n\taccount,\n\tdocument,\n\toverwrite\n}: {\n\tmemory: MemoryI;\n\taccount: Account;\n\tdocument: MemoryDocumentI;\n\toverwrite: boolean;\n}) {\n\tp.log.info(\n\t\t`Checking \"${memory.name}\" memory for document \"${document.name}\".`\n\t);\n\n\t// Fetch the existing documents\n\tconst prodDocs = await listMemoryDocuments({\n\t\taccount,\n\t\tmemoryName: memory.name\n\t});\n\n\t// If overwrite is present, deploy.\n\tif (overwrite) {\n\t\tawait uploadDocumentsToMemory({\n\t\t\taccount,\n\t\t\tdocuments: [document],\n\t\t\tname: memory.name\n\t\t});\n\t\tp.log.success(\n\t\t\t`Document \"${document.name}\" uploaded to memory \"${memory.name}\".`\n\t\t);\n\t\treturn;\n\t}\n\n\t// Get the list of local document names\n\tconst localDocs = await getMemoryFileNames(memory.name);\n\n\t// If it is the only that does not exist in prod, deploy.\n\tconst onlyDeployDocMissing = checkOnlyDeployDocumentMissing({\n\t\tlocalDocs,\n\t\tprodDocs,\n\t\tdeployDoc: document.name\n\t});\n\n\tif (onlyDeployDocMissing) {\n\t\tawait uploadDocumentsToMemory({\n\t\t\taccount,\n\t\t\tdocuments: [document],\n\t\t\tname: memory.name\n\t\t});\n\t\tp.log.success(\n\t\t\t`Document \"${document.name}\" uploaded to memory \"${memory.name}\".`\n\t\t);\n\t\treturn;\n\t}\n\n\tconst existInProd = prodDocs.includes(document.name);\n\n\tif (existInProd) {\n\t\tp.log.info(\n\t\t\t`Document \"${document.name}\" already exists in memory \"${memory.name}\".`\n\t\t);\n\n\t\tp.log.info(\n\t\t\t`Use the --overwrite flag to overwrite the existing document in memory.\\n`\n\t\t);\n\t\treturn;\n\t}\n\n\t// Compare the documents\n\tconst { isProdSupersetOfLocal, areMutuallyExclusive, areOverlapping } =\n\t\tcompareDocumentLists({\n\t\t\tlocalDocs,\n\t\t\tprodDocs\n\t\t});\n\n\tif (isProdSupersetOfLocal || areMutuallyExclusive || areOverlapping) {\n\t\tp.log.warning(\n\t\t\t`The documents in memory \"${memory.name}\" are not in sync with the production memory.`\n\t\t);\n\n\t\tp.log.warning(\n\t\t\t`Memory deploy is currently in beta. We only support overwriting the prod memory on Langbase.com.`\n\t\t);\n\n\t\tp.log.info(\n\t\t\t`Use the --overwrite flag to overwrite the existing document in memory.\\n`\n\t\t);\n\t\treturn;\n\t}\n}\n\nexport function checkOnlyDeployDocumentMissing({\n\tlocalDocs,\n\tprodDocs,\n\tdeployDoc\n}: {\n\tlocalDocs: string[];\n\tprodDocs: string[];\n\tdeployDoc: string;\n}): boolean {\n\t// Convert arrays to Sets for efficient lookup\n\tconst localDocSet = new Set(localDocs);\n\tconst prodDocSet = new Set(prodDocs);\n\n\t// Check if the deployed document is in local but not in prod\n\tconst deployDocMissing =\n\t\tlocalDocSet.has(deployDoc) && !prodDocSet.has(deployDoc);\n\n\t// If sizes don't match (excluding deployDoc), sets can't be equal\n\tif (localDocSet.size !== prodDocSet.size + 1) {\n\t\treturn false;\n\t}\n\n\t// Check if all docs in prod are in local (excluding deployDoc)\n\tfor (const doc of prodDocSet) {\n\t\tif (!localDocSet.has(doc)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// At this point, we know:\n\t// 1. Local has exactly one more doc than prod (deployDoc)\n\t// 2. All docs in prod are in local\n\t// Therefore, local and prod are the same except for deployDoc\n\n\treturn deployDocMissing;\n}\n","import { heading } from '@/utils/heading';\nimport * as p from '@clack/prompts';\nimport { outro } from '@clack/prompts';\nimport { serve } from '@hono/node-server';\nimport figures from 'figures';\nimport { Hono, type Context } from 'hono';\nimport { prettyJSON } from 'hono/pretty-json';\nimport { trimTrailingSlash } from 'hono/trailing-slash';\nimport color from 'picocolors';\nimport type { HonoEnv } from './hono/env';\nimport { handleError } from './hono/errors';\nimport { customCors } from './middleware/custom-cors';\nimport { poweredBy } from './middleware/powered-by';\nimport { preFlight } from './middleware/pre-flight';\nimport { registerRoot } from './routes/base';\nimport { registerV1PipesRun } from './routes/v1/pipes/run';\n\nexport async function runBaseServer() {\n\tconst app = new Hono();\n\n\tapp.use(trimTrailingSlash());\n\tapp.use('*', customCors);\n\tapp.use(prettyJSON());\n\tapp.use(poweredBy());\n\tapp.use(preFlight());\n\tapp.onError((err, c) => {\n\t\treturn handleError(err, c as unknown as Context<HonoEnv, any, {}>);\n\t});\n\n\t// Routes.\n\tregisterRoot(app);\n\tregisterV1PipesRun(app);\n\n\tconst port = 9000;\n\n\ttry {\n\t\tp.intro(heading({ text: 'DEV', sub: 'BaseAI dev server' }));\n\n\t\tconst server = serve({\n\t\t\tfetch: app.fetch,\n\t\t\tport\n\t\t});\n\n\t\tserver.on('error', (e: NodeJS.ErrnoException) => {\n\t\t\tif (e.code === 'EADDRINUSE') {\n\t\t\t\tp.log.error(\n\t\t\t\t\tcolor.red(`Error: Port ${port} is already in use.`)\n\t\t\t\t);\n\t\t\t\tp.log.info(\n\t\t\t\t\t`Please close the other application using 9000 port. And try again.`\n\t\t\t\t);\n\n\t\t\t\tprocess.exit(1);\n\t\t\t} else {\n\t\t\t\tconsole.error('Unexpected server error:', e);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t});\n\n\t\tserver.on('listening', () => {\n\t\t\toutro(\n\t\t\t\t`BaseAI server running on: ${color.green(`http://localhost:${port}`)}`\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\t`When needed you can press ${color.cyan('Ctrl + C')} to shut down.`\n\t\t\t);\n\t\t});\n\n\t\t// Add immediate shutdown handler using Clack\n\t\tprocess.on('SIGINT', () => {\n\t\t\tconst spinner = p.spinner();\n\t\t\tspinner.start('Shutting down server');\n\n\t\t\tserver.close(() => {\n\t\t\t\tspinner.stop('Shutting down the server …');\n\t\t\t\tp.outro(\n\t\t\t\t\t`${color.green(figures.tick)} BaseAI server has been gracefully shut down.`\n\t\t\t\t);\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t});\n\t} catch (error: any) {\n\t\tp.outro(`Error: Unable to start server. ${error.message}`);\n\t\tprocess.exit(1);\n\t}\n}\n","import { z } from '@hono/zod-openapi';\nimport type { Context } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport type { StatusCode } from 'hono/utils/http-status';\nimport type { RateLimitErrorResponse } from 'types/api';\nimport { type AnyZodObject, ZodError } from 'zod';\nimport { generateErrorMessage } from 'zod-error';\nimport { fromZodError } from 'zod-validation-error';\nimport type { HonoEnv } from '../hono/env';\n\nconst ErrorCode = z.enum([\n\t'BAD_REQUEST',\n\t'FORBIDDEN',\n\t'INTERNAL_SERVER_ERROR',\n\t'USAGE_EXCEEDED',\n\t'DISABLED',\n\t'NOT_FOUND',\n\t'CONFLICT',\n\t'RATE_LIMITED',\n\t'UNAUTHORIZED',\n\t'PRECONDITION_FAILED',\n\t'INSUFFICIENT_PERMISSIONS'\n]);\n\nexport function errorSchemaFactory(code: z.ZodEnum<any>) {\n\treturn z.object({\n\t\terror: z.object({\n\t\t\tcode: code.openapi({\n\t\t\t\tdescription: 'A machine readable error code.',\n\t\t\t\texample: code._def.values.at(0)\n\t\t\t}),\n\t\t\tdocs: z.string().openapi({\n\t\t\t\tdescription:\n\t\t\t\t\t'A link to our documentation with more details about this error code',\n\t\t\t\texample: `https://langbase.com/docs/api-reference/errors/${code._def.values\n\t\t\t\t\t.at(0)\n\t\t\t\t\t.toLowerCase()}`\n\t\t\t}),\n\t\t\tmessage: z.string().openapi({\n\t\t\t\tdescription: 'A human readable explanation of what went wrong'\n\t\t\t})\n\t\t})\n\t});\n}\n\nexport const ErrorSchema = z.object({\n\tsuccess: z.literal(false).openapi({\n\t\tdescription: 'Indicates that the request was not successful'\n\t}),\n\terror: z.object({\n\t\tcode: ErrorCode.openapi({\n\t\t\tdescription: 'A machine readable error code.',\n\t\t\texample: 'INTERNAL_SERVER_ERROR'\n\t\t}),\n\t\tstatus: z.number().openapi({ description: 'The HTTP status code' }),\n\t\tmessage: z.string().openapi({\n\t\t\tdescription: 'A human readable explanation of what went wrong'\n\t\t}),\n\t\tdocs: z.string().openapi({\n\t\t\tdescription:\n\t\t\t\t'A link to our documentation with more details about this error code',\n\t\t\texample:\n\t\t\t\t'https://langbase.com/docs/api-reference/errors/bad_request'\n\t\t}),\n\t\tcause: z.instanceof(ZodError).optional(),\n\t\trateLimit: z\n\t\t\t.object({\n\t\t\t\tlimit: z.number().openapi({\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t'The maximum number of requests that you can make per hour'\n\t\t\t\t}),\n\t\t\t\tremaining: z.number().openapi({\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t'The number of requests remaining in the current rate limit window'\n\t\t\t\t}),\n\t\t\t\treset: z.number().openapi({\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t'The time at which the current rate limit window resets, in UTC epoch seconds'\n\t\t\t\t})\n\t\t\t})\n\t\t\t.optional()\n\t})\n});\n\nexport type ErrorCodesType = z.infer<typeof ErrorCode>;\nexport type ErrorSchemaType = z.infer<typeof ErrorSchema>;\n\nfunction codeToStatus(code: ErrorCodesType): StatusCode {\n\tswitch (code) {\n\t\tcase 'BAD_REQUEST':\n\t\t\treturn 400;\n\t\tcase 'UNAUTHORIZED':\n\t\t\treturn 401;\n\t\tcase 'FORBIDDEN':\n\t\tcase 'DISABLED':\n\t\tcase 'INSUFFICIENT_PERMISSIONS':\n\t\tcase 'USAGE_EXCEEDED':\n\t\t\treturn 403;\n\t\tcase 'NOT_FOUND':\n\t\t\treturn 404;\n\t\tcase 'CONFLICT':\n\t\t\treturn 409;\n\t\tcase 'PRECONDITION_FAILED':\n\t\t\treturn 412;\n\t\tcase 'RATE_LIMITED':\n\t\t\treturn 429;\n\t\tcase 'INTERNAL_SERVER_ERROR':\n\t\t\treturn 500;\n\t}\n}\n\nexport class ApiError extends HTTPException {\n\tpublic readonly code: ErrorCodesType;\n\tpublic readonly success: boolean;\n\tpublic readonly rateLimit?: RateLimitErrorResponse;\n\tpublic readonly docs?: string;\n\n\tconstructor({\n\t\tstatus,\n\t\tcode,\n\t\tmessage,\n\t\trateLimit,\n\t\tdocs\n\t}: {\n\t\tstatus?: StatusCode;\n\t\tcode: ErrorCodesType;\n\t\tmessage: string;\n\t\trateLimit?: RateLimitErrorResponse;\n\t\tdocs?: string;\n\t}) {\n\t\tsuper(status || codeToStatus(code), { message });\n\t\tthis.code = code;\n\t\tthis.success = false;\n\t\tthis.rateLimit = rateLimit;\n\t\tthis.docs = docs;\n\t}\n}\n\nexport class ApiErrorZod extends HTTPException {\n\tpublic readonly code: ErrorCodesType;\n\n\tconstructor({\n\t\tcode,\n\t\tvalidationResult,\n\t\tcustomMessage\n\t}: {\n\t\tcode: ErrorCodesType;\n\t\tvalidationResult: { success: boolean; error?: ZodError };\n\t\tcustomMessage?: string;\n\t}) {\n\t\tlet message = '';\n\t\tif (validationResult.error) {\n\t\t\tconst _customMessage = customMessage ? customMessage : ``;\n\t\t\tlet _validationMessage = fromZodError(\n\t\t\t\tvalidationResult.error\n\t\t\t).toString();\n\t\t\tmessage = `${_customMessage} HINT: ${_validationMessage}`.trim();\n\t\t}\n\n\t\tsuper(codeToStatus(code), { message });\n\t\tthis.code = code;\n\t\tthis.cause = validationResult.error;\n\t}\n\n\t// Helper static method to simplify throwing errors\n\tstatic handle({\n\t\tcode,\n\t\tresult,\n\t\tmessage\n\t}: {\n\t\tcode: ErrorCodesType;\n\t\tresult: ReturnType<AnyZodObject['safeParse']>;\n\t\tmessage?: string;\n\t}) {\n\t\tif (!result.success) {\n\t\t\tthrow new ApiErrorZod({\n\t\t\t\tcode,\n\t\t\t\tvalidationResult: result,\n\t\t\t\tcustomMessage: message\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * Handles errors and returns a response object.\n *\n * @param err - The error object.\n * @param c - The context object.\n * @returns The response object.\n */\nexport function handleError(err: Error, c: Context<HonoEnv>): Response {\n\tif (err instanceof ApiError) {\n\t\treturn c.json<ErrorSchemaType, StatusCode>(\n\t\t\t{\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: err.code,\n\t\t\t\t\tstatus: err.status,\n\t\t\t\t\tmessage: err.message,\n\t\t\t\t\tdocs:\n\t\t\t\t\t\terr.docs ||\n\t\t\t\t\t\t`https://langbase.com/docs/api-reference/errors/${err.code.toLowerCase()}`,\n\t\t\t\t\trateLimit: err.rateLimit as\n\t\t\t\t\t\t| RateLimitErrorResponse\n\t\t\t\t\t\t| undefined\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ status: err.status }\n\t\t);\n\t}\n\n\tif (err instanceof ApiErrorZod) {\n\t\treturn c.json<ErrorSchemaType, StatusCode>(\n\t\t\t{\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: err.code,\n\t\t\t\t\tstatus: err.status,\n\t\t\t\t\tmessage: err.message,\n\t\t\t\t\tdocs: `https://langbase.com/docs/api-reference/errors/${err.code.toLowerCase()}`,\n\t\t\t\t\tcause: err.cause as ZodError | undefined\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ status: err.status }\n\t\t);\n\t}\n\n\treturn c.json<ErrorSchemaType, StatusCode>(\n\t\t{\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tstatus: 500,\n\t\t\t\tmessage: 'Something unexpected happened.',\n\t\t\t\tdocs: 'https://langbase.com/docs/api-reference/errors/internal_server_error'\n\t\t\t}\n\t\t},\n\t\t{ status: 500 }\n\t);\n}\n\nexport function errorResponse(\n\tc: Context,\n\tcode: ErrorCodesType,\n\tmessage: string\n) {\n\treturn c.json<ErrorSchemaType, StatusCode>(\n\t\t{\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: code,\n\t\t\t\tstatus: codeToStatus(code),\n\t\t\t\tmessage,\n\t\t\t\tdocs: `https://langbase.com/docs/api-reference/errors/${code.toLowerCase()}`\n\t\t\t}\n\t\t},\n\t\t{ status: codeToStatus(code) }\n\t);\n}\n\nexport function handleZodError(\n\tresult:\n\t\t| {\n\t\t\t\tsuccess: true;\n\t\t\t\tdata: any;\n\t\t  }\n\t\t| {\n\t\t\t\tsuccess: false;\n\t\t\t\terror: ZodError;\n\t\t  },\n\tc: Context\n) {\n\tif (!result.success) {\n\t\treturn c.json<ErrorSchemaType, StatusCode>(\n\t\t\t{\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\t\tstatus: 400,\n\t\t\t\t\tdocs: 'https://langbase.com/docs/api-reference/errors/bad_request',\n\t\t\t\t\tmessage: generateErrorMessage(result.error.issues, {\n\t\t\t\t\t\tmaxErrors: 1,\n\t\t\t\t\t\tdelimiter: {\n\t\t\t\t\t\t\tcomponent: ': '\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpath: {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\ttype: 'objectNotation',\n\t\t\t\t\t\t\tlabel: ''\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcode: {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tlabel: ''\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tlabel: ''\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsuffix: ', See \"https://langbase.com/docs/api-reference\" for more details'\n\t\t\t\t\t}),\n\t\t\t\t\tcause: result.error\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ status: 400 }\n\t\t);\n\t}\n}\n","import type { MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\n\n// Custom CORS middleware configuration\nexport const customCors: MiddlewareHandler = cors({\n\torigin: '*', // Equivalent to 'Access-Control-Allow-Origin'\n\tmaxAge: 86400, // Equivalent to 'Access-Control-Max-Age'\n\tallowMethods: ['GET', 'POST', 'OPTIONS'], // Equivalent to 'Access-Control-Allow-Methods'\n\tallowHeaders: ['Content-Type', 'Authorization'] // Equivalent to 'Access-Control-Allow-Headers'\n});\n","import type { MiddlewareHandler } from 'hono';\n\nexport const poweredBy = (): MiddlewareHandler => {\n\treturn async function poweredBy(c, next) {\n\t\tawait next();\n\t\tc.res.headers.set('lb-powered-by', 'Langbase');\n\t\tc.res.headers.set('powered-by', 'BaseAI');\n\t\tc.res.headers.set('env', 'local');\n\t};\n};\n","import {MiddlewareHandler} from 'hono';\n\nexport const preFlight = (): MiddlewareHandler => {\n\treturn async function preFlight(c, next) {\n\t\tif (c.req.method === 'OPTIONS') {\n\t\t\treturn new Response(null);\n\t\t}\n\t\tawait next();\n\t};\n};\n","export const registerRoot = (app: any) =>\n\tapp.get('/', (c: any) => {\n\t\treturn c.json({\n\t\t\tsuccess: true,\n\t\t\tmessage: 'BaseAI Local API',\n\t\t\tlink: 'https://langbase.com/docs'\n\t\t});\n\t});\n","import type { Message, Pipe } from 'types/pipe';\n\nexport function getPipeFewShotsMessages(pipe: Pipe): Message[] {\n\tconst fewShotMessages: Message[] = pipe.messages.filter(\n\t\tm => m.role !== 'system'\n\t);\n\n\tif (fewShotMessages && fewShotMessages.length > 0) {\n\t\treturn fewShotMessages;\n\t}\n\n\treturn [];\n}\n","export type Models =\n\t| 'Audio models'\n\t| 'Embedding models'\n\t| 'Fine-tuning models'\n\t| 'GPT-4'\n\t| 'GPT-4 Turbo'\n\t| 'GPT-3.5 Turbo'\n\t| 'InstructGPT'\n\t| 'Base models'\n\t| 'Image models';\n\nexport type GPT4Model =\n\t| 'gpt-4'\n\t| 'gpt-4-0314'\n\t| 'gpt-4-0613'\n\t| 'gpt-4-32k'\n\t| 'gpt-4-32k-0314'\n\t| 'gpt-4-1106-preview'\n\t| 'gpt-4-1106-vision-preview';\n\nexport type GPT3Model =\n\t| 'gpt-3.5-turbo'\n\t| 'gpt-3.5-turbo-0301'\n\t| 'gpt-3.5-turbo-0613'\n\t| 'gpt-3.5-turbo-16k-0613'\n\t| 'gpt-3.5-turbo-1106';\n\nexport type ChatCompletionModel = GPT3Model | GPT4Model;\n\nexport type CompletionModel =\n\t| 'text-ada-001'\n\t| 'text-babbage-001'\n\t| 'text-curie-001'\n\t| 'text-davinci-002'\n\t| 'text-davinci-003'\n\t| 'text-davinci:003';\n\nexport type EditModel = 'text-davinci-edit-001' | 'code-davinci-edit-001';\n\nexport type FineTunedModel =\n\t| 'text-davinci-003'\n\t| 'text-davinci-002'\n\t| 'text-curie-001'\n\t| 'text-babbage-001'\n\t| 'text-ada-001';\n\nexport type AudioModel = 'whisper-1' | 'whisper-2';\n\nexport type EmbeddingModel =\n\t| 'text-embedding-ada-002'\n\t| 'text-embedding-ada-002-v2'\n\t| 'text-search-ada-doc-001';\n\nexport type ImageResolution = '256x256' | '512x512' | '1024x1024';\n\nexport type Snapshot =\n\t| ChatCompletionModel\n\t| CompletionModel\n\t| EditModel\n\t| FineTunedModel\n\t| AudioModel\n\t| EmbeddingModel\n\t| ImageResolution;\n\nexport type CompletionModelCost = {\n\tprompt: number;\n\tcompletion: number;\n};\n\nexport type CostPerUnit = {\n\t[key in Snapshot | string]?: CompletionModelCost | number;\n};\n\nexport const IMAGE_MODEL_COST = {\n\t'1024x1024': 0.02, // per 1 image\n\t'512x512': 0.018, // per 1 image\n\t'256x256': 0.016 // per 1 image\n};\n\nexport const OPEN_AI: string = 'OpenAI';\nexport const ANTHROPIC: string = 'Anthropic';\nexport const TOGETHER_AI: string = 'Together';\nexport const GOOGLE: string = 'Google';\nexport const GROQ: string = 'Groq';\nexport const COHERE: string = 'Cohere';\nexport const FIREWORKS_AI: string = 'Fireworks AI';\nexport const PERPLEXITY: string = 'Perplexity';\n\n// Not being used yet\nexport const DEEPINFRA: string = 'deepinfra';\nexport const BEDROCK: string = 'bedrock';\nexport const AZURE_OPEN_AI: string = 'azure-openai';\nexport const X_AI: string = 'xAI';\nexport const OLLAMA: string = 'ollama';\n\ninterface Model {\n\tid: string;\n\tprovider: string;\n\tpromptCost: number;\n\tcompletionCost: number;\n\trequestCost?: number;\n\ttoolSupport?: {\n\t\ttoolChoice: boolean;\n\t\tparallelToolCalls: boolean;\n\t};\n}\n\ninterface ModelsByProviderInclCosts {\n\t[provider: string]: Model[];\n}\n\nexport const modelsByProvider: ModelsByProviderInclCosts = {\n\t[OPEN_AI]: [\n\t\t{\n\t\t\tid: 'gpt-4o',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 5.0,\n\t\t\tcompletionCost: 15.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4o-2024-08-06',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 2.5,\n\t\t\tcompletionCost: 10.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4o-mini',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 0.15,\n\t\t\tcompletionCost: 0.6,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-turbo',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-turbo-preview',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-0125-preview',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-1106-preview',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 10.0,\n\t\t\tcompletionCost: 30.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 30.0,\n\t\t\tcompletionCost: 60.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-0613',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 30.0,\n\t\t\tcompletionCost: 60.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-4-32k',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 60.0,\n\t\t\tcompletionCost: 120.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo-0125',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo-1106',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 1.0,\n\t\t\tcompletionCost: 2.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gpt-3.5-turbo-16k',\n\t\t\tprovider: OPEN_AI,\n\t\t\tpromptCost: 3.0,\n\t\t\tcompletionCost: 4.0,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t}\n\t],\n\t[TOGETHER_AI]: [\n\t\t{\n\t\t\tid: 'meta-llama/Llama-3.3-70B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.88,\n\t\t\tcompletionCost: 0.88,\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 5,\n\t\t\tcompletionCost: 5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.88,\n\t\t\tcompletionCost: 0.88,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.18,\n\t\t\tcompletionCost: 0.18,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-3-70b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-3-8b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'togethercomputer/Llama-2-7B-32K-Instruct',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-2-13b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.225,\n\t\t\tcompletionCost: 0.225\n\t\t},\n\t\t{\n\t\t\tid: 'meta-llama/Llama-2-70b-chat-hf',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t},\n\t\t{\n\t\t\tid: 'google/gemma-7b-it',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'google/gemma-2b-it',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.1,\n\t\t\tcompletionCost: 0.1\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mistral-7B-Instruct-v0.1',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mistral-7B-Instruct-v0.2',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mixtral-8x7B-Instruct-v0.1',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 0.6,\n\t\t\tcompletionCost: 0.6,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'mistralai/Mixtral-8x22B-Instruct-v0.1',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 1.2,\n\t\t\tcompletionCost: 1.2\n\t\t},\n\t\t{\n\t\t\tid: 'databricks/dbrx-instruct',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tpromptCost: 1.2,\n\t\t\tcompletionCost: 1.2\n\t\t}\n\t],\n\t[ANTHROPIC]: [\n\t\t{\n\t\t\tid: 'claude-3-5-sonnet-latest',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-5-sonnet-20240620',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-opus-20240229',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 15,\n\t\t\tcompletionCost: 75,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-sonnet-20240229',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-haiku-20240307',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 0.25,\n\t\t\tcompletionCost: 1.25,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'claude-3-5-haiku-20241022',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tpromptCost: 1,\n\t\t\tcompletionCost: 5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t}\n\t],\n\t[GROQ]: [\n\t\t{\n\t\t\tid: 'llama-3.3-70b-versatile',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79,\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-70b-versatile',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-8b-instant',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79\n\t\t},\n\t\t{\n\t\t\tid: 'llama3-70b-8192',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.59,\n\t\t\tcompletionCost: 0.79\n\t\t},\n\t\t{\n\t\t\tid: 'llama3-8b-8192',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.05,\n\t\t\tcompletionCost: 0.1\n\t\t},\n\t\t{\n\t\t\tid: 'mixtral-8x7b-32768',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.27,\n\t\t\tcompletionCost: 0.27\n\t\t},\n\t\t{\n\t\t\tid: 'gemma2-9b-it',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'gemma-7b-it',\n\t\t\tprovider: GROQ,\n\t\t\tpromptCost: 0.07,\n\t\t\tcompletionCost: 0.07\n\t\t}\n\t],\n\t[GOOGLE]: [\n\t\t{\n\t\t\tid: 'gemini-1.5-pro-latest',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 3.5,\n\t\t\tcompletionCost: 10.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gemini-1.5-flash-latest',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 0.075,\n\t\t\tcompletionCost: 0.3,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gemini-1.5-flash-8b-latest',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 0.0375,\n\t\t\tcompletionCost: 0.15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: true\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: 'gemini-pro',\n\t\t\tprovider: GOOGLE,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: false,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t}\n\t],\n\t[COHERE]: [\n\t\t{\n\t\t\tid: 'command-r',\n\t\t\tprovider: COHERE,\n\t\t\tpromptCost: 0.5,\n\t\t\tcompletionCost: 1.5\n\t\t},\n\t\t{\n\t\t\tid: 'command-r-plus',\n\t\t\tprovider: COHERE,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 15\n\t\t}\n\t],\n\t[FIREWORKS_AI]: [\n\t\t{\n\t\t\tid: 'llama-v3p3-70b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.88,\n\t\t\tcompletionCost: 0.88,\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3p1-405b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 3\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3p1-70b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3p1-8b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t},\n\t\t{\n\t\t\tid: 'yi-large',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 3,\n\t\t\tcompletionCost: 3\n\t\t},\n\t\t{\n\t\t\tid: 'llama-v3-70b-instruct',\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tpromptCost: 0.9,\n\t\t\tcompletionCost: 0.9\n\t\t}\n\t],\n\t[PERPLEXITY]: [\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-huge-128k-online',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 5,\n\t\t\tcompletionCost: 5,\n\t\t\trequestCost: 0.005\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-large-128k-online',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 1,\n\t\t\tcompletionCost: 1,\n\t\t\trequestCost: 0.005\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-small-128k-online',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2,\n\t\t\trequestCost: 0.005\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-large-128k-chat',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 1,\n\t\t\tcompletionCost: 1\n\t\t},\n\t\t{\n\t\t\tid: 'llama-3.1-sonar-small-128k-chat',\n\t\t\tprovider: PERPLEXITY,\n\t\t\tpromptCost: 0.2,\n\t\t\tcompletionCost: 0.2\n\t\t}\n\t],\n\t[X_AI]: [\n\t\t{\n\t\t\tid: 'grok-beta',\n\t\t\tprovider: X_AI,\n\t\t\tpromptCost: 5,\n\t\t\tcompletionCost: 15,\n\t\t\ttoolSupport: {\n\t\t\t\ttoolChoice: true,\n\t\t\t\tparallelToolCalls: false\n\t\t\t}\n\t\t}\n\t]\n};\n\n// Keep it synced with API. Add model IDs.\nexport const jsonModeModels = [\n\t'gpt-4o',\n\t'gpt-4o-2024-08-06',\n\t'gpt-4o-mini',\n\t'gpt-4-turbo',\n\t'gpt-4-turbo-preview',\n\t'gpt-4-0125-preview',\n\t'gpt-3.5-turbo',\n\t'gpt-3.5-turbo-0125',\n\t'gpt-3.5-turbo-1106',\n\t'gpt-4-1106-preview',\n\t'mistralai/Mistral-7B-Instruct-v0.1',\n\t'mistralai/Mixtral-8x7B-Instruct-v0.1',\n\t'gemini-1.5-pro-latest',\n\t'gemini-1.5-flash-latest'\n];\n","import {OPEN_AI} from './models';\n\nexport const CONTENT_TYPES = {\n\tAPPLICATION_JSON: 'application/json',\n\tMULTIPART_FORM_DATA: 'multipart/form-data',\n\tEVENT_STREAM: 'text/event-stream',\n\tAUDIO_MPEG: 'audio/mpeg',\n\tAPPLICATION_OCTET_STREAM: 'application/octet-stream',\n\tGENERIC_AUDIO_PATTERN: 'audio',\n\tPLAIN_TEXT: 'text/plain',\n\tHTML: 'text/html',\n\tGENERIC_IMAGE_PATTERN: 'image/',\n};\n\nexport const REQUEST_TIMEOUT_STATUS_CODE = 408;\nexport const defaultJsonPrompt = 'Output should be in JSON format.';\nexport const defaultRagPrompt = `Below is some CONTEXT for you to answer the questions. ONLY answer from the CONTEXT. CONTEXT consists of multiple information chunks. Each chunk has a source mentioned at the end.\\n\\nFor each piece of response you provide, cite the source in brackets like so: [1].\\n\\nAt the end of the answer, always list each source with its corresponding number and provide the document name. like so [1] Filename.doc.\\n\\nIf you don't know the answer, just say that you don't know. Ask for more context and better questions if needed.`;\n\nexport const defaultPipeVersionInsert = {\n\tmeta: {\n\t\tnumber: '1',\n\t\tstream: true,\n\t\tstore: true,\n\t\tdebug: false,\n\t\tjson: false,\n\t},\n\tmodel: {\n\t\tname: 'gpt-4o-mini',\n\t\tprovider: OPEN_AI,\n\t\ttone: 'Custom',\n\t\tparams: {\n\t\t\tmax_tokens: 1000,\n\t\t\ttemperature: 0.7,\n\t\t\ttop_p: 1,\n\t\t\tfrequency_penalty: 0,\n\t\t\tpresence_penalty: 0,\n\t\t\tstop: [],\n\t\t},\n\t\ttool_choice: 'auto',\n\t\tparallel_tool_calls: true,\n\t},\n\tprompt: {\n\t\topening: `Welcome to Langbase. Prompt away!`,\n\t\tsystem: `You're a helpful AI assistant.`,\n\t\tsafety: '',\n\t\tmessages: [],\n\t\tvariables: [],\n\t\tjson: '',\n\t\trag: '',\n\t},\n\tmemorysets: [],\n\tpipe_id: '',\n\tpreview: false,\n\tfunctions: [],\n};\n","/**\n * Adds JSON mode if enabled and supported by the current model\n *\n * @param {string} pipe - The pipe config.\n * @param {string} prompt - The system prompt.\n * @returns {string} The prompt with JSON mode line added.\n */\n\nimport { jsonModeModels } from '@/data/models';\nimport { defaultJsonPrompt } from '@/dev/data/globals';\nimport type { Pipe } from 'types/pipe';\n\nexport function addJsonMode({\n\tpipe,\n\tsystemPrompt\n}: {\n\tpipe: Pipe;\n\tsystemPrompt: string;\n}) {\n\t// Return the system prompt if JSON mode is not enabled\n\tif (!pipe?.json) return systemPrompt;\n\n\tconst modelName = pipe.model.split(':')[1];\n\t// Return the system prompt if JSON mode is not supported by the current model\n\tif (!jsonModeModels.includes(modelName)) return systemPrompt;\n\n\tconst jsonModePrompt = getJsonPrompt(pipe);\n\n\t// Add JSON mode if enabled & supported by model\n\treturn `${systemPrompt}\\n\\n${jsonModePrompt}`;\n}\n\nfunction getJsonPrompt(pipe: Pipe): string {\n\tconst jsonPrompt =\n\t\tpipe.messages.find(m => m.role === 'system' && m.name === 'json')\n\t\t\t?.content || '';\n\n\t// Use default prompt if json prompt is empty or not set\n\tconst useDefaultPrompt = jsonPrompt === '';\n\treturn useDefaultPrompt ? defaultJsonPrompt : jsonPrompt;\n}\n","import { defaultRagPrompt } from '@/utils/memory/constants';\nimport type { SimilarChunk } from '@/utils/memory/db/lib';\nimport type { Message, Pipe } from 'types/pipe';\nimport { addJsonMode } from './add-json-mode';\n\nexport function getSystemPromptMessage({\n\tpipe,\n\tsimilarChunks\n}: {\n\tpipe: Pipe;\n\tsimilarChunks: SimilarChunk[] | undefined;\n}) {\n\tlet systemPrompt = '';\n\n\tsystemPrompt = addSystemPrompt(pipe);\n\tsystemPrompt = addSafetyPrompt({ pipe, systemPrompt });\n\tsystemPrompt = addJsonMode({ pipe, systemPrompt });\n\tsystemPrompt = addRagPromptWithAugmentedContext({\n\t\tpipe,\n\t\tsystemPrompt,\n\t\tsimilarChunks\n\t});\n\n\treturn [{ role: 'system', content: systemPrompt }] as Message[];\n}\n\nfunction addSystemPrompt(pipe: Pipe): string {\n\tconst defualtSystemPrompt = `You are a helpful AI Chat assistant`;\n\tconst systemPrompt =\n\t\tpipe.messages.find(m => m.role === 'system' && !m.name)?.content || '';\n\tconst hasSystemPrompt = systemPrompt !== '';\n\n\tconst systemPromptWithoutSafety = hasSystemPrompt\n\t\t? systemPrompt\n\t\t: defualtSystemPrompt;\n\n\treturn systemPromptWithoutSafety;\n}\n\nfunction getSafetyPrompt(pipe: Pipe): string {\n\treturn (\n\t\tpipe.messages.find(m => m.role === 'system' && m.name === 'safety')\n\t\t\t?.content || ''\n\t);\n}\n\nfunction addSafetyPrompt({\n\tpipe,\n\tsystemPrompt\n}: {\n\tpipe: Pipe;\n\tsystemPrompt: string;\n}): string {\n\tlet safetyPrompt = getSafetyPrompt(pipe);\n\tconst hasSafetyPrompt = safetyPrompt !== '';\n\n\tsafetyPrompt = hasSafetyPrompt\n\t\t? `\"\"\"SAFETY GUIDELINE: ${safetyPrompt}\"\"\"`\n\t\t: ``;\n\n\treturn `${systemPrompt} \\n ${safetyPrompt}`.trim();\n}\n\nfunction addRagPromptWithAugmentedContext({\n\tpipe,\n\tsystemPrompt,\n\tsimilarChunks\n}: {\n\tpipe: Pipe;\n\tsystemPrompt: string;\n\tsimilarChunks: SimilarChunk[] | undefined;\n}): string {\n\t// No RAG: then return the system prompt.\n\tif (!similarChunks || similarChunks.length === 0) return systemPrompt;\n\n\tconst memoryContext = similarChunks\n\t\t.map(chunk => `${chunk.text} \\n\\n Source: ${chunk.attributes.docName}`)\n\t\t.join('\\n\\n');\n\n\t// Extract Rag prompt from the messages.\n\tconst ragMsg =\n\t\tpipe.messages.find(m => m.role === 'system' && m.name === 'rag')\n\t\t\t?.content || '';\n\n\t// If there is no rag prompt, use the default rag prompt.\n\tconst hasRagPrompt = ragMsg !== '';\n\tconst ragPrompt = hasRagPrompt ? ragMsg : defaultRagPrompt;\n\n\tconst contextContent = `\"\"\"CONTEXT:\\n ${memoryContext}\"\"\"`;\n\tconst ragPromptWithAugmentedContext = `\"\"\"${ragPrompt}\"\"\" \\n\\n ${contextContent}`;\n\n\treturn `${systemPrompt} \\n\\n ${ragPromptWithAugmentedContext}`.trim();\n}\n","import type { Message, Pipe, VariableI, VariablesI } from 'types/pipe';\nimport { dlog } from '../dlog';\n\n/**\n * Process the messages to replace variables with their values\n * Replaces variables in messages content with their values\n */\nexport function processMessages({\n\tpipe,\n\tmessages,\n\tvariables\n}: {\n\tpipe: Pipe;\n\tmessages: Message[];\n\tvariables?: VariablesI;\n}) {\n\tconst variablesMap = getVarsMap({ pipe, variables });\n\n\tconst messagesWithVarsValues = replaceVarsInMessagesWithVals({\n\t\tmessages,\n\t\tvariablesMap\n\t});\n\treturn { messages: messagesWithVarsValues, variablesMap };\n}\n\nfunction getVarsMap({\n\tpipe,\n\tvariables\n}: {\n\tpipe: Pipe;\n\tvariables?: VariablesI;\n}) {\n\tconst hasPipeVars = pipe.variables ? pipe.variables.length > 0 : false;\n\tconst hasCurrentPromptVars = variables ? variables.length > 0 : false;\n\n\tconst pipeVars = hasPipeVars ? pipe.variables : [];\n\tconst currentPromptVars = hasCurrentPromptVars ? variables : [];\n\n\tlet finalVariablesMap: Map<string, string> = new Map();\n\n\tif (hasPipeVars) {\n\t\tpipeVars.forEach((v: { name: string; value: string }) =>\n\t\t\tfinalVariablesMap.set(v.name, v.value)\n\t\t);\n\t}\n\n\tif (hasCurrentPromptVars) {\n\t\tcurrentPromptVars?.forEach((v: VariableI) =>\n\t\t\tfinalVariablesMap.set(v.name, v.value)\n\t\t);\n\t}\n\n\t// Convert the map back to an array for debugging\n\tlet finalVariables: VariableI[] = Array.from(\n\t\tfinalVariablesMap,\n\t\t([name, value]) => ({\n\t\t\tname,\n\t\t\tvalue\n\t\t})\n\t);\n\tdlog(`finalVariables`, finalVariables);\n\n\treturn finalVariablesMap;\n}\n\n// Function to replace variables in the messages\nfunction replaceVarsInMessagesWithVals({\n\tmessages,\n\tvariablesMap\n}: {\n\tmessages: Message[];\n\tvariablesMap: Map<string, string>;\n}): Message[] {\n\tconst variableRegex = /{{(.*?)}}/g; // Regex to match double curly braces\n\n\treturn messages.map(message => {\n\t\t// When Assistant requests a tool call,\n\t\t// 1- message.content is empty\n\t\t// 2- message.role is 'assistant'\n\t\t// 3- message.tool_calls is an array of tool calls requested by LLM.\n\t\tconst isAssistantToolCall =\n\t\t\t!message.content &&\n\t\t\tmessage.role === 'assistant' &&\n\t\t\tmessage.tool_calls?.length;\n\n\t\t// Since no content to replace variables in, return the message as is.\n\t\tif (isAssistantToolCall) return message;\n\t\tif (!message.content) return message;\n\n\t\t// Replace variables in the message content\n\t\tconst updatedContent = message.content.replace(\n\t\t\tvariableRegex,\n\t\t\t(match, varName) => {\n\t\t\t\tconst trimmedVarName = varName.trim(); // Trim any extra spaces\n\t\t\t\t// If the variable exists in the map, replace with its value; otherwise, leave the placeholder intact\n\t\t\t\treturn variablesMap.get(trimmedVarName) || match;\n\t\t\t}\n\t\t);\n\t\treturn {\n\t\t\t...message,\n\t\t\tcontent: updatedContent\n\t\t};\n\t});\n}\n","import { ApiError } from '@/dev/hono/errors';\nimport type { SimilarChunk } from '@/utils/memory/db/lib';\nimport type { Message, Pipe, VariablesI } from 'types/pipe';\nimport { dlog } from '../dlog';\nimport { getPipeFewShotsMessages } from './get-few-shot-messages';\nimport { getSystemPromptMessage } from './get-system-prompt';\nimport { processMessages } from './process-messages';\n\nexport function getRunThread({\n\tpipe,\n\tmessages,\n\tsimilarChunks,\n\tvariables\n}: {\n\tpipe: Pipe;\n\tmessages: Message[];\n\tsimilarChunks: SimilarChunk[] | undefined;\n\tvariables?: VariablesI;\n}) {\n\ttry {\n\t\tconst systemPromptMessage = getSystemPromptMessage({\n\t\t\tpipe,\n\t\t\tsimilarChunks\n\t\t});\n\t\tconst pipeFewShotsMessages = getPipeFewShotsMessages(pipe);\n\n\t\tconst messagesThread = [\n\t\t\t// Messages in the pipe\n\t\t\t...systemPromptMessage,\n\t\t\t...pipeFewShotsMessages,\n\t\t\t// Messages sent with the request\n\t\t\t...messages\n\t\t];\n\n\t\tconst { messages: messagesThreadWithVars } = processMessages({\n\t\t\tpipe,\n\t\t\tmessages: messagesThread,\n\t\t\tvariables\n\t\t});\n\n\t\treturn messagesThreadWithVars;\n\t} catch (error: any) {\n\t\tdlog('Error get-run-thread.ts:', error);\n\n\t\tthrow new ApiError({\n\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: `Something unexpected happened. Error generating thread of messages.`\n\t\t});\n\t}\n}\n","import type { ProviderAPIConfig } from 'types/providers';\n\nconst AnthropicAPIConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.anthropic.com/v1',\n\theaders: ({\n\t\tllmApiKey,\n\t\tendpoint\n\t}: {\n\t\tllmApiKey: string;\n\t\tendpoint: string;\n\t}) => {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'X-API-Key': `${llmApiKey}`,\n\t\t\t'anthropic-version': '2023-06-01'\n\t\t};\n\t\tif (endpoint === 'chatComplete') {\n\t\t\theaders['anthropic-beta'] = 'messages-2023-12-15';\n\t\t}\n\t\treturn headers;\n\t},\n\tchatComplete: '/messages'\n};\n\nexport default AnthropicAPIConfig;\n","import type { ErrorResponse } from 'types/providers';\n\nexport const generateInvalidProviderResponseError: (\n\tresponse: Record<string, any>,\n\tprovider: string\n) => ErrorResponse = (response, provider) => {\n\treturn {\n\t\terror: {\n\t\t\tmessage: `Invalid response received from ${provider}: ${JSON.stringify(response)}`,\n\t\t\ttype: null,\n\t\t\tparam: null,\n\t\t\tcode: null\n\t\t},\n\t\tprovider: provider\n\t} as ErrorResponse;\n};\n\nexport const generateErrorResponse: (\n\terrorDetails: {\n\t\tmessage: string;\n\t\ttype: string | null;\n\t\tparam: string | null;\n\t\tcode: string | null;\n\t},\n\tprovider: string\n) => ErrorResponse = ({ message, type, param, code }, provider) => {\n\treturn {\n\t\terror: {\n\t\t\tmessage: `${message}`,\n\t\t\ttype: type ?? null,\n\t\t\tparam: param ?? null,\n\t\t\tcode: code ?? null\n\t\t},\n\t\tprovider: provider\n\t} as ErrorResponse;\n};\n\nconst fileExtensionMimeTypeMap = {\n\tmp4: 'video/mp4',\n\tjpeg: 'image/jpeg',\n\tjpg: 'image/jpeg',\n\tpng: 'image/png',\n\tbmp: 'image/bmp',\n\ttiff: 'image/tiff',\n\twebp: 'image/webp',\n\tpdf: 'application/pdf',\n\tmp3: 'audio/mp3',\n\twav: 'audio/wav',\n\ttxt: 'text/plain',\n\tmov: 'video/mov',\n\tmpeg: 'video/mpeg',\n\tmpg: 'video/mpg',\n\tavi: 'video/avi',\n\twmv: 'video/wmv',\n\tmpegps: 'video/mpegps',\n\tflv: 'video/flv'\n};\n\nexport const getMimeType = (url: string): string | undefined => {\n\tconst urlParts = url.split('.');\n\tconst extension = urlParts[\n\t\turlParts.length - 1\n\t] as keyof typeof fileExtensionMimeTypeMap;\n\tconst mimeType = fileExtensionMimeTypeMap[extension];\n\treturn mimeType;\n};\n","import type {\n\tChatCompletionResponse,\n\tContentType,\n\tErrorResponse,\n\tMessageRole,\n\tModelParams,\n\tProviderConfig,\n\tProviderMessage\n} from 'types/providers';\nimport { ANTHROPIC } from '@/data/models';\nimport { generateInvalidProviderResponseError } from '../utils';\n\ninterface AnthropicTool {\n\tname: string;\n\tdescription: string;\n\tinput_schema: {\n\t\ttype: string;\n\t\tproperties: Record<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\ttype: string;\n\t\t\t\tdescription: string;\n\t\t\t}\n\t\t>;\n\t\trequired: string[];\n\t};\n}\n\ninterface AnthropicToolResultContentItem {\n\ttype: 'tool_result';\n\ttool_use_id: string;\n\tcontent?: string;\n}\n\ntype AnthropicMessageContentItem = AnthropicToolResultContentItem | ContentType;\n\ninterface AnthropicMessage extends ProviderMessage {\n\tcontent?: string | AnthropicMessageContentItem[];\n}\n\ninterface AnthorpicTextContentItem {\n\ttype: 'text';\n\ttext: string;\n}\n\ninterface AnthropicToolContentItem {\n\ttype: 'tool_use';\n\tname: string;\n\tid: string;\n\tinput: Record<string, any>;\n}\n\ntype AnthropicContentItem = AnthorpicTextContentItem | AnthropicToolContentItem;\n\nconst transformAssistantMessage = (msg: ProviderMessage): AnthropicMessage => {\n\tlet content: AnthropicContentItem[] = [];\n\tconst containsToolCalls = msg.tool_calls && msg.tool_calls.length;\n\n\tif (msg.content && typeof msg.content === 'string') {\n\t\tcontent.push({\n\t\t\ttype: 'text',\n\t\t\ttext: msg.content\n\t\t});\n\t} else if (\n\t\tmsg.content &&\n\t\ttypeof msg.content === 'object' &&\n\t\tmsg.content.length\n\t) {\n\t\tif (msg.content[0].text) {\n\t\t\tcontent.push({\n\t\t\t\ttype: 'text',\n\t\t\t\ttext: msg.content[0].text\n\t\t\t});\n\t\t}\n\t}\n\tif (containsToolCalls) {\n\t\tmsg.tool_calls.forEach((toolCall: any) => {\n\t\t\tcontent.push({\n\t\t\t\ttype: 'tool_use',\n\t\t\t\tname: toolCall.function.name,\n\t\t\t\tid: toolCall.id,\n\t\t\t\tinput: JSON.parse(toolCall.function.arguments)\n\t\t\t});\n\t\t});\n\t}\n\treturn {\n\t\trole: msg.role,\n\t\tcontent\n\t};\n};\n\nconst transformToolMessage = (msg: ProviderMessage): AnthropicMessage => {\n\treturn {\n\t\trole: 'user',\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: 'tool_result',\n\t\t\t\ttool_use_id: msg.tool_call_id,\n\t\t\t\tcontent: msg.content as string\n\t\t\t}\n\t\t]\n\t};\n};\n\nexport const AnthropicChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\tdefault: 'claude-3-haiku',\n\t\trequired: true\n\t},\n\tmessages: [\n\t\t{\n\t\t\tparam: 'messages',\n\t\t\trequired: true,\n\t\t\ttransform: (params: ModelParams) => {\n\t\t\t\tlet messages: ProviderMessage[] = [];\n\t\t\t\tlet lastRole: MessageRole | undefined;\n\n\t\t\t\tif (!!params.messages) {\n\t\t\t\t\tparams.messages.forEach((msg: ProviderMessage) => {\n\t\t\t\t\t\tif (msg.role === 'system') return;\n\n\t\t\t\t\t\tif (msg.role === 'assistant') {\n\t\t\t\t\t\t\tmessages.push(transformAssistantMessage(msg));\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\tmsg.content &&\n\t\t\t\t\t\t\ttypeof msg.content === 'object' &&\n\t\t\t\t\t\t\tmsg.content.length\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst transformedMessage: Record<string, any> = {\n\t\t\t\t\t\t\t\trole: msg.role,\n\t\t\t\t\t\t\t\tcontent: []\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tmsg.content.forEach(item => {\n\t\t\t\t\t\t\t\tif (item.type === 'text') {\n\t\t\t\t\t\t\t\t\ttransformedMessage.content.push({\n\t\t\t\t\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\t\t\t\t\ttext: item.text\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\t\titem.type === 'image_url' &&\n\t\t\t\t\t\t\t\t\titem.image_url &&\n\t\t\t\t\t\t\t\t\titem.image_url.url\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tconst parts = item.image_url.url.split(';');\n\t\t\t\t\t\t\t\t\tif (parts.length === 2) {\n\t\t\t\t\t\t\t\t\t\tconst base64ImageParts =\n\t\t\t\t\t\t\t\t\t\t\tparts[1].split(',');\n\t\t\t\t\t\t\t\t\t\tconst base64Image = base64ImageParts[1];\n\t\t\t\t\t\t\t\t\t\tconst mediaTypeParts =\n\t\t\t\t\t\t\t\t\t\t\tparts[0].split(':');\n\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\tmediaTypeParts.length === 2 &&\n\t\t\t\t\t\t\t\t\t\t\tbase64Image\n\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\tconst mediaType = mediaTypeParts[1];\n\t\t\t\t\t\t\t\t\t\t\ttransformedMessage.content.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: 'image',\n\t\t\t\t\t\t\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'base64',\n\t\t\t\t\t\t\t\t\t\t\t\t\tmedia_type: mediaType,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: base64Image\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tmessages.push(\n\t\t\t\t\t\t\t\ttransformedMessage as ProviderMessage\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (msg.role === 'tool') {\n\t\t\t\t\t\t\t// Combine consecutive tool messages into a single message\n\t\t\t\t\t\t\t// add consecutive tool message as tool_result in content array\n\t\t\t\t\t\t\tif (lastRole === 'tool') {\n\t\t\t\t\t\t\t\tconst toolMessage = transformToolMessage(msg);\n\t\t\t\t\t\t\t\tconst content =\n\t\t\t\t\t\t\t\t\ttoolMessage.content as AnthropicMessageContentItem[];\n\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\tmessages[messages.length - 1]\n\t\t\t\t\t\t\t\t\t\t.content as AnthropicMessageContentItem[]\n\t\t\t\t\t\t\t\t).push(content[0]);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tmessages.push(transformToolMessage(msg));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmessages.push({\n\t\t\t\t\t\t\t\trole: msg.role,\n\t\t\t\t\t\t\t\tcontent: msg.content\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastRole = msg.role;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn messages;\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tparam: 'system',\n\t\t\trequired: false,\n\t\t\ttransform: (params: ModelParams) => {\n\t\t\t\tlet systemMessage: string = '';\n\t\t\t\t// Transform the chat messages into a simple prompt\n\t\t\t\tif (!!params.messages) {\n\t\t\t\t\tparams.messages.forEach(msg => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tmsg.role === 'system' &&\n\t\t\t\t\t\t\tmsg.content &&\n\t\t\t\t\t\t\ttypeof msg.content === 'object' &&\n\t\t\t\t\t\t\tmsg.content[0].text\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tsystemMessage = msg.content[0].text;\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\tmsg.role === 'system' &&\n\t\t\t\t\t\t\ttypeof msg.content === 'string'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tsystemMessage = msg.content;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn systemMessage;\n\t\t\t}\n\t\t}\n\t],\n\ttools: {\n\t\tparam: 'tools',\n\t\trequired: false,\n\t\ttransform: (params: ModelParams) => {\n\t\t\tlet tools: AnthropicTool[] = [];\n\t\t\tif (params.tools) {\n\t\t\t\tparams.tools.forEach(tool => {\n\t\t\t\t\tif (tool.function) {\n\t\t\t\t\t\ttools.push({\n\t\t\t\t\t\t\tname: tool.function.name,\n\t\t\t\t\t\t\tdescription: tool.function?.description || '',\n\t\t\t\t\t\t\tinput_schema: {\n\t\t\t\t\t\t\t\ttype:\n\t\t\t\t\t\t\t\t\ttool.function.parameters?.type || 'object',\n\t\t\t\t\t\t\t\tproperties:\n\t\t\t\t\t\t\t\t\ttool.function.parameters?.properties || {},\n\t\t\t\t\t\t\t\trequired:\n\t\t\t\t\t\t\t\t\ttool.function.parameters?.required || []\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn tools;\n\t\t}\n\t},\n\t// None is not supported by Anthropic, defaults to auto\n\ttool_choice: {\n\t\tparam: 'tool_choice',\n\t\trequired: false,\n\t\ttransform: (params: ModelParams) => {\n\t\t\tlet toolChoice = {};\n\t\t\tif (params.tool_choice) {\n\t\t\t\tif (typeof params.tool_choice === 'string') {\n\t\t\t\t\tif (params.tool_choice === 'required')\n\t\t\t\t\t\ttoolChoice = { type: 'any' };\n\t\t\t\t\telse if (params.tool_choice === 'auto')\n\t\t\t\t\t\ttoolChoice = { type: 'auto' };\n\t\t\t\t} else if (typeof params.tool_choice === 'object') {\n\t\t\t\t\ttoolChoice = {\n\t\t\t\t\t\ttype: 'tool',\n\t\t\t\t\t\tname: params.tool_choice.function.name\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!params.parallel_tool_calls) {\n\t\t\t\ttoolChoice = { ...toolChoice, disable_parallel_tool_use: true };\n\t\t\t}\n\n\t\t\treturn toolChoice;\n\t\t}\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\trequired: true\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\ttop_p: {\n\t\tparam: 'top_p',\n\t\tdefault: -1,\n\t\tmin: -1\n\t},\n\ttop_k: {\n\t\tparam: 'top_k',\n\t\tdefault: -1\n\t},\n\tstop: {\n\t\tparam: 'stop_sequences'\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tuser: {\n\t\tparam: 'metadata.user_id'\n\t}\n};\n\nexport interface AnthropicErrorObject {\n\ttype: string;\n\tmessage: string;\n}\n\ninterface AnthropicErrorResponse {\n\ttype: string;\n\terror: AnthropicErrorObject;\n}\n\ninterface AnthropicChatCompleteResponse {\n\tid: string;\n\ttype: string;\n\trole: string;\n\tcontent: AnthropicContentItem[];\n\tstop_reason: string;\n\tmodel: string;\n\tstop_sequence: null | string;\n\tusage: {\n\t\tinput_tokens: number;\n\t\toutput_tokens: number;\n\t};\n}\n\nexport interface AnthropicChatCompleteStreamResponse {\n\ttype: string;\n\tindex: number;\n\tdelta: {\n\t\ttype: string;\n\t\ttext: string;\n\t\tpartial_json?: string;\n\t\tstop_reason?: string;\n\t};\n\tcontent_block?: {\n\t\ttype: string;\n\t\tid?: string;\n\t\ttext?: string;\n\t\tname?: string;\n\t\tinput?: {};\n\t};\n\tusage?: {\n\t\toutput_tokens?: number;\n\t\tinput_tokens?: number;\n\t\tcache_creation_input_tokens?: number;\n\t\tcache_read_input_tokens?: number;\n\t};\n\tmessage?: {\n\t\tusage?: {\n\t\t\toutput_tokens?: number;\n\t\t\tinput_tokens?: number;\n\t\t\tcache_creation_input_tokens?: number;\n\t\t\tcache_read_input_tokens?: number;\n\t\t};\n\t};\n}\n\nexport const AnthropicChatCompleteResponseTransform: (\n\tresponse: AnthropicChatCompleteResponse | AnthropicErrorResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\tif (responseStatus !== 200 && 'error' in response) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tmessage: response.error?.message,\n\t\t\t\ttype: response.error?.type,\n\t\t\t\tparam: null,\n\t\t\t\tcode: null\n\t\t\t},\n\t\t\tprovider: ANTHROPIC\n\t\t} as ErrorResponse;\n\t}\n\n\tif ('content' in response) {\n\t\tconst { input_tokens = 0, output_tokens = 0 } = response?.usage;\n\n\t\tlet content = '';\n\t\tif (response.content.length && response.content[0].type === 'text') {\n\t\t\tcontent = response.content[0].text;\n\t\t}\n\n\t\tlet toolCalls: any = [];\n\t\tresponse.content.forEach(item => {\n\t\t\tif (item.type === 'tool_use') {\n\t\t\t\ttoolCalls.push({\n\t\t\t\t\tid: item.id,\n\t\t\t\t\ttype: 'function',\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: item.name,\n\t\t\t\t\t\targuments: JSON.stringify(item.input)\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tid: response.id,\n\t\t\tobject: 'chat_completion',\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel: response.model,\n\t\t\tprovider: ANTHROPIC,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\ttool_calls: toolCalls.length ? toolCalls : undefined\n\t\t\t\t\t},\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tlogprobs: null,\n\t\t\t\t\tfinish_reason: response.stop_reason\n\t\t\t\t}\n\t\t\t],\n\t\t\tusage: {\n\t\t\t\tprompt_tokens: input_tokens,\n\t\t\t\tcompletion_tokens: output_tokens,\n\t\t\t\ttotal_tokens: input_tokens + output_tokens\n\t\t\t}\n\t\t};\n\t}\n\treturn generateInvalidProviderResponseError(response, ANTHROPIC);\n};\n\nexport const AnthropicChatCompleteStreamChunkTransform: (\n\tresponse: string,\n\tfallbackId: string\n) => string | undefined = (responseChunk, fallbackId) => {\n\tlet chunk = responseChunk.trim();\n\tif (\n\t\tchunk.startsWith('event: ping') ||\n\t\tchunk.startsWith('event: content_block_stop')\n\t) {\n\t\treturn;\n\t}\n\n\tif (chunk.startsWith('event: message_stop')) {\n\t\treturn 'data: [DONE]\\n\\n';\n\t}\n\n\tchunk = chunk.replace(/^event: content_block_delta[\\r\\n]*/, '');\n\tchunk = chunk.replace(/^event: content_block_start[\\r\\n]*/, '');\n\tchunk = chunk.replace(/^event: message_delta[\\r\\n]*/, '');\n\tchunk = chunk.replace(/^event: message_start[\\r\\n]*/, '');\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\n\tconst parsedChunk: AnthropicChatCompleteStreamResponse = JSON.parse(chunk);\n\n\tif (parsedChunk.type === 'message_start') {\n\t\treturn (\n\t\t\t`data: ${JSON.stringify({\n\t\t\t\tid: fallbackId,\n\t\t\t\tobject: 'chat.completion.chunk',\n\t\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\t\tmodel: '',\n\t\t\t\tprovider: ANTHROPIC,\n\t\t\t\tchoices: [\n\t\t\t\t\t{\n\t\t\t\t\t\tdelta: {\n\t\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\t\tcontent: ''\n\t\t\t\t\t\t},\n\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\tlogprobs: null,\n\t\t\t\t\t\tfinish_reason: null\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})}` + '\\n\\n'\n\t\t);\n\t}\n\n\tif (parsedChunk.type === 'message_delta') {\n\t\treturn (\n\t\t\t`data: ${JSON.stringify({\n\t\t\t\tid: fallbackId,\n\t\t\t\tobject: 'chat.completion.chunk',\n\t\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\t\tmodel: '',\n\t\t\t\tprovider: ANTHROPIC,\n\t\t\t\tchoices: [\n\t\t\t\t\t{\n\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\tdelta: {},\n\t\t\t\t\t\tfinish_reason: parsedChunk.delta?.stop_reason\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t})}` + '\\n\\n'\n\t\t);\n\t}\n\n\tconst toolCalls = [];\n\tconst isToolBlockStart: boolean =\n\t\tparsedChunk.type === 'content_block_start' &&\n\t\t!!parsedChunk.content_block?.id;\n\tconst isToolBlockDelta: boolean =\n\t\tparsedChunk.type === 'content_block_delta' &&\n\t\t!!parsedChunk.delta.partial_json;\n\tconst toolIndex: number = parsedChunk.index;\n\n\tif (isToolBlockStart && parsedChunk.content_block) {\n\t\ttoolCalls.push({\n\t\t\tindex: toolIndex,\n\t\t\tid: parsedChunk.content_block.id,\n\t\t\ttype: 'function',\n\t\t\tfunction: {\n\t\t\t\tname: parsedChunk.content_block.name,\n\t\t\t\targuments: ''\n\t\t\t}\n\t\t});\n\t} else if (isToolBlockDelta) {\n\t\ttoolCalls.push({\n\t\t\tindex: toolIndex,\n\t\t\tfunction: {\n\t\t\t\targuments: parsedChunk.delta.partial_json\n\t\t\t}\n\t\t});\n\t}\n\n\treturn (\n\t\t`data: ${JSON.stringify({\n\t\t\tid: fallbackId,\n\t\t\tobject: 'chat.completion.chunk',\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel: '',\n\t\t\tprovider: ANTHROPIC,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tdelta: {\n\t\t\t\t\t\tcontent: parsedChunk.delta?.text,\n\t\t\t\t\t\ttool_calls: toolCalls.length ? toolCalls : undefined\n\t\t\t\t\t},\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tlogprobs: null,\n\t\t\t\t\tfinish_reason: parsedChunk.delta?.stop_reason ?? null\n\t\t\t\t}\n\t\t\t]\n\t\t})}` + '\\n\\n'\n\t);\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport AnthropicAPIConfig from './api';\nimport {\n\tAnthropicChatCompleteConfig,\n\tAnthropicChatCompleteResponseTransform,\n\tAnthropicChatCompleteStreamChunkTransform\n} from './chatComplete';\n\nconst AnthropicConfig: ProviderConfigs = {\n\tchatComplete: AnthropicChatCompleteConfig,\n\tapi: AnthropicAPIConfig,\n\tresponseTransforms: {\n\t\tchatComplete: AnthropicChatCompleteResponseTransform,\n\t\t'stream-chatComplete': AnthropicChatCompleteStreamChunkTransform\n\t}\n};\n\nexport default AnthropicConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst OpenAIAPIConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.openai.com/v1',\n\theaders: (API_KEY: string) => {\n\t\treturn { Authorization: `Bearer ${API_KEY}` };\n\t},\n\tchatComplete: '/chat/completions'\n};\n\nexport default OpenAIAPIConfig;\n","import type { ChatCompletionResponse, ProviderConfig } from 'types/providers';\n\nexport const OpenAIChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true,\n\t\tdefault: 'gpt-4o-mini'\n\t},\n\tmessages: {\n\t\tparam: 'messages',\n\t\tdefault: ''\n\t},\n\tfunctions: {\n\t\tparam: 'functions'\n\t},\n\tfunction_call: {\n\t\tparam: 'function_call'\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\tdefault: 100,\n\t\tmin: 0\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 2\n\t},\n\ttop_p: {\n\t\tparam: 'top_p',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\tn: {\n\t\tparam: 'n',\n\t\tdefault: 1\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tstop: {\n\t\tparam: 'stop'\n\t},\n\tpresence_penalty: {\n\t\tparam: 'presence_penalty',\n\t\tmin: -2,\n\t\tmax: 2\n\t},\n\tfrequency_penalty: {\n\t\tparam: 'frequency_penalty',\n\t\tmin: -2,\n\t\tmax: 2\n\t},\n\tlogit_bias: {\n\t\tparam: 'logit_bias'\n\t},\n\tuser: {\n\t\tparam: 'user'\n\t},\n\tseed: {\n\t\tparam: 'seed'\n\t},\n\ttools: {\n\t\tparam: 'tools'\n\t},\n\ttool_choice: {\n\t\tparam: 'tool_choice'\n\t},\n\tresponse_format: {\n\t\tparam: 'response_format'\n\t},\n\tlogprobs: {\n\t\tparam: 'logprobs',\n\t\tdefault: false\n\t},\n\ttop_logprobs: {\n\t\tparam: 'top_logprobs'\n\t}\n};\n\nexport interface OpenAIChatCompleteResponse extends ChatCompletionResponse {\n\tsystem_fingerprint: string;\n}\n\nexport const OpenAIChatCompleteResponseTransform: (\n\tresponse: OpenAIChatCompleteResponse\n) => ChatCompletionResponse = response => response;\n","import type { ProviderConfigs } from 'types/providers';\nimport OpenAIAPIConfig from './api';\nimport { OpenAIChatCompleteConfig } from './chatComplete';\n\nconst OpenAIConfig: ProviderConfigs = {\n\tapi: OpenAIAPIConfig,\n\tchatComplete: OpenAIChatCompleteConfig\n};\n\nexport default OpenAIConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst TogetherAIApiConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.together.xyz',\n\theaders: (API_KEY: string) => {\n\t\treturn { Authorization: `Bearer ${API_KEY}` };\n\t},\n\tchatComplete: '/v1/chat/completions',\n\tcomplete: '/v1/completions',\n\tembed: '/v1/embeddings'\n};\n\nexport default TogetherAIApiConfig;\n","import { TOGETHER_AI } from '@/dev/data/models';\nimport type {\n\tChatCompletionResponse,\n\tErrorResponse,\n\tProviderConfig\n} from 'types/providers';\n\nexport const TogetherAIChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true,\n\t\tdefault: 'mistralai/Mistral-7B-Instruct-v0.1'\n\t},\n\tmessages: {\n\t\tparam: 'messages',\n\t\trequired: true,\n\t\tdefault: ''\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\trequired: true,\n\t\tdefault: 128,\n\t\tmin: 1\n\t},\n\tstop: {\n\t\tparam: 'stop'\n\t},\n\ttemperature: {\n\t\tparam: 'temperature'\n\t},\n\ttop_p: {\n\t\tparam: 'top_p'\n\t},\n\ttop_k: {\n\t\tparam: 'top_k'\n\t},\n\tfrequency_penalty: {\n\t\tparam: 'repetition_penalty'\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tlogprobs: {\n\t\tparam: 'logprobs'\n\t},\n\ttools: {\n\t\tparam: 'tools'\n\t},\n\ttool_choice: {\n\t\tparam: 'tool_choice'\n\t},\n\tresponse_format: {\n\t\tparam: 'response_format'\n\t}\n};\n\nexport interface TogetherAIChatCompleteResponse extends ChatCompletionResponse {\n\tusage: {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n}\n\nexport interface TogetherAIErrorResponse {\n\tmodel: string;\n\tjob_id: string;\n\trequest_id: string;\n\terror: string;\n\tmessage?: string;\n\ttype?: string;\n}\n\nexport interface TogetherAIOpenAICompatibleErrorResponse\n\textends ErrorResponse {}\n\nexport interface TogetherAIChatCompletionStreamChunk {\n\tid: string;\n\trequest_id: string;\n\tobject: string;\n\tchoices: {\n\t\tindex: number;\n\t\tdelta: {\n\t\t\tcontent: string;\n\t\t};\n\t}[];\n}\n\nexport const TogetherAIErrorResponseTransform: (\n\tresponse: TogetherAIErrorResponse | TogetherAIOpenAICompatibleErrorResponse\n) => ErrorResponse | false = response => {\n\tif ('error' in response && typeof response.error === 'string') {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tmessage: response.error,\n\t\t\t\ttype: null,\n\t\t\t\tparam: null,\n\t\t\t\tcode: null\n\t\t\t},\n\t\t\tprovider: TOGETHER_AI\n\t\t} as ErrorResponse;\n\t}\n\n\tif ('error' in response && typeof response.error === 'object') {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tmessage: response.error?.message || '',\n\t\t\t\ttype: response.error?.type || null,\n\t\t\t\tparam: response.error?.param || null,\n\t\t\t\tcode: response.error?.code || null\n\t\t\t},\n\t\t\tprovider: TOGETHER_AI\n\t\t} as ErrorResponse;\n\t}\n\n\tif ('message' in response) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tmessage: response.message,\n\t\t\t\ttype: response.type,\n\t\t\t\tparam: null,\n\t\t\t\tcode: null\n\t\t\t},\n\t\t\tprovider: TOGETHER_AI\n\t\t} as ErrorResponse;\n\t}\n\n\treturn false;\n};\n\nexport const TogetherAIChatCompleteResponseTransform: (\n\tresponse:\n\t\t| TogetherAIChatCompleteResponse\n\t\t| TogetherAIErrorResponse\n\t\t| TogetherAIOpenAICompatibleErrorResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\tif (responseStatus !== 200 && !('choices' in response)) {\n\t\tconst errorResponse = TogetherAIErrorResponseTransform(response);\n\t\tif (errorResponse) return errorResponse;\n\t}\n\n\tif ('choices' in response) {\n\t\treturn {\n\t\t\tid: response.id,\n\t\t\tobject: response.object,\n\t\t\tcreated: response.created,\n\t\t\tmodel: response.model,\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tchoices: response.choices.map(choice => {\n\t\t\t\treturn {\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\tcontent: choice.message.content,\n\t\t\t\t\t\ttool_calls: choice.message.tool_calls\n\t\t\t\t\t\t\t? choice.message.tool_calls.map(\n\t\t\t\t\t\t\t\t\t(toolCall: any) => ({\n\t\t\t\t\t\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\t\t\t\t\t\ttype: toolCall.type,\n\t\t\t\t\t\t\t\t\t\tfunction: toolCall.function\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: null\n\t\t\t\t\t},\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tlogprobs: null,\n\t\t\t\t\tfinish_reason: choice.finish_reason\n\t\t\t\t};\n\t\t\t}),\n\t\t\tusage: {\n\t\t\t\tprompt_tokens: response.usage?.prompt_tokens,\n\t\t\t\tcompletion_tokens: response.usage?.completion_tokens,\n\t\t\t\ttotal_tokens: response.usage?.total_tokens\n\t\t\t}\n\t\t};\n\t}\n\treturn {\n\t\terror: {\n\t\t\tmessage: `Invalid response recieved from together-ai: ${JSON.stringify(response)}`,\n\t\t\ttype: null,\n\t\t\tparam: null,\n\t\t\tcode: null\n\t\t},\n\t\tprovider: TOGETHER_AI\n\t} as ErrorResponse;\n};\n\nexport const TogetherAIChatCompleteStreamChunkTransform: (\n\tresponse: string\n) => string = responseChunk => {\n\tlet chunk = responseChunk.trim();\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\tif (chunk === '[DONE]') {\n\t\treturn `data: ${chunk}\\n\\n`;\n\t}\n\tconst parsedChunk: TogetherAIChatCompletionStreamChunk = JSON.parse(chunk);\n\treturn (\n\t\t`data: ${JSON.stringify({\n\t\t\tid: parsedChunk.id,\n\t\t\tobject: parsedChunk.object,\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel: '',\n\t\t\tprovider: TOGETHER_AI,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tdelta: {\n\t\t\t\t\t\tcontent: parsedChunk.choices[0]?.delta.content\n\t\t\t\t\t},\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tfinish_reason: ''\n\t\t\t\t}\n\t\t\t]\n\t\t})}` + '\\n\\n'\n\t);\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport TogetherAIApiConfig from './api';\nimport { TogetherAIChatCompleteConfig } from './chatComplete';\n\nconst TogetherAIConfig: ProviderConfigs = {\n\tchatComplete: TogetherAIChatCompleteConfig,\n\tapi: TogetherAIApiConfig\n};\n\nexport default TogetherAIConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst GroqAPIConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.groq.com/openai/v1',\n\theaders: (llmApiKey: string) => {\n\t\treturn { Authorization: `Bearer ${llmApiKey}` };\n\t},\n\tchatComplete: '/chat/completions'\n};\n\nexport default GroqAPIConfig;\n","import type { ProviderConfig } from 'types/providers';\nexport const GroqChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true,\n\t\tdefault: 'mixtral-8x7b-32768'\n\t},\n\tmessages: {\n\t\tparam: 'messages',\n\t\tdefault: ''\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\tdefault: 100,\n\t\tmin: 0\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 2\n\t},\n\ttop_p: {\n\t\tparam: 'top_p',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tstop: {\n\t\tparam: 'stop'\n\t},\n\tn: {\n\t\tparam: 'n',\n\t\tdefault: 1,\n\t\tmax: 1,\n\t\tmin: 1\n\t}\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport GroqAPIConfig from './api';\nimport { GroqChatCompleteConfig } from './chatComplete';\n\nconst GroqConfig: ProviderConfigs = {\n\tchatComplete: GroqChatCompleteConfig,\n\tapi: GroqAPIConfig\n};\n\nexport default GroqConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst GoogleApiConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://generativelanguage.googleapis.com/v1beta',\n\theaders: () => {\n\t\treturn { 'Content-Type': 'application/json' };\n\t},\n\tgetEndpoint: ({\n\t\tendpoint,\n\t\tllmApiKey,\n\t\tmodel,\n\t\tstream\n\t}: {\n\t\tendpoint: string;\n\t\tllmApiKey: string;\n\t\tmodel: string;\n\t\tstream: boolean;\n\t}) => {\n\t\tlet mappedEndpoint = endpoint;\n\t\tif (stream) {\n\t\t\tmappedEndpoint = `stream-${endpoint}`;\n\t\t}\n\t\tswitch (mappedEndpoint) {\n\t\t\tcase 'chatComplete': {\n\t\t\t\treturn `/models/${model}:generateContent?key=${llmApiKey}`;\n\t\t\t}\n\t\t\tcase 'stream-chatComplete': {\n\t\t\t\treturn `/models/${model}:streamGenerateContent?key=${llmApiKey}`;\n\t\t\t}\n\t\t}\n\t}\n};\n\nexport default GoogleApiConfig;\n","import {\n\tgenerateErrorResponse,\n\tgenerateInvalidProviderResponseError,\n\tgetMimeType\n} from '../utils';\nimport { GOOGLE } from '@/dev/data/models';\nimport type { ToolCall, ToolChoice } from 'types/pipe';\nimport type {\n\tChatCompletionResponse,\n\tContentType,\n\tErrorResponse,\n\tMessageRole,\n\tModelParams,\n\tProviderConfig,\n\tProviderMessage\n} from 'types/providers';\n\nconst transformGenerationConfig = (params: ModelParams) => {\n\tconst generationConfig: Record<string, any> = {};\n\tif (params['temperature']) {\n\t\tgenerationConfig['temperature'] = params['temperature'];\n\t}\n\tif (params['top_p']) {\n\t\tgenerationConfig['topP'] = params['top_p'];\n\t}\n\tif (params['top_k']) {\n\t\tgenerationConfig['topK'] = params['top_k'];\n\t}\n\tif (params['max_tokens']) {\n\t\tgenerationConfig['maxOutputTokens'] = params['max_tokens'];\n\t}\n\tif (params['stop']) {\n\t\tgenerationConfig['stopSequences'] = params['stop'];\n\t}\n\treturn generationConfig;\n};\n\nexport type GoogleMessageRole = 'user' | 'model' | 'function';\n\ninterface GoogleFunctionCallMessagePart {\n\tfunctionCall: GoogleGenerateFunctionCall;\n}\n\ninterface GoogleFunctionResponseMessagePart {\n\tfunctionResponse: {\n\t\tname: string;\n\t\tresponse: {\n\t\t\tname?: string;\n\t\t\tcontent: string;\n\t\t};\n\t};\n}\n\ntype GoogleMessagePart =\n\t| GoogleFunctionCallMessagePart\n\t| GoogleFunctionResponseMessagePart\n\t| { text: string };\n\nexport interface GoogleMessage {\n\trole: GoogleMessageRole;\n\tparts: GoogleMessagePart[];\n}\n\nexport interface GoogleToolConfig {\n\tfunction_calling_config: {\n\t\tmode: GoogleToolChoiceType | undefined;\n\t\tallowed_function_names?: string[];\n\t};\n}\n\nexport const transformOpenAIRoleToGoogleRole = (\n\trole: MessageRole\n): GoogleMessageRole => {\n\tswitch (role) {\n\t\tcase 'assistant':\n\t\t\treturn 'model';\n\t\tcase 'tool':\n\t\t\treturn 'function';\n\t\t// Not all gemini models support system role\n\t\tcase 'system':\n\t\t\treturn 'user';\n\t\t// user is the default role\n\t\tdefault:\n\t\t\treturn role;\n\t}\n};\n\ntype GoogleToolChoiceType = 'AUTO' | 'ANY' | 'NONE';\n\nexport const transformToolChoiceForGemini = (\n\ttool_choice: ToolChoice\n): GoogleToolChoiceType | undefined => {\n\tif (typeof tool_choice === 'object' && tool_choice.type === 'function')\n\t\treturn 'ANY';\n\tif (typeof tool_choice === 'string') {\n\t\tswitch (tool_choice) {\n\t\t\tcase 'auto':\n\t\t\t\treturn 'AUTO';\n\t\t\tcase 'none':\n\t\t\t\treturn 'NONE';\n\t\t\tcase 'required':\n\t\t\t\treturn 'ANY';\n\t\t}\n\t}\n\treturn undefined;\n};\n\nexport const GoogleChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true,\n\t\tdefault: 'gemini-pro'\n\t},\n\tmessages: {\n\t\tparam: 'contents',\n\t\tdefault: '',\n\t\ttransform: (params: ModelParams) => {\n\t\t\tconst messages: GoogleMessage[] = [];\n\t\t\tlet lastRole: GoogleMessageRole | undefined;\n\n\t\t\tparams.messages?.forEach((message: ProviderMessage) => {\n\t\t\t\tconst role = transformOpenAIRoleToGoogleRole(message.role);\n\t\t\t\tlet parts = [];\n\n\t\t\t\tif (message.role === 'assistant' && message.tool_calls) {\n\t\t\t\t\tmessage.tool_calls.forEach((tool_call: ToolCall) => {\n\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\tfunctionCall: {\n\t\t\t\t\t\t\t\tname: tool_call.function.name,\n\t\t\t\t\t\t\t\targs: JSON.parse(tool_call.function.arguments)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t} else if (\n\t\t\t\t\tmessage.role === 'tool' &&\n\t\t\t\t\ttypeof message.content === 'string'\n\t\t\t\t) {\n\t\t\t\t\tparts.push({\n\t\t\t\t\t\tfunctionResponse: {\n\t\t\t\t\t\t\tname: message.name ?? 'lb-random-tool-name',\n\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\tcontent: message.content\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else if (\n\t\t\t\t\tmessage.content &&\n\t\t\t\t\ttypeof message.content === 'object'\n\t\t\t\t) {\n\t\t\t\t\tmessage.content.forEach((c: ContentType) => {\n\t\t\t\t\t\tif (c.type === 'text') {\n\t\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\t\ttext: c.text\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (c.type === 'image_url') {\n\t\t\t\t\t\t\tconst { url } = c.image_url || {};\n\t\t\t\t\t\t\tif (!url) return;\n\n\t\t\t\t\t\t\t// Handle different types of image URLs\n\t\t\t\t\t\t\tif (url.startsWith('data:')) {\n\t\t\t\t\t\t\t\tconst [mimeTypeWithPrefix, base64Image] =\n\t\t\t\t\t\t\t\t\turl.split(';base64,');\n\t\t\t\t\t\t\t\tconst mimeType =\n\t\t\t\t\t\t\t\t\tmimeTypeWithPrefix.split(':')[1];\n\n\t\t\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\t\t\tinlineData: {\n\t\t\t\t\t\t\t\t\t\tmimeType: mimeType,\n\t\t\t\t\t\t\t\t\t\tdata: base64Image\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\turl.startsWith('gs://') ||\n\t\t\t\t\t\t\t\turl.startsWith('https://') ||\n\t\t\t\t\t\t\t\turl.startsWith('http://')\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\t\t\tfileData: {\n\t\t\t\t\t\t\t\t\t\tmimeType: getMimeType(url),\n\t\t\t\t\t\t\t\t\t\tfileUri: url\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\t\t\tinlineData: {\n\t\t\t\t\t\t\t\t\t\tmimeType: 'image/jpeg',\n\t\t\t\t\t\t\t\t\t\tdata: c.image_url?.url\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else if (typeof message.content === 'string') {\n\t\t\t\t\tparts.push({\n\t\t\t\t\t\ttext: message.content\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Combine consecutive messages if they are from the same role\n\t\t\t\t// This takes care of the \"Please ensure that multiturn requests alternate between user and model.\n\t\t\t\t// Also possible fix for \"Please ensure that function call turn comes immediately after a user turn or after a function response turn.\" in parallel tool calls\n\t\t\t\tconst shouldCombineMessages =\n\t\t\t\t\tlastRole === role && !params.model?.includes('vision');\n\n\t\t\t\tif (shouldCombineMessages) {\n\t\t\t\t\tmessages[messages.length - 1].parts.push(...parts);\n\t\t\t\t} else {\n\t\t\t\t\tmessages.push({ role, parts });\n\t\t\t\t}\n\t\t\t\tlastRole = role;\n\t\t\t});\n\t\t\treturn messages;\n\t\t}\n\t},\n\ttemperature: {\n\t\tparam: 'generationConfig',\n\t\ttransform: (params: ModelParams) => transformGenerationConfig(params)\n\t},\n\ttop_p: {\n\t\tparam: 'generationConfig',\n\t\ttransform: (params: ModelParams) => transformGenerationConfig(params)\n\t},\n\ttop_k: {\n\t\tparam: 'generationConfig',\n\t\ttransform: (params: ModelParams) => transformGenerationConfig(params)\n\t},\n\tmax_tokens: {\n\t\tparam: 'generationConfig',\n\t\ttransform: (params: ModelParams) => transformGenerationConfig(params)\n\t},\n\tstop: {\n\t\tparam: 'generationConfig',\n\t\ttransform: (params: ModelParams) => transformGenerationConfig(params)\n\t},\n\ttools: {\n\t\tparam: 'tools',\n\t\tdefault: '',\n\t\ttransform: (params: ModelParams) => {\n\t\t\tconst functionDeclarations: any = [];\n\t\t\tparams.tools?.forEach(tool => {\n\t\t\t\tif (tool.type === 'function') {\n\t\t\t\t\tfunctionDeclarations.push(tool.function);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn [{ functionDeclarations }];\n\t\t}\n\t},\n\ttool_choice: {\n\t\tparam: 'tool_config',\n\t\tdefault: '',\n\t\ttransform: (params: ModelParams) => {\n\t\t\tif (params.tool_choice) {\n\t\t\t\tconst allowedFunctionNames: string[] = [];\n\t\t\t\t// If tool_choice is an object and type is function, add the function name to allowedFunctionNames\n\t\t\t\tif (\n\t\t\t\t\ttypeof params.tool_choice === 'object' &&\n\t\t\t\t\tparams.tool_choice.type === 'function'\n\t\t\t\t) {\n\t\t\t\t\tallowedFunctionNames.push(params.tool_choice.function.name);\n\t\t\t\t}\n\t\t\t\tconst toolConfig: GoogleToolConfig = {\n\t\t\t\t\tfunction_calling_config: {\n\t\t\t\t\t\tmode: transformToolChoiceForGemini(params.tool_choice)\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\t// TODO: @msaaddev I think we can't have more than one function in tool_choice\n\t\t\t\t// but this will also handle the case if we have more than one function in tool_choice\n\n\t\t\t\t// If tool_choice has functions, add the function names to allowedFunctionNames\n\t\t\t\tif (allowedFunctionNames.length > 0) {\n\t\t\t\t\ttoolConfig.function_calling_config.allowed_function_names =\n\t\t\t\t\t\tallowedFunctionNames;\n\t\t\t\t}\n\t\t\t\treturn toolConfig;\n\t\t\t}\n\t\t}\n\t}\n};\n\nexport interface GoogleErrorResponse {\n\terror: {\n\t\tcode: number;\n\t\tmessage: string;\n\t\tstatus: string;\n\t\tdetails: Array<Record<string, any>>;\n\t};\n}\n\ninterface GoogleGenerateFunctionCall {\n\tname: string;\n\targs: Record<string, any>;\n}\n\ninterface GoogleGenerateContentResponse {\n\tcandidates: {\n\t\tcontent: {\n\t\t\tparts: {\n\t\t\t\ttext?: string;\n\t\t\t\tfunctionCall?: GoogleGenerateFunctionCall;\n\t\t\t}[];\n\t\t};\n\t\tfinishReason: string;\n\t\tindex: number;\n\t\tsafetyRatings: {\n\t\t\tcategory: string;\n\t\t\tprobability: string;\n\t\t}[];\n\t}[];\n\tpromptFeedback: {\n\t\tsafetyRatings: {\n\t\t\tcategory: string;\n\t\t\tprobability: string;\n\t\t}[];\n\t};\n\tusageMetadata: {\n\t\tpromptTokenCount: number;\n\t\tcandidatesTokenCount: number;\n\t\ttotalTokenCount: number;\n\t};\n}\n\nexport const GoogleChatCompleteResponseTransform: (\n\tresponse: GoogleGenerateContentResponse | GoogleErrorResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\t// Extract error from response. It is in an array when streaming, and object when not streaming\n\tconst errorObject = Array.isArray(response)\n\t\t? response.find(item => 'error' in item)?.error\n\t\t: 'error' in response\n\t\t\t? response.error\n\t\t\t: null;\n\n\tif (responseStatus !== 200 && errorObject) {\n\t\treturn generateErrorResponse(\n\t\t\t{\n\t\t\t\tmessage: errorObject?.message ?? '',\n\t\t\t\ttype: errorObject?.status ?? null,\n\t\t\t\tparam: null,\n\t\t\t\tcode: errorObject?.code ? `${errorObject.code}` : null\n\t\t\t},\n\t\t\tGOOGLE\n\t\t);\n\t}\n\tif ('candidates' in response) {\n\t\treturn {\n\t\t\tid: crypto.randomUUID(),\n\t\t\tobject: 'chat_completion',\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel: 'Unknown',\n\t\t\tprovider: GOOGLE,\n\t\t\tchoices:\n\t\t\t\tresponse.candidates?.map(generation => {\n\t\t\t\t\t// In blocking mode: Google AI does not return content if response > max output tokens param\n\t\t\t\t\t// Test it by asking a big response while keeping maxtokens low ~ 50\n\t\t\t\t\tif (\n\t\t\t\t\t\tgeneration.finishReason === 'MAX_TOKENS' &&\n\t\t\t\t\t\t!generation.content\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t\t'The response exceeded your Max Tokens limit parameter. Increase the limit or change the prompt accordingly.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet message: ProviderMessage = {\n\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\tcontent: ''\n\t\t\t\t\t};\n\t\t\t\t\tif (generation.content?.parts[0]?.text) {\n\t\t\t\t\t\tmessage = {\n\t\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\t\tcontent: generation.content.parts[0]?.text\n\t\t\t\t\t\t};\n\t\t\t\t\t} else if (generation.content?.parts[0]?.functionCall) {\n\t\t\t\t\t\tmessage = {\n\t\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\t\tcontent: null,\n\t\t\t\t\t\t\ttool_calls: generation.content.parts.map(part => {\n\t\t\t\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\t\t\t\t\t\t\ttype: 'function',\n\t\t\t\t\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\t\t\t\t\tname: part.functionCall.name,\n\t\t\t\t\t\t\t\t\t\t\targuments: JSON.stringify(\n\t\t\t\t\t\t\t\t\t\t\t\tpart.functionCall.args\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmessage: message,\n\t\t\t\t\t\tindex: generation.index,\n\t\t\t\t\t\tfinish_reason: generation.finishReason\n\t\t\t\t\t};\n\t\t\t\t}) ?? [],\n\t\t\tusage: {\n\t\t\t\tprompt_tokens: response.usageMetadata.promptTokenCount,\n\t\t\t\tcompletion_tokens: response.usageMetadata.candidatesTokenCount,\n\t\t\t\ttotal_tokens: response.usageMetadata.totalTokenCount\n\t\t\t}\n\t\t};\n\t}\n\n\treturn generateInvalidProviderResponseError(response, GOOGLE);\n};\n\nexport const GoogleChatCompleteStreamChunkTransform: (\n\tresponse: string,\n\tfallbackId: string\n) => string = (responseChunk, fallbackId) => {\n\tlet chunk = responseChunk.trim();\n\tif (chunk.startsWith('[')) {\n\t\tchunk = chunk.slice(1);\n\t}\n\n\tif (chunk.endsWith(',')) {\n\t\tchunk = chunk.slice(0, chunk.length - 1);\n\t}\n\tif (chunk.endsWith(']')) {\n\t\tchunk = chunk.slice(0, chunk.length - 2);\n\t}\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\tif (chunk === '[DONE]') {\n\t\treturn `data: ${chunk}\\n\\n`;\n\t}\n\n\tconst parsedChunk: GoogleGenerateContentResponse = JSON.parse(chunk);\n\n\treturn (\n\t\t`data: ${JSON.stringify({\n\t\t\tid: fallbackId,\n\t\t\tobject: 'chat.completion.chunk',\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel: '',\n\t\t\tprovider: 'google',\n\t\t\tchoices:\n\t\t\t\tparsedChunk.candidates?.map((generation, index) => {\n\t\t\t\t\tlet message: ProviderMessage = {\n\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\tcontent: ''\n\t\t\t\t\t};\n\t\t\t\t\tif (generation.content.parts[0]?.text) {\n\t\t\t\t\t\tmessage = {\n\t\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\t\tcontent: generation.content.parts[0]?.text\n\t\t\t\t\t\t};\n\t\t\t\t\t} else if (generation.content.parts[0]?.functionCall) {\n\t\t\t\t\t\tmessage = {\n\t\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\t\ttool_calls: generation.content.parts.map(\n\t\t\t\t\t\t\t\t(part, idx) => {\n\t\t\t\t\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tindex: idx,\n\t\t\t\t\t\t\t\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\t\t\t\t\t\t\t\ttype: 'function',\n\t\t\t\t\t\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\t\t\t\t\t\tname: part.functionCall.name,\n\t\t\t\t\t\t\t\t\t\t\t\targuments: JSON.stringify(\n\t\t\t\t\t\t\t\t\t\t\t\t\tpart.functionCall.args\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdelta: message,\n\t\t\t\t\t\tindex: generation.index ?? index,\n\t\t\t\t\t\tfinish_reason: generation.finishReason\n\t\t\t\t\t};\n\t\t\t\t}) ?? []\n\t\t})}` + '\\n\\n'\n\t);\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport GoogleApiConfig from './api';\nimport {\n\tGoogleChatCompleteConfig,\n\tGoogleChatCompleteResponseTransform,\n\tGoogleChatCompleteStreamChunkTransform\n} from './chatComplete';\n\nconst GoogleConfig: ProviderConfigs = {\n\tapi: GoogleApiConfig,\n\tchatComplete: GoogleChatCompleteConfig,\n\tresponseTransforms: {\n\t\tchatComplete: GoogleChatCompleteResponseTransform,\n\t\t'stream-chatComplete': GoogleChatCompleteStreamChunkTransform\n\t}\n};\n\nexport default GoogleConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst CohereAPIConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.cohere.ai/v1',\n\theaders: (llmApiKey: string) => {\n\t\treturn { Authorization: `Bearer ${llmApiKey}` };\n\t},\n\tchatComplete: '/chat'\n};\n\nexport default CohereAPIConfig;\n","import type {\n\tChatCompletionResponse,\n\tErrorResponse,\n\tProviderConfig,\n\tModelParams,\n\tProviderMessage\n} from 'types/providers';\n\nimport { generateErrorResponse } from '../utils';\nimport { COHERE } from '@/dev/data/models';\n\nexport const CohereChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\tdefault: 'command-r',\n\t\trequired: true\n\t},\n\tmessages: [\n\t\t{\n\t\t\tparam: 'message',\n\t\t\trequired: true,\n\t\t\t// Adds the last message's content to the message param\n\t\t\ttransform: (params: ModelParams) => {\n\t\t\t\tlet message: string = '';\n\n\t\t\t\tif (!!params.messages) {\n\t\t\t\t\tlet messages: ProviderMessage[] = params.messages;\n\t\t\t\t\tlet lastMessage = messages[messages.length - 1];\n\n\t\t\t\t\t// Check if last message's content is a string\n\t\t\t\t\tif (typeof lastMessage.content === 'string') {\n\t\t\t\t\t\tmessage = lastMessage.content;\n\t\t\t\t\t}\n\t\t\t\t\t// TODO: Handle if content is an object\n\t\t\t\t}\n\t\t\t\treturn message;\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tparam: 'chat_history',\n\t\t\t// Adds all messages except the last one to the chat_history param which is an array of objects with role and message\n\t\t\ttransform: (params: ModelParams) => {\n\t\t\t\tlet chat_history: { role: string; message: string }[] = [];\n\n\t\t\t\tif (!!params.messages) {\n\t\t\t\t\tlet messages: ProviderMessage[] = params.messages;\n\n\t\t\t\t\t// Retrun if there is only one message. No need to add it to chat_history\n\t\t\t\t\tif (messages.length === 1) return chat_history;\n\t\t\t\t\t// Remove the last message. It will be sent as the message param\n\t\t\t\t\tmessages.pop();\n\n\t\t\t\t\tmessages.forEach(msg => {\n\t\t\t\t\t\tif (typeof msg.content === 'string') {\n\t\t\t\t\t\t\t// Map roles to the ones accepted by Cohere. Default is USER.\n\t\t\t\t\t\t\tlet role: 'CHATBOT' | 'SYSTEM' | 'USER' = 'USER';\n\t\t\t\t\t\t\tif (msg.role === 'assistant') {\n\t\t\t\t\t\t\t\trole = 'CHATBOT';\n\t\t\t\t\t\t\t} else if (msg.role === 'system') {\n\t\t\t\t\t\t\t\trole = 'SYSTEM';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tchat_history.push({ role, message: msg.content });\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn chat_history;\n\t\t\t}\n\t\t}\n\t],\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\tdefault: 50,\n\t\tmin: 1\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tdefault: 0.3,\n\t\tmin: 0,\n\t\tmax: 5\n\t},\n\ttop_p: {\n\t\tparam: 'p',\n\t\tdefault: 0.75,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\ttop_k: {\n\t\tparam: 'k',\n\t\tdefault: 0,\n\t\tmax: 500\n\t},\n\tfrequency_penalty: {\n\t\tparam: 'frequency_penalty',\n\t\tdefault: 0,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\t// TODO: @ahmadbilaldev Error: cannot specify both frequency_penalty and presence_penalty. However, docs say this is supported.\n\t// presence_penalty: {\n\t// \tparam: \"presence_penalty\",\n\t// \tdefault: 0,\n\t// \tmin: 0,\n\t// \tmax: 1,\n\t// },\n\tstop: {\n\t\tparam: 'stop_sequences'\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tprompt_truncation: {\n\t\tparam: 'prompt_truncation',\n\t\tdefault: 'OFF',\n\t\trequired: true\n\t}\n};\n\ninterface CohereCompleteResponse {\n\tresponse_id: string;\n\ttext: string;\n\tchat_history: {\n\t\trole: string;\n\t\tmessage: string;\n\t}[];\n\tfinish_reason: string;\n\tmeta: {\n\t\tapi_version: {\n\t\t\tversion: string;\n\t\t};\n\t\ttokens: {\n\t\t\tinput_tokens: number;\n\t\t\toutput_tokens: number;\n\t\t};\n\t};\n\tmessage?: string;\n\tstatus?: number;\n}\n\nexport const CohereChatCompleteResponseTransform: (\n\tresponse: CohereCompleteResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\tif (responseStatus !== 200) {\n\t\treturn generateErrorResponse(\n\t\t\t{\n\t\t\t\tmessage: response.message || '',\n\t\t\t\ttype: null,\n\t\t\t\tparam: null,\n\t\t\t\tcode: null\n\t\t\t},\n\t\t\tCOHERE\n\t\t);\n\t}\n\tconst { input_tokens = 0, output_tokens = 0 } = response.meta?.tokens;\n\n\treturn {\n\t\tid: response.response_id,\n\t\tobject: 'chat_completion',\n\t\tcreated: Math.floor(Date.now() / 1000),\n\t\tmodel: 'Unknown',\n\t\tprovider: COHERE,\n\t\tchoices: [\n\t\t\t{\n\t\t\t\tmessage: { role: 'assistant', content: response.text },\n\t\t\t\tindex: 0,\n\t\t\t\tfinish_reason: response.finish_reason\n\t\t\t}\n\t\t],\n\t\tusage: {\n\t\t\tprompt_tokens: input_tokens,\n\t\t\tcompletion_tokens: output_tokens,\n\t\t\ttotal_tokens: input_tokens + output_tokens\n\t\t}\n\t};\n};\n\nexport interface CohereStreamChunk {\n\tid?: string;\n\tresponse: {\n\t\tgenerations?: {\n\t\t\tid: string;\n\t\t\ttext: string;\n\t\t\tfinish_reason: boolean;\n\t\t}[];\n\t};\n\tprompt?: string;\n\tmeta?: {\n\t\tapi_version: {\n\t\t\tversion: string;\n\t\t};\n\t};\n\ttext: string;\n\tis_finished: boolean;\n\tindex?: number;\n}\n\nexport const CohereChatCompleteStreamChunkTransform: (\n\tresponse: string,\n\tfallbackId: string\n) => string = (responseChunk, fallbackId) => {\n\tlet chunk = responseChunk.trim();\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\tconst parsedChunk: CohereStreamChunk = JSON.parse(chunk);\n\n\t// discard the last cohere chunk as it sends the whole response combined.\n\tif (parsedChunk.is_finished) {\n\t\treturn '';\n\t}\n\treturn (\n\t\t`data: ${JSON.stringify({\n\t\t\tid: parsedChunk.id ?? fallbackId,\n\t\t\tobject: 'chat.completion.chunk',\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel: '',\n\t\t\tprovider: COHERE,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tdelta: {\n\t\t\t\t\t\tcontent:\n\t\t\t\t\t\t\tparsedChunk.response?.generations?.[0]?.text ??\n\t\t\t\t\t\t\tparsedChunk.text\n\t\t\t\t\t},\n\t\t\t\t\tindex: parsedChunk.index ?? 0,\n\t\t\t\t\tlogprobs: null,\n\t\t\t\t\tfinish_reason:\n\t\t\t\t\t\tparsedChunk.response?.generations?.[0]?.finish_reason ??\n\t\t\t\t\t\tnull\n\t\t\t\t}\n\t\t\t]\n\t\t})}` + '\\n\\n'\n\t);\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport CohereAPIConfig from './api';\nimport {\n\tCohereChatCompleteConfig,\n\tCohereChatCompleteResponseTransform,\n\tCohereChatCompleteStreamChunkTransform\n} from './chatComplete';\n\nconst CohereConfig: ProviderConfigs = {\n\tchatComplete: CohereChatCompleteConfig,\n\tapi: CohereAPIConfig,\n\tresponseTransforms: {\n\t\tchatComplete: CohereChatCompleteResponseTransform,\n\t\t'stream-chatComplete': CohereChatCompleteStreamChunkTransform\n\t}\n};\n\nexport default CohereConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst FireworksAIAPIConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.fireworks.ai/inference/v1',\n\theaders: ({ llmApiKey }: { llmApiKey: string }) => {\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${llmApiKey}`,\n\t\t\tAccept: 'application/json'\n\t\t};\n\t},\n\tgetEndpoint: ({ endpoint }: { endpoint: string }) => {\n\t\tswitch (endpoint) {\n\t\t\tcase 'chatComplete':\n\t\t\t\treturn '/chat/completions';\n\t\t\tdefault:\n\t\t\t\treturn '';\n\t\t}\n\t}\n};\n\nexport default FireworksAIAPIConfig;\n","import { FIREWORKS_AI } from '@/dev/data/models';\nimport {\n\tgenerateErrorResponse,\n\tgenerateInvalidProviderResponseError\n} from '../utils';\n\nimport type {\n\tChatCompletionResponse,\n\tErrorResponse,\n\tProviderConfig\n} from 'types/providers';\n\nexport const FireworksAIChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true\n\t},\n\tmessages: {\n\t\tparam: 'messages',\n\t\trequired: true,\n\t\tdefault: []\n\t},\n\ttools: {\n\t\tparam: 'tools'\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\tdefault: 200,\n\t\tmin: 1\n\t},\n\tprompt_truncate_len: {\n\t\tparam: 'prompt_truncate_len',\n\t\tdefault: 1500\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 2\n\t},\n\ttop_p: {\n\t\tparam: 'top_p',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\ttop_k: {\n\t\tparam: 'top_k',\n\t\tmin: 1,\n\t\tmax: 128\n\t},\n\tfrequency_penalty: {\n\t\tparam: 'frequency_penalty',\n\t\tmin: -2,\n\t\tmax: 2\n\t},\n\tpresence_penalty: {\n\t\tparam: 'presence_penalty',\n\t\tmin: -2,\n\t\tmax: 2\n\t},\n\tn: {\n\t\tparam: 'n',\n\t\tdefault: 1,\n\t\tmin: 1,\n\t\tmax: 128\n\t},\n\tstop: {\n\t\tparam: 'stop'\n\t},\n\tresponse_format: {\n\t\tparam: 'response_format'\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tcontext_length_exceeded_behavior: {\n\t\tparam: 'context_length_exceeded_behavior'\n\t},\n\tuser: {\n\t\tparam: 'user'\n\t}\n};\n\ninterface FireworksAIChatCompleteResponse extends ChatCompletionResponse {\n\tid: string;\n\tobject: string;\n\tcreated: number;\n\tmodel: string;\n\tusage: {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n}\n\nexport interface FireworksAIValidationErrorResponse {\n\tfault: {\n\t\tfaultstring: string;\n\t\tdetail: {\n\t\t\terrorcode: string;\n\t\t};\n\t};\n}\n\nexport interface FireworksAIErrorResponse extends ErrorResponse {}\n\nexport interface FireworksAIStreamChunk {\n\tid: string;\n\tobject: string;\n\tcreated: number;\n\tmodel: string;\n\tchoices: {\n\t\tdelta: {\n\t\t\trole?: string | null;\n\t\t\tcontent?: string;\n\t\t};\n\t\tindex: number;\n\t\tfinish_reason: string | null;\n\t}[];\n\tusage: null | {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n}\n\nexport const FireworksAIErrorResponseTransform: (\n\tresponse: FireworksAIValidationErrorResponse | FireworksAIErrorResponse\n) => ErrorResponse = response => {\n\tif ('fault' in response) {\n\t\treturn generateErrorResponse(\n\t\t\t{\n\t\t\t\tmessage: response.fault.faultstring,\n\t\t\t\ttype: null,\n\t\t\t\tparam: null,\n\t\t\t\tcode: response.fault.detail.errorcode\n\t\t\t},\n\t\t\tFIREWORKS_AI\n\t\t);\n\t} else if ('detail' in response) {\n\t\treturn generateErrorResponse(\n\t\t\t{\n\t\t\t\tmessage: response.detail as string,\n\t\t\t\ttype: null,\n\t\t\t\tparam: null,\n\t\t\t\tcode: null\n\t\t\t},\n\t\t\tFIREWORKS_AI\n\t\t);\n\t}\n\treturn generateErrorResponse(\n\t\t{\n\t\t\tmessage: response.error as unknown as string,\n\t\t\ttype: null,\n\t\t\tparam: null,\n\t\t\tcode: null\n\t\t},\n\t\tFIREWORKS_AI\n\t);\n};\n\nexport const FireworksAIChatCompleteResponseTransform: (\n\tresponse:\n\t\t| FireworksAIChatCompleteResponse\n\t\t| FireworksAIValidationErrorResponse\n\t\t| FireworksAIErrorResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\tif (responseStatus !== 200) {\n\t\treturn FireworksAIErrorResponseTransform(\n\t\t\tresponse as\n\t\t\t\t| FireworksAIValidationErrorResponse\n\t\t\t\t| FireworksAIErrorResponse\n\t\t);\n\t}\n\n\tif ('choices' in response) {\n\t\treturn {\n\t\t\tid: response.id,\n\t\t\tobject: response.object,\n\t\t\tcreated: response.created,\n\t\t\tmodel: response.model,\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tchoices: response.choices.map(c => ({\n\t\t\t\tindex: c.index,\n\t\t\t\tmessage: {\n\t\t\t\t\trole: c.message.role,\n\t\t\t\t\tcontent: c.message.content,\n\t\t\t\t\ttool_calls: c.message.tool_calls\n\t\t\t\t},\n\t\t\t\tfinish_reason: c.finish_reason\n\t\t\t})),\n\t\t\tusage: {\n\t\t\t\tprompt_tokens: response.usage?.prompt_tokens,\n\t\t\t\tcompletion_tokens: response.usage?.completion_tokens,\n\t\t\t\ttotal_tokens: response.usage?.total_tokens\n\t\t\t}\n\t\t};\n\t}\n\t// Invalid response received from provider\n\treturn generateInvalidProviderResponseError(response, FIREWORKS_AI);\n};\n\nexport const FireworksAIChatCompleteStreamChunkTransform: (\n\tresponse: string\n) => string = responseChunk => {\n\tlet chunk = responseChunk.trim();\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\tif (chunk === '[DONE]') {\n\t\treturn `data: ${chunk}\\n\\n`;\n\t}\n\tconst parsedChunk: FireworksAIStreamChunk = JSON.parse(chunk);\n\treturn (\n\t\t`data: ${JSON.stringify({\n\t\t\tid: parsedChunk.id,\n\t\t\tobject: parsedChunk.object,\n\t\t\tcreated: parsedChunk.created,\n\t\t\tmodel: parsedChunk.model,\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tindex: parsedChunk.choices[0].index,\n\t\t\t\t\tdelta: parsedChunk.choices[0].delta,\n\t\t\t\t\tfinish_reason: parsedChunk.choices[0].finish_reason\n\t\t\t\t}\n\t\t\t],\n\t\t\t...(parsedChunk.usage ? { usage: parsedChunk.usage } : {})\n\t\t})}` + '\\n\\n'\n\t);\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport FireworksAIAPIConfig from './api';\nimport {\n\tFireworksAIChatCompleteConfig,\n\tFireworksAIChatCompleteResponseTransform,\n\tFireworksAIChatCompleteStreamChunkTransform\n} from './chatComplete';\n\nconst FireworksAIConfig: ProviderConfigs = {\n\tchatComplete: FireworksAIChatCompleteConfig,\n\tapi: FireworksAIAPIConfig,\n\tresponseTransforms: {\n\t\tchatComplete: FireworksAIChatCompleteResponseTransform,\n\t\t'stream-chatComplete': FireworksAIChatCompleteStreamChunkTransform\n\t}\n};\n\nexport default FireworksAIConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst PerplexityAIApiConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.perplexity.ai',\n\theaders: (llmApiKey: string) => {\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${llmApiKey}`,\n\t\t\t'content-type': 'application/json',\n\t\t\taccept: 'application/json'\n\t\t};\n\t},\n\tchatComplete: '/chat/completions'\n};\n\nexport default PerplexityAIApiConfig;\n","import { PERPLEXITY } from '@/dev/data/models';\nimport type {\n\tChatCompletionResponse,\n\tErrorResponse,\n\tProviderConfig\n} from 'types/providers';\nimport {\n\tgenerateErrorResponse,\n\tgenerateInvalidProviderResponseError\n} from '../utils';\n\nexport const PerplexityAIChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true,\n\t\tdefault: 'llama-3.1-sonar-small-128k-chat'\n\t},\n\tmessages: {\n\t\tparam: 'messages',\n\t\trequired: true,\n\t\tdefault: []\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\trequired: true,\n\t\tmin: 1\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tmin: 0,\n\t\tmax: 2\n\t},\n\ttop_p: {\n\t\tparam: 'top_p',\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\ttop_k: {\n\t\tparam: 'top_k',\n\t\tmin: 0,\n\t\tmax: 2048\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tpresence_penalty: {\n\t\tparam: 'presence_penalty',\n\t\tmin: -2,\n\t\tmax: 2\n\t},\n\tfrequency_penalty: {\n\t\tparam: 'repetition_penalty'\n\t},\n\tn: {\n\t\tparam: 'n',\n\t\tmax: 1,\n\t\tmin: 1\n\t}\n};\n\ninterface PerplexityAIChatChoice {\n\tmessage: {\n\t\trole: string;\n\t\tcontent: string;\n\t};\n\tdelta: {\n\t\trole: string;\n\t\tcontent: string;\n\t};\n\tindex: number;\n\tfinish_reason: string | null;\n}\n\nexport interface PerplexityAIChatCompleteResponse {\n\tid: string;\n\tmodel: string;\n\tobject: string;\n\tcreated: number;\n\tchoices: PerplexityAIChatChoice[];\n\tusage: {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n}\n\nexport interface PerplexityAIErrorResponse {\n\terror: {\n\t\tmessage: string;\n\t\ttype: string;\n\t\tcode: number;\n\t};\n}\n\nexport interface PerplexityAIChatCompletionStreamChunk {\n\tid: string;\n\tmodel: string;\n\tobject: string;\n\tcreated: number;\n\tusage: {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n\tchoices: PerplexityAIChatChoice[];\n}\n\nexport const PerplexityAIChatCompleteResponseTransform: (\n\tresponse: PerplexityAIChatCompleteResponse | PerplexityAIErrorResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\tif ('error' in response) {\n\t\treturn generateErrorResponse(\n\t\t\t{\n\t\t\t\tmessage: response.error.message,\n\t\t\t\ttype: response.error.type,\n\t\t\t\tparam: null,\n\t\t\t\tcode: response.error.code.toString()\n\t\t\t},\n\t\t\tPERPLEXITY\n\t\t);\n\t}\n\n\tif ('choices' in response) {\n\t\treturn {\n\t\t\tid: response.id,\n\t\t\tobject: response.object,\n\t\t\tcreated: response.created,\n\t\t\tmodel: response.model,\n\t\t\tprovider: PERPLEXITY,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tmessage: {\n\t\t\t\t\t\trole: 'assistant',\n\t\t\t\t\t\tcontent: response.choices[0]?.message.content\n\t\t\t\t\t},\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tlogprobs: null,\n\t\t\t\t\tfinish_reason: ''\n\t\t\t\t}\n\t\t\t],\n\t\t\tusage: {\n\t\t\t\tprompt_tokens: response.usage.prompt_tokens,\n\t\t\t\tcompletion_tokens: response.usage.completion_tokens,\n\t\t\t\ttotal_tokens: response.usage.total_tokens\n\t\t\t}\n\t\t};\n\t}\n\n\treturn generateInvalidProviderResponseError(response, PERPLEXITY);\n};\n\nexport const PerplexityAIChatCompleteStreamChunkTransform: (\n\tresponse: string\n) => string = responseChunk => {\n\tlet chunk = responseChunk.trim();\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\n\tconst parsedChunk: PerplexityAIChatCompletionStreamChunk =\n\t\tJSON.parse(chunk);\n\tlet returnChunk =\n\t\t`data: ${JSON.stringify({\n\t\t\tid: parsedChunk.id,\n\t\t\tobject: parsedChunk.object,\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel: parsedChunk.model,\n\t\t\tprovider: PERPLEXITY,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tdelta: {\n\t\t\t\t\t\trole: parsedChunk.choices[0]?.delta.role,\n\t\t\t\t\t\tcontent: parsedChunk.choices[0]?.delta.content\n\t\t\t\t\t},\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tfinish_reason: parsedChunk.choices[0]?.finish_reason\n\t\t\t\t}\n\t\t\t]\n\t\t})}` + '\\n\\n';\n\n\treturn returnChunk;\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport PerplexityAIApiConfig from './api';\nimport {\n\tPerplexityAIChatCompleteConfig,\n\tPerplexityAIChatCompleteResponseTransform,\n\tPerplexityAIChatCompleteStreamChunkTransform\n} from './chatComplete';\n\nconst PerplexityAIConfig: ProviderConfigs = {\n\tchatComplete: PerplexityAIChatCompleteConfig,\n\tapi: PerplexityAIApiConfig,\n\tresponseTransforms: {\n\t\tchatComplete: PerplexityAIChatCompleteResponseTransform,\n\t\t'stream-chatComplete': PerplexityAIChatCompleteStreamChunkTransform\n\t}\n};\n\nexport default PerplexityAIConfig;\n","import type { ProviderAPIConfig } from 'types/providers';\nconst MistralAIAPIConfig: ProviderAPIConfig = {\n\tbaseURL: 'https://api.mistral.ai/v1',\n\theaders: (llmApiKey: string) => {\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${llmApiKey}`\n\t\t};\n\t},\n\tchatComplete: '/chat/completions'\n};\n\nexport default MistralAIAPIConfig;\n","import { MISTRAL_AI } from '@/dev/data/models';\nimport type {\n\tChatCompletionResponse,\n\tErrorResponse,\n\tProviderConfig\n} from 'types/providers';\nimport {\n\tgenerateErrorResponse,\n\tgenerateInvalidProviderResponseError\n} from '../utils';\n\nexport const MistralAIChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true,\n\t\tdefault: 'mistral-large-latest'\n\t},\n\tmessages: {\n\t\tparam: 'messages',\n\t\tdefault: []\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tdefault: 0.7,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\ttop_p: {\n\t\tparam: 'top_p',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\tdefault: null,\n\t\tmin: 1\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\tseed: {\n\t\tparam: 'random_seed',\n\t\tdefault: null\n\t},\n\tsafe_prompt: {\n\t\tparam: 'safe_prompt',\n\t\tdefault: false\n\t},\n\tsafe_mode: {\n\t\tparam: 'safe_prompt',\n\t\tdefault: false\n\t}\n};\n\ninterface MistralAIChatCompleteResponse extends ChatCompletionResponse {\n\tid: string;\n\tobject: string;\n\tcreated: number;\n\tmodel: string;\n\tusage: {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n}\n\nexport interface MistralAIErrorResponse {\n\tobject: string;\n\tmessage: string;\n\ttype: string;\n\tparam: string | null;\n\tcode: string;\n}\n\ninterface MistralAIStreamChunk {\n\tid: string;\n\tobject: string;\n\tcreated: number;\n\tmodel: string;\n\tchoices: {\n\t\tdelta: {\n\t\t\trole?: string | null;\n\t\t\tcontent?: string;\n\t\t};\n\t\tindex: number;\n\t\tfinish_reason: string | null;\n\t}[];\n}\n\nexport const MistralAIChatCompleteResponseTransform: (\n\tresponse: MistralAIChatCompleteResponse | MistralAIErrorResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\tif ('message' in response && responseStatus !== 200) {\n\t\treturn generateErrorResponse(\n\t\t\t{\n\t\t\t\tmessage: response.message,\n\t\t\t\ttype: response.type,\n\t\t\t\tparam: response.param,\n\t\t\t\tcode: response.code\n\t\t\t},\n\t\t\tMISTRAL_AI\n\t\t);\n\t}\n\n\tif ('choices' in response) {\n\t\treturn {\n\t\t\tid: response.id,\n\t\t\tobject: response.object,\n\t\t\tcreated: response.created,\n\t\t\tmodel: response.model,\n\t\t\tprovider: MISTRAL_AI,\n\t\t\tchoices: response.choices.map(c => ({\n\t\t\t\tindex: c.index,\n\t\t\t\tmessage: {\n\t\t\t\t\trole: c.message.role,\n\t\t\t\t\tcontent: c.message.content\n\t\t\t\t},\n\t\t\t\tfinish_reason: c.finish_reason\n\t\t\t})),\n\t\t\tusage: {\n\t\t\t\tprompt_tokens: response.usage?.prompt_tokens,\n\t\t\t\tcompletion_tokens: response.usage?.completion_tokens,\n\t\t\t\ttotal_tokens: response.usage?.total_tokens\n\t\t\t}\n\t\t};\n\t}\n\n\treturn generateInvalidProviderResponseError(response, MISTRAL_AI);\n};\n\nexport const MistralAIChatCompleteStreamChunkTransform: (\n\tresponse: string\n) => string = responseChunk => {\n\tlet chunk = responseChunk.trim();\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\tif (chunk === '[DONE]') {\n\t\treturn `data: ${chunk}\\n\\n`;\n\t}\n\tconst parsedChunk: MistralAIStreamChunk = JSON.parse(chunk);\n\treturn (\n\t\t`data: ${JSON.stringify({\n\t\t\tid: parsedChunk.id,\n\t\t\tobject: parsedChunk.object,\n\t\t\tcreated: parsedChunk.created,\n\t\t\tmodel: parsedChunk.model,\n\t\t\tprovider: MISTRAL_AI,\n\t\t\tchoices: [\n\t\t\t\t{\n\t\t\t\t\tindex: parsedChunk.choices[0].index,\n\t\t\t\t\tdelta: parsedChunk.choices[0].delta,\n\t\t\t\t\tfinish_reason: parsedChunk.choices[0].finish_reason\n\t\t\t\t}\n\t\t\t]\n\t\t})}` + '\\n\\n'\n\t);\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport MistralAIAPIConfig from './api';\nimport {\n\tMistralAIChatCompleteConfig,\n\tMistralAIChatCompleteResponseTransform,\n\tMistralAIChatCompleteStreamChunkTransform\n} from './chatComplete';\n\nconst MistralAIConfig: ProviderConfigs = {\n\tchatComplete: MistralAIChatCompleteConfig,\n\tapi: MistralAIAPIConfig,\n\tresponseTransforms: {\n\t\tchatComplete: MistralAIChatCompleteResponseTransform,\n\t\t'stream-chatComplete': MistralAIChatCompleteStreamChunkTransform\n\t}\n};\n\nexport default MistralAIConfig;\n","import type { ProviderAPIConfig, ProviderOptions } from 'types/providers';\n\nconst OllamaAPIConfig: ProviderAPIConfig = {\n\theaders: () => {\n\t\treturn {};\n\t},\n\tgetBaseURL: ({ providerOptions }: { providerOptions: ProviderOptions }) => {\n\t\treturn providerOptions.customHost ?? 'http://localhost:11434';\n\t},\n\tchatComplete: '/v1/chat/completions'\n};\n\nexport default OllamaAPIConfig;\n","import type {\n\tChatCompletionResponse,\n\tErrorResponse,\n\tProviderConfig\n} from 'types/providers';\nimport { generateErrorResponse } from '../utils';\nimport { OLLAMA } from '@/dev/data/models';\n\nexport const OllamaChatCompleteConfig: ProviderConfig = {\n\tmodel: {\n\t\tparam: 'model',\n\t\trequired: true,\n\t\tdefault: 'llama2'\n\t},\n\tmessages: {\n\t\tparam: 'messages',\n\t\tdefault: ''\n\t},\n\tfrequency_penalty: {\n\t\tparam: 'frequency_penalty',\n\t\tmin: -2,\n\t\tmax: 2\n\t},\n\tpresence_penalty: {\n\t\tparam: 'presence_penalty',\n\t\tmin: -2,\n\t\tmax: 2\n\t},\n\tresponse_format: {\n\t\tparam: 'response_format'\n\t},\n\tseed: {\n\t\tparam: 'seed'\n\t},\n\tstop: {\n\t\tparam: 'stop'\n\t},\n\tstream: {\n\t\tparam: 'stream',\n\t\tdefault: false\n\t},\n\ttemperature: {\n\t\tparam: 'temperature',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 2\n\t},\n\ttop_p: {\n\t\tparam: 'top_p',\n\t\tdefault: 1,\n\t\tmin: 0,\n\t\tmax: 1\n\t},\n\tmax_tokens: {\n\t\tparam: 'max_tokens',\n\t\tdefault: 100,\n\t\tmin: 0\n\t}\n};\n\nexport interface OllamaChatCompleteResponse\n\textends ChatCompletionResponse,\n\t\tErrorResponse {\n\tsystem_fingerprint: string;\n}\n\nexport interface OllamaStreamChunk {\n\tid: string;\n\tobject: string;\n\tcreated: number;\n\tmodel: string;\n\tsystem_fingerprint: string;\n\tchoices: {\n\t\tdelta: {\n\t\t\trole: string;\n\t\t\tcontent?: string;\n\t\t};\n\t\tindex: number;\n\t\tfinish_reason: string | null;\n\t}[];\n}\n\nexport const OllamaChatCompleteResponseTransform: (\n\tresponse: OllamaChatCompleteResponse,\n\tresponseStatus: number\n) => ChatCompletionResponse | ErrorResponse = (response, responseStatus) => {\n\tif (responseStatus !== 200) {\n\t\treturn generateErrorResponse(\n\t\t\t{\n\t\t\t\tmessage: response.error?.message,\n\t\t\t\ttype: response.error?.type,\n\t\t\t\tparam: null,\n\t\t\t\tcode: null\n\t\t\t},\n\t\t\tOLLAMA\n\t\t);\n\t}\n\n\treturn {\n\t\tid: response.id,\n\t\tobject: response.object,\n\t\tcreated: response.created,\n\t\tmodel: response.model,\n\t\tprovider: OLLAMA,\n\t\tchoices: response.choices,\n\t\tusage: response.usage\n\t};\n};\n\nexport const OllamaChatCompleteStreamChunkTransform: (\n\treponse: string\n) => string = responseChunk => {\n\tlet chunk = responseChunk.trim();\n\tchunk = chunk.replace(/^data: /, '');\n\tchunk = chunk.trim();\n\tif (chunk === '[DONE]') {\n\t\treturn `data: ${chunk}\\n\\n`;\n\t}\n\tconst parsedChunk: OllamaStreamChunk = JSON.parse(chunk);\n\treturn (\n\t\t`data: ${JSON.stringify({\n\t\t\tid: parsedChunk.id,\n\t\t\tobject: parsedChunk.object,\n\t\t\tcreated: parsedChunk.created,\n\t\t\tmodel: parsedChunk.model,\n\t\t\tprovider: OLLAMA,\n\t\t\tchoices: parsedChunk.choices\n\t\t})}` + '\\n\\n'\n\t);\n};\n","import type { ProviderConfigs } from 'types/providers';\nimport OllamaAPIConfig from './api';\nimport {\n\tOllamaChatCompleteConfig,\n\tOllamaChatCompleteResponseTransform,\n\tOllamaChatCompleteStreamChunkTransform\n} from './chatComplete';\n\nconst OllamaConfig: ProviderConfigs = {\n\tapi: OllamaAPIConfig,\n\tchatComplete: OllamaChatCompleteConfig,\n\tresponseTransforms: {\n\t\tchatComplete: OllamaChatCompleteResponseTransform,\n\t\t'stream-chatComplete': OllamaChatCompleteStreamChunkTransform\n\t}\n};\n\nexport default OllamaConfig;\n","import {\n\tANTHROPIC,\n\tCOHERE,\n\tFIREWORKS_AI,\n\tGOOGLE,\n\tGROQ,\n\tMISTRAL_AI,\n\tOLLAMA,\n\tOPEN_AI,\n\tPERPLEXITY,\n\tTOGETHER_AI\n} from '../data/models';\n\nimport type { ProviderConfigs } from 'types/providers';\n\nimport AnthropicConfig from './anthropic';\nimport OpenAIConfig from './openai';\nimport TogetherAIConfig from './together-ai';\nimport GroqConfig from './groq';\nimport GoogleConfig from './google';\nimport CohereConfig from './cohere';\nimport FireworksAIConfig from './fireworks-ai';\nimport PerplexityAIConfig from './perplexity';\nimport MistralAIConfig from './mistral-ai';\nimport OllamaConfig from './ollama';\n\n// Provider Configs\nconst Providers: { [key: string]: ProviderConfigs } = {\n\t[OPEN_AI]: OpenAIConfig,\n\t[ANTHROPIC]: AnthropicConfig,\n\t[TOGETHER_AI]: TogetherAIConfig,\n\t[GROQ]: GroqConfig,\n\t[GOOGLE]: GoogleConfig,\n\t[COHERE]: CohereConfig,\n\t[FIREWORKS_AI]: FireworksAIConfig,\n\t[PERPLEXITY]: PerplexityAIConfig,\n\t[MISTRAL_AI]: MistralAIConfig,\n\t[OLLAMA]: OllamaConfig\n};\n\nexport default Providers;\n","import type { endpointStrings, ModelParams } from 'types/providers';\nimport ProviderConfigs from '../../providers';\n\n/**\n * Helper function to set a nested property in an object.\n *\n * @param obj - The object on which to set the property.\n * @param path - The dot-separated path to the property.\n * @param value - The value to set the property to.\n */\nfunction setNestedProperty(obj: any, path: string, value: any) {\n\tconst parts = path.split('.');\n\tlet current = obj;\n\tfor (let i = 0; i < parts.length - 1; i++) {\n\t\tif (!current[parts[i]]) {\n\t\t\tcurrent[parts[i]] = {};\n\t\t}\n\t\tcurrent = current[parts[i]];\n\t}\n\tcurrent[parts[parts.length - 1]] = value;\n}\n\n/**\n * Transforms the request parameters to match the structure required by the AI provider.\n * It also ensures the values for each parameter are within the minimum and maximum\n * constraints defined in the provider's configuration. If a required parameter is missing,\n * it assigns the default value from the provider's configuration.\n *\n * @param provider - The name of the AI provider.\n * @param params - Langbase model parameters.\n * @param fn - The function to transform  call on the provider. Typically an endpoint, like chatComplete,\n * embed, etc.\n *\n * @returns The transformed parameters according to the provider's format.\n *\n * @throws {Error} If the provider is not supported.\n */\nconst transformToProviderRequest = ({\n\tprovider,\n\tparams,\n\tfn\n}: {\n\tprovider: string;\n\tparams: ModelParams;\n\tfn: endpointStrings;\n}): { [key: string]: any } => {\n\t// Get the configuration for the specified provider\n\tlet providerConfig = ProviderConfigs[provider];\n\n\tif (providerConfig.getConfig) {\n\t\tproviderConfig = providerConfig.getConfig(params)[fn];\n\t} else {\n\t\tproviderConfig = providerConfig[fn];\n\t}\n\n\t// If the provider is not supported, throw an error\n\tif (!providerConfig) {\n\t\tthrow new Error('Unsupported provider');\n\t}\n\n\tconst transformedRequest: { [key: string]: any } = {};\n\n\t// For each parameter in the provider's configuration\n\tfor (const configParam in providerConfig) {\n\t\t// Get the config for this parameter\n\t\tlet paramConfigs = providerConfig[configParam];\n\t\tif (!Array.isArray(paramConfigs)) {\n\t\t\tparamConfigs = [paramConfigs];\n\t\t}\n\n\t\tfor (const paramConfig of paramConfigs) {\n\t\t\t// If the parameter is present in the incoming request body\n\t\t\tif (configParam in params) {\n\t\t\t\t// Get the value for this parameter\n\t\t\t\tlet value = params[configParam as keyof typeof params];\n\n\t\t\t\t// If a transformation is defined for this parameter, apply it\n\t\t\t\tif (paramConfig.transform) {\n\t\t\t\t\tvalue = paramConfig.transform(params);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tvalue === 'default' &&\n\t\t\t\t\tparamConfig &&\n\t\t\t\t\tparamConfig.default !== undefined\n\t\t\t\t) {\n\t\t\t\t\t// Set the transformed parameter to the default value\n\t\t\t\t\tvalue = paramConfig.default;\n\t\t\t\t}\n\n\t\t\t\t// If a minimum is defined for this parameter and the value is less than this, set the value to the minimum\n\t\t\t\t// Also, we should only do this comparison if value is of type 'number'\n\t\t\t\tif (\n\t\t\t\t\ttypeof value === 'number' &&\n\t\t\t\t\tparamConfig &&\n\t\t\t\t\tparamConfig.min !== undefined &&\n\t\t\t\t\tvalue < paramConfig.min\n\t\t\t\t) {\n\t\t\t\t\tvalue = paramConfig.min;\n\t\t\t\t}\n\n\t\t\t\t// If a maximum is defined for this parameter and the value is more than this, set the value to the maximum\n\t\t\t\t// Also, we should only do this comparison if value is of type 'number'\n\t\t\t\telse if (\n\t\t\t\t\ttypeof value === 'number' &&\n\t\t\t\t\tparamConfig &&\n\t\t\t\t\tparamConfig.max !== undefined &&\n\t\t\t\t\tvalue > paramConfig.max\n\t\t\t\t) {\n\t\t\t\t\tvalue = paramConfig.max;\n\t\t\t\t}\n\n\t\t\t\t// Set the transformed parameter to the validated value\n\t\t\t\tsetNestedProperty(\n\t\t\t\t\ttransformedRequest,\n\t\t\t\t\tparamConfig?.param as string,\n\t\t\t\t\tvalue\n\t\t\t\t);\n\t\t\t}\n\t\t\t// If the parameter is not present in the incoming request body but is required, set it to the default value\n\t\t\telse if (\n\t\t\t\tparamConfig &&\n\t\t\t\tparamConfig.required &&\n\t\t\t\tparamConfig.default !== undefined\n\t\t\t) {\n\t\t\t\t// Set the transformed parameter to the default value\n\t\t\t\tsetNestedProperty(\n\t\t\t\t\ttransformedRequest,\n\t\t\t\t\tparamConfig.param,\n\t\t\t\t\tparamConfig.default\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn transformedRequest;\n};\n\nexport default transformToProviderRequest;\n","import { REQUEST_TIMEOUT_STATUS_CODE } from '../../data/globals';\nimport {\n\tAZURE_OPEN_AI,\n\tBEDROCK,\n\tCOHERE,\n\tDEEPINFRA,\n\tGOOGLE,\n\tPERPLEXITY\n} from '../../data/models';\nimport { dlog } from '../dlog';\n\n/**\n * Handles non-streaming responses. Applies the appropriate response transformer to the response.\n * Returns a mapped response in OpenAI format\n * @param {Response} response - The HTTP response recieved from LLM.\n * @param {Function | undefined} responseTransformer - The response transform function given in provider/index.ts.\n * @returns {Promise<any>} - A promise that resolves to the processed response.\n */\n\nexport async function handleNonStreamingMode({\n\tresponse,\n\tresponseTransformer\n}: {\n\tresponse: Response;\n\tresponseTransformer: Function | undefined;\n}): Promise<any> {\n\t// 408 is thrown whenever a request takes more than request_timeout to respond.\n\t// In that case, response thrown by gateway is already in OpenAI format.\n\t// So no need to transform it again.\n\tif (response.status === REQUEST_TIMEOUT_STATUS_CODE) {\n\t\treturn response;\n\t}\n\tlet responseBodyJson = await response.json();\n\n\tdlog('original provider response', responseBodyJson);\n\n\tif (responseTransformer) {\n\t\tresponseBodyJson = responseTransformer(\n\t\t\tresponseBodyJson,\n\t\t\tresponse.status,\n\t\t\tresponse.headers\n\t\t);\n\t}\n\n\treturn responseBodyJson;\n}\n\n/**\n * Handles the streaming mode for a response.\n *\n * @param response - The response object.\n * @param provider - The provider string.\n * @param responseTransformer - The response transformer function.\n * @param requestURL - The request URL string.\n * @returns A promise that resolves to the transformed response or the readable stream.\n * @throws An error if the response format is invalid and the body is not found.\n */\nexport async function handleStreamingMode(\n\tresponse: Response,\n\tprovider: string,\n\tresponseTransformer: Function | undefined,\n\trequestURL: string\n): Promise<any> {\n\tconst splitPattern = getStreamModeSplitPattern(provider, requestURL);\n\tconst fallbackChunkId = Date.now().toString();\n\n\tif (!response.body) {\n\t\tthrow new Error('Response format is invalid. Body not found');\n\t}\n\tconst { readable, writable } = new TransformStream();\n\tconst writer = writable.getWriter();\n\tconst reader = response.body.getReader();\n\tconst isSleepTimeRequired = provider === AZURE_OPEN_AI ? true : false;\n\tconst encoder = new TextEncoder();\n\n\t(async () => {\n\t\tfor await (const chunk of readStream(\n\t\t\treader,\n\t\t\tsplitPattern,\n\t\t\tresponseTransformer,\n\t\t\tisSleepTimeRequired,\n\t\t\tfallbackChunkId\n\t\t)) {\n\t\t\tawait writer.write(encoder.encode(chunk));\n\t\t}\n\t\twriter.close();\n\t})();\n\n\t// Convert GEMINI/COHERE json stream to text/event-stream\n\tif ([GOOGLE, COHERE, BEDROCK].includes(provider) && responseTransformer) {\n\t\treturn readable;\n\t\t// return new Response(readable, {\n\t\t// \t...response,\n\t\t// \theaders: new Headers({\n\t\t// \t\t...Object.fromEntries(response.headers),\n\t\t// \t\t'content-type': 'text/event-stream',\n\t\t// \t}),\n\t\t// });\n\t}\n\n\treturn readable;\n}\n\n/**\n * Returns the split pattern based on the provider and request URL.\n * @param provider - The provider name.\n * @param requestURL - The request endpoint URL.\n * @returns The split pattern.\n */\nexport const getStreamModeSplitPattern = (\n\tprovider: string,\n\trequestURL: string\n) => {\n\tlet splitPattern = '\\n\\n';\n\tif (provider === COHERE) {\n\t\tsplitPattern = '\\n';\n\t}\n\tif (provider === GOOGLE) {\n\t\tsplitPattern = '\\r\\n';\n\t}\n\n\tif (provider === PERPLEXITY) {\n\t\tsplitPattern = '\\r\\n\\r\\n';\n\t}\n\n\tif (provider === DEEPINFRA) {\n\t\tsplitPattern = '\\r\\n\\r\\n';\n\t}\n\n\treturn splitPattern;\n};\n\n/**\n * Asynchronously reads a stream and yields chunks of data based on a split pattern.\n * @param reader The ReadableStreamDefaultReader to read from.\n * @param splitPattern The pattern used to split the chunks of data.\n * @param transformFunction An optional function to transform each chunk of data.\n * @param isSleepTimeRequired A boolean indicating whether sleep time is required between chunks.\n * @param fallbackChunkId The ID to use for fallback chunks.\n * @yields The chunks of data read from the stream.\n */\nexport async function* readStream(\n\treader: ReadableStreamDefaultReader,\n\tsplitPattern: string,\n\ttransformFunction: Function | undefined,\n\tisSleepTimeRequired: boolean,\n\tfallbackChunkId: string\n) {\n\tlet buffer = '';\n\tlet decoder = new TextDecoder();\n\tlet isFirstChunk = true;\n\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) {\n\t\t\tif (buffer.length > 0) {\n\t\t\t\tif (transformFunction) {\n\t\t\t\t\tyield transformFunction(buffer, fallbackChunkId);\n\t\t\t\t} else {\n\t\t\t\t\tyield buffer;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t// keep buffering until we have a complete chunk\n\n\t\twhile (buffer.split(splitPattern).length > 1) {\n\t\t\tlet parts = buffer.split(splitPattern);\n\t\t\tlet lastPart = parts.pop() ?? ''; // remove the last part from the array and keep it in buffer\n\t\t\tfor (let part of parts) {\n\t\t\t\t// Some providers send ping event which can be ignored during parsing\n\n\t\t\t\tif (part.length > 0) {\n\t\t\t\t\tif (isFirstChunk) {\n\t\t\t\t\t\tisFirstChunk = false;\n\t\t\t\t\t\tawait new Promise(resolve => setTimeout(resolve, 25));\n\t\t\t\t\t} else if (isSleepTimeRequired) {\n\t\t\t\t\t\tawait new Promise(resolve => setTimeout(resolve, 1));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (transformFunction) {\n\t\t\t\t\t\tconst transformedChunk = transformFunction(\n\t\t\t\t\t\t\tpart,\n\t\t\t\t\t\t\tfallbackChunkId\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (transformedChunk !== undefined) {\n\t\t\t\t\t\t\tyield transformedChunk;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tyield part + splitPattern;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuffer = lastPart; // keep the last part (after the last '\\n\\n') in buffer\n\t\t}\n\t}\n}\n\n// export async function handleJSONToStreamResponse(response: Response, provider: string, responseTransformerFunction: Function): Promise<Response> {\n// \tconst { readable, writable } = new TransformStream();\n// \tconst writer = writable.getWriter();\n// \tconst encoder = new TextEncoder();\n// \tconst responseJSON: OpenAIChatCompleteResponse = await response.clone().json();\n// \tconst streamChunkArray = responseTransformerFunction(responseJSON, provider);\n\n// \t(async () => {\n// \t\tfor (const chunk of streamChunkArray) {\n// \t\t\tawait writer.write(encoder.encode(chunk));\n// \t\t}\n// \t\twriter.close();\n// \t})();\n\n// \treturn new Response(readable, {\n// \t\theaders: new Headers({\n// \t\t\t...Object.fromEntries(response.headers),\n// \t\t\t'content-type': CONTENT_TYPES.EVENT_STREAM\n// \t\t})\n// \t});\n// }\n\n// function readUInt32BE(buffer: Uint8Array, offset: number) {\n// \treturn (\n// \t\t(buffer[offset] << 24) |\n// \t\t(buffer[offset + 1] << 16) |\n// \t\t(buffer[offset + 2] << 8) |\n// \t\tbuffer[offset + 3]\n// \t) >>> 0; // Ensure the result is an unsigned integer\n// }\n\n// function getPayloadFromAWSChunk(chunk: Uint8Array): string {\n// \tconst decoder = new TextDecoder();\n// \tconst chunkLength = readUInt32BE(chunk, 0);\n// \tconst headersLength = readUInt32BE(chunk, 4);\n\n// \t// prelude 8 + Prelude crc 4 = 12\n// \tconst headersEnd = 12 + headersLength;\n\n// \tconst payloadLength = chunkLength - headersEnd - 4; // Subtracting 4 for the message crc\n// \tconst payload = chunk.slice(headersEnd, headersEnd + payloadLength);\n// \treturn decoder.decode(payload);\n// }\n\n// function concatenateUint8Arrays(a: Uint8Array, b: Uint8Array): Uint8Array {\n// \tconst result = new Uint8Array(a.length + b.length);\n// \tresult.set(a, 0); // Copy contents of array 'a' into 'result' starting at index 0\n// \tresult.set(b, a.length); // Copy contents of array 'b' into 'result' starting at index 'a.length'\n// \treturn result;\n// }\n\n// export async function* readAWSStream(reader: ReadableStreamDefaultReader, transformFunction: Function | undefined, fallbackChunkId: string) {\n// \tlet buffer = new Uint8Array();\n// \tlet expectedLength = 0;\n// \twhile (true) {\n// \t\tconst { done, value } = await reader.read();\n// \t\tif (done) {\n// \t\t\tif (buffer.length) {\n// \t\t\t\texpectedLength = readUInt32BE(buffer, 0);\n// \t\t\t\twhile (buffer.length >= expectedLength && buffer.length !== 0) {\n// \t\t\t\t\tconst data = buffer.subarray(0, expectedLength);\n// \t\t\t\t\tbuffer = buffer.subarray(expectedLength);\n// \t\t\t\t\texpectedLength = readUInt32BE(buffer, 0);\n// \t\t\t\t\tconst payload = Buffer.from(JSON.parse(getPayloadFromAWSChunk(data)).bytes, 'base64').toString();\n// \t\t\t\t\tif (transformFunction) {\n// \t\t\t\t\t\tconst transformedChunk = transformFunction(payload, fallbackChunkId);\n// \t\t\t\t\t\tif (Array.isArray(transformedChunk)) {\n// \t\t\t\t\t\t\tfor (var item of transformedChunk) {\n// \t\t\t\t\t\t\t\tyield item;\n// \t\t\t\t\t\t\t}\n// \t\t\t\t\t\t} else {\n// \t\t\t\t\t\t\tyield transformedChunk;\n// \t\t\t\t\t\t}\n// \t\t\t\t\t} else {\n// \t\t\t\t\t\tyield data;\n// \t\t\t\t\t}\n// \t\t\t\t}\n// \t\t\t}\n// \t\t\tbreak;\n// \t\t}\n\n// \t\tif (expectedLength === 0) {\n// \t\t\texpectedLength = readUInt32BE(value, 0);\n// \t\t}\n\n// \t\tbuffer = concatenateUint8Arrays(buffer, value);\n\n// \t\twhile (buffer.length >= expectedLength && buffer.length !== 0) {\n// \t\t\tconst data = buffer.subarray(0, expectedLength);\n// \t\t\tbuffer = buffer.subarray(expectedLength);\n\n// \t\t\texpectedLength = readUInt32BE(buffer, 0);\n// \t\t\tconst payload = Buffer.from(JSON.parse(getPayloadFromAWSChunk(data)).bytes, 'base64').toString();\n\n// \t\t\tif (transformFunction) {\n// \t\t\t\tconst transformedChunk = transformFunction(payload, fallbackChunkId);\n// \t\t\t\tif (Array.isArray(transformedChunk)) {\n// \t\t\t\t\tfor (var item of transformedChunk) {\n// \t\t\t\t\t\tyield item;\n// \t\t\t\t\t}\n// \t\t\t\t} else {\n// \t\t\t\t\tyield transformedChunk;\n// \t\t\t\t}\n// \t\t\t} else {\n// \t\t\t\tyield data;\n// \t\t\t}\n// \t\t}\n// \t}\n// }\n\n// export async function handleTextResponse(response: Response, responseTransformer: Function | undefined) {\n// \tconst text = await response.text();\n\n// \tif (responseTransformer) {\n// \t\tconst transformedText = responseTransformer({ \"html-message\": text }, response.status);\n// \t\treturn new Response(JSON.stringify(transformedText), {\n// \t\t\t...response,\n// \t\t\tstatus: response.status,\n// \t\t\theaders: new Headers({\n// \t\t\t\t...Object.fromEntries(response.headers),\n// \t\t\t\t'content-type': \"application/json\"\n// \t\t\t})\n// \t\t});\n// \t}\n\n// \treturn new Response(text, response);\n// }\n\n// export async function handleAudioResponse(response: Response) {\n// \treturn new Response(response.body, response);\n// }\n\n// export async function handleOctetStreamResponse(response: Response) {\n// \treturn new Response(response.body, response);\n// }\n\n// export async function handleImageResponse(response: Response) {\n// \treturn new Response(response.body, response);\n// }\n","import type { ModelParams } from '@/types/providers';\nimport {\n\thandleNonStreamingMode,\n\thandleStreamingMode\n} from './response-handler-utils';\nimport Providers from '@/dev/providers';\nimport { dlog } from '../dlog';\n\n/**\n * Handles various types of responses based on the specified parameters\n * and returns a mapped response in OpenAI format\n * @param {Response} response - The HTTP response recieved from LLM.\n * @param {boolean} streamingMode - Indicates whether streaming mode is enabled.\n * @param {string} provider - The provider name string.\n * @param {string | undefined} responseTransformer - The response transform name given in provider/index.ts. Usually is LLM endpoint. For example GoogleChatCompleteResponseTransform.\n * @param {string} requestURL - The URL of the original LLM request.\n * @returns {Promise<any>} - A promise that resolves to the processed response.\n */\nexport function handleProviderResponse({\n\tresponse,\n\tstreamingMode,\n\tprovider,\n\tresponseTransformer,\n\trequestURL,\n\tmodelParams\n}: {\n\tresponse: Response;\n\tstreamingMode: boolean;\n\tprovider: string;\n\tresponseTransformer: string | undefined;\n\trequestURL: string;\n\tmodelParams: ModelParams;\n}): Promise<any> {\n\ttry {\n\t\tlet responseTransformerFunction: Function | undefined;\n\t\t// const responseContentType = response.headers?.get(\"content-type\");\n\n\t\tconst providerConfig = Providers[provider];\n\n\t\t// Get all response transformers of the provider\n\t\tlet providerTransformers = Providers[provider]?.responseTransforms;\n\t\tif (providerConfig.getConfig) {\n\t\t\tproviderTransformers =\n\t\t\t\tproviderConfig.getConfig(modelParams).responseTransforms;\n\t\t}\n\n\t\t// Extract the relevant response transformer\n\t\tif (responseTransformer && streamingMode && response.status === 200) {\n\t\t\tresponseTransformerFunction =\n\t\t\t\tproviderTransformers?.[`stream-${responseTransformer}`];\n\t\t} else if (responseTransformer) {\n\t\t\tresponseTransformerFunction =\n\t\t\t\tproviderTransformers?.[responseTransformer];\n\t\t}\n\n\t\tdlog(\n\t\t\t'transforming provider response using',\n\t\t\tresponseTransformerFunction\n\t\t\t\t? `${provider}${responseTransformer}ResponseTransform`\n\t\t\t\t: 'No transformer found'\n\t\t);\n\n\t\t// STREAMING: Convert the stream into OpenAI Stream.\n\t\tif (streamingMode && response.status === 200) {\n\t\t\treturn handleStreamingMode(\n\t\t\t\tresponse,\n\t\t\t\tprovider,\n\t\t\t\tresponseTransformerFunction,\n\t\t\t\trequestURL\n\t\t\t);\n\t\t}\n\t\t// NON-STREAMING: Apply the appropriate response transformer to the response.\n\t\treturn handleNonStreamingMode({\n\t\t\tresponse,\n\t\t\tresponseTransformer: responseTransformerFunction\n\t\t});\n\t} catch (error) {\n\t\t// Handle the error here, log it, or throw a new error\n\t\tconsole.error('An error occurred in responseHandler:', error);\n\t\tthrow error;\n\t}\n}\n","/**\n * Constructs the request options for the provider API call.\n *\n * @param {any} providerConfigMappedHeaders - Headers mapped according to the provider\n * @param {string} method - The HTTP method for the request. Currently using only POST.\n * @returns {RequestInit} - The fetch options for the request.\n */\nexport function constructRequest({\n\tproviderConfigMappedHeaders,\n\tmethod = 'POST',\n}: {\n\tproviderConfigMappedHeaders: any;\n\tmethod: string;\n}) {\n\tlet baseHeaders: any = {\n\t\t'content-type': 'application/json',\n\t};\n\n\tlet headers: Record<string, string> = {\n\t\t...providerConfigMappedHeaders,\n\t};\n\n\t// Add any extra headers, forward, passthrough headers here\n\theaders = {...baseHeaders, ...headers};\n\n\tlet fetchOptions: RequestInit = {\n\t\tmethod,\n\t\theaders,\n\t};\n\n\t// If the method is GET, delete the content-type header\n\tif (method === 'GET' && fetchOptions.headers) {\n\t\tlet headers = fetchOptions.headers as Record<string, unknown>;\n\t\tdelete headers['content-type'];\n\t}\n\n\treturn fetchOptions;\n}\n","import { handleProviderResponse } from './provider-response-handler';\nimport Providers from '@/dev/providers';\nimport { constructRequest } from './construct-provider-request';\nimport { ANTHROPIC, FIREWORKS_AI, GOOGLE, OLLAMA } from '@/dev/data/models';\nimport { ApiError } from '@/dev/hono/errors';\nimport { dlog } from '../dlog';\nimport type {\n\tendpointStrings,\n\tModelParams,\n\tProviderAPIConfig,\n\tProviderOptions\n} from 'types/providers';\n\n/**\n * Makes a POST request to a provider and returns the response.\n * The POST request is constructed using the provider, llmApiKey, and inputParams parameters.\n * The endpoint parameter is the type of request being made (e.g., \"complete\", \"chatComplete\").\n * Currently only handles non-streamed responses. We handle streaming with provider sdks.\n *\n * @param {ProviderOptions} providerOptions - The provider options.\n * @param {inputParams} inputParams - The langbase model params.\n * @param {string} endpoint - The endpoint of the provider, eg chatComplete, embed, etc.\n * @param {transformedRequestParams} transformedRequestParams - The transformed params in the provider's format.\n * @returns {Promise<any>} - The response from the POST request.\n * @throws Will throw an error if the response is not ok or if all retry attempts fail.\n */\nexport async function handleProviderRequest({\n\tproviderOptions,\n\tinputParams,\n\tendpoint,\n\ttransformedRequestParams\n}: {\n\tproviderOptions: ProviderOptions;\n\tinputParams: ModelParams;\n\tendpoint: endpointStrings;\n\ttransformedRequestParams: { [key: string]: any };\n}): Promise<any> {\n\tconst params: ModelParams = { ...inputParams };\n\n\tconst isStreamingMode = params.stream ? true : false;\n\n\tconst provider: string = providerOptions.provider ?? '';\n\t// Get API request info for the provider\n\tconst apiConfig: ProviderAPIConfig = Providers[provider].api;\n\n\tlet baseUrl: string = '',\n\t\tproviderEndpoint: string,\n\t\tfetchOptions;\n\n\t/**\n\t * Handling providers with different base URLs and endpoints.\n\t * Maps to following functions in providers/provider/api.ts\n\t * headers()\n\t * getEndpoint()\n\t */\n\n\t// Anthropic\n\tif (provider === ANTHROPIC && apiConfig.baseURL) {\n\t\tconst providerConfigMappedHeaders = apiConfig.headers({\n\t\t\tllmApiKey: providerOptions.llmApiKey,\n\t\t\tendpoint\n\t\t});\n\n\t\tfetchOptions = constructRequest({\n\t\t\tproviderConfigMappedHeaders,\n\t\t\tmethod: 'POST'\n\t\t});\n\t\tbaseUrl = baseUrl || apiConfig.baseURL;\n\t\tproviderEndpoint = apiConfig[endpoint] || '';\n\t}\n\t// Google\n\telse if (\n\t\tprovider === GOOGLE &&\n\t\tapiConfig.baseURL &&\n\t\tapiConfig.getEndpoint\n\t) {\n\t\tfetchOptions = constructRequest({\n\t\t\tproviderConfigMappedHeaders: apiConfig.headers(),\n\t\t\tmethod: 'POST'\n\t\t});\n\t\tbaseUrl = baseUrl || apiConfig.baseURL;\n\t\tproviderEndpoint = apiConfig.getEndpoint({\n\t\t\tendpoint,\n\t\t\tllmApiKey: providerOptions.llmApiKey,\n\t\t\tmodel: transformedRequestParams.model,\n\t\t\tstream: params.stream\n\t\t});\n\t}\n\t// Fireworks AI\n\telse if (\n\t\tprovider === FIREWORKS_AI &&\n\t\tapiConfig.baseURL &&\n\t\tapiConfig.getEndpoint\n\t) {\n\t\tfetchOptions = constructRequest({\n\t\t\tproviderConfigMappedHeaders: apiConfig.headers({\n\t\t\t\tllmApiKey: providerOptions.llmApiKey\n\t\t\t}),\n\t\t\tmethod: 'POST'\n\t\t});\n\t\tbaseUrl = baseUrl || apiConfig.baseURL;\n\t\tproviderEndpoint = apiConfig.getEndpoint({ endpoint });\n\t}\n\t// Ollama\n\telse if (provider === OLLAMA && apiConfig.getBaseURL) {\n\t\tfetchOptions = constructRequest({\n\t\t\tproviderConfigMappedHeaders: apiConfig.headers(),\n\t\t\tmethod: 'POST'\n\t\t});\n\t\tbaseUrl = apiConfig.getBaseURL({ providerOptions });\n\t\tproviderEndpoint = apiConfig[endpoint] || '';\n\n\t\tdlog('Ollama request', {\n\t\t\tbaseUrl,\n\t\t\tproviderEndpoint,\n\t\t\ttransformedRequestParams\n\t\t});\n\t}\n\t// Other providers\n\telse {\n\t\tfetchOptions = constructRequest({\n\t\t\tproviderConfigMappedHeaders: apiConfig.headers(\n\t\t\t\tproviderOptions.llmApiKey\n\t\t\t),\n\t\t\tmethod: 'POST'\n\t\t});\n\n\t\t// We can support custom base urls and endpoints here\n\t\tbaseUrl = baseUrl || apiConfig.baseURL || '';\n\t\tproviderEndpoint = apiConfig[endpoint] || '';\n\t}\n\n\t// Construct the request URL and body\n\tconst url = `${baseUrl}${providerEndpoint}`;\n\tfetchOptions.body = JSON.stringify(transformedRequestParams);\n\n\tlet response;\n\n\ttry {\n\t\tresponse = (await fetch(url, fetchOptions)) as unknown as Response & {\n\t\t\twebSocket?: any;\n\t\t\tcf?: any;\n\t\t};\n\n\t\t// Transform provider's response into OpenAI format\n\t\tconst transformedResponse = await handleProviderResponse({\n\t\t\tresponse,\n\t\t\tstreamingMode: isStreamingMode,\n\t\t\tprovider,\n\t\t\tresponseTransformer: endpoint,\n\t\t\trequestURL: url,\n\t\t\tmodelParams: params\n\t\t});\n\n\t\tdlog('Transformed provider response', transformedResponse);\n\n\t\t// Handle LLM errors.\n\t\tif (!response.ok) {\n\t\t\tthrow transformedResponse.error;\n\t\t}\n\n\t\treturn transformedResponse;\n\t} catch (error: any) {\n\t\tconsole.error(error);\n\t\tthrow new ApiError({\n\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: error.message\n\t\t});\n\t}\n}\n","import { jsonModeModels } from '@/dev/data/models';\n\nexport function isJsonModeOn({\n\tcurrentModel,\n\tjsonMode\n}: {\n\tcurrentModel: string;\n\tjsonMode: boolean;\n}) {\n\tconst modelHasJsonMode = jsonModeModels.includes(currentModel);\n\tconst jsonModeOn = jsonMode;\n\tif (jsonModeOn && modelHasJsonMode) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n","import type { ModelParams } from 'types/providers';\nimport { ApiError } from '../hono/errors';\nimport { dlog } from '../utils/dlog';\nimport { isJsonModeOn } from '../utils/is-json-mode';\nimport type { Pipe } from 'types/pipe';\n\nexport function handleLlmError({\n\terror,\n\tprovider\n}: {\n\terror: any;\n\tprovider: string;\n}) {\n\tdlog(`Error call-${provider}.ts:`, error);\n\tthrow new ApiError({\n\t\tcode: 'BAD_REQUEST',\n\t\tmessage: `Error from ${provider}: ${error.message}`\n\t});\n}\n\nexport function applyJsonModeIfEnabled(modelParams: ModelParams, pipe: Pipe) {\n\tconst hasJsonMode = isJsonModeOn({\n\t\tcurrentModel: modelParams.model as string,\n\t\tjsonMode: pipe.json || false\n\t});\n\n\tif (hasJsonMode) {\n\t\tmodelParams.response_format = { type: 'json_object' };\n\t}\n}\n\nexport function applyJsonModeIfEnabledForGoogle(\n\ttransformedRequestParams: any,\n\tpipe: Pipe\n) {\n\tconst currentModel = pipe.model.split(':')[1];\n\tconst hasJsonMode = isJsonModeOn({\n\t\tcurrentModel,\n\t\tjsonMode: pipe.json || false\n\t});\n\n\tif (hasJsonMode) {\n\t\ttransformedRequestParams.generationConfig = {\n\t\t\t...transformedRequestParams.generationConfig,\n\t\t\tresponseMimeType: 'application/json'\n\t\t};\n\t}\n}\n","import {\n\tANTHROPIC,\n\tCOHERE,\n\tFIREWORKS_AI,\n\tGOOGLE,\n\tGROQ,\n\tOLLAMA,\n\tOPEN_AI,\n\tPERPLEXITY,\n\tTOGETHER_AI,\n\tX_AI\n} from '@/data/models';\n\ntype Provider =\n\t| typeof OPEN_AI\n\t| typeof ANTHROPIC\n\t| typeof TOGETHER_AI\n\t| typeof GOOGLE\n\t| typeof GROQ\n\t| typeof COHERE\n\t| typeof FIREWORKS_AI\n\t| typeof PERPLEXITY;\n\n/**\n * Retrieves the provider based on the given provider string.\n *\n * @param providerString - The provider string.\n * @returns The corresponding provider object.\n * @throws Error if the provider is unknown.\n */\nexport function getProvider(providerString: string): Provider {\n\tconst providerMap: { [key: string]: Provider } = {\n\t\topenai: OPEN_AI,\n\t\tanthropic: ANTHROPIC,\n\t\ttogether: TOGETHER_AI,\n\t\tgoogle: GOOGLE,\n\t\tgroq: GROQ,\n\t\tcohere: COHERE,\n\t\tfireworks: FIREWORKS_AI,\n\t\tperplexity: PERPLEXITY,\n\t\tollama: OLLAMA,\n\t\txai: X_AI\n\t};\n\n\tconst provider = providerMap[providerString.toLowerCase()];\n\tif (!provider) {\n\t\tthrow new Error(`Unknown provider: ${providerString}`);\n\t}\n\treturn provider;\n}\n","import { modelsByProvider } from '@/data/models';\n\nexport function hasToolSupport({\n\tprovider,\n\tmodelName\n}: {\n\tmodelName: string;\n\tprovider: string;\n}) {\n\tconst toolSupportedModels = modelsByProvider[provider].filter(\n\t\tmodel => model.toolSupport\n\t);\n\tconst hasToolCallSupport = toolSupportedModels\n\t\t.flatMap(model => model.id)\n\t\t.includes(modelName);\n\n\treturn hasToolCallSupport;\n}\n\nexport function getSupportedToolSettings({\n\tprovider,\n\tmodelName\n}: {\n\tmodelName: string;\n\tprovider: string;\n}) {\n\tconst toolSupportedModels = modelsByProvider[provider].filter(\n\t\tmodel => model.toolSupport\n\t);\n\tconst providerModel = toolSupportedModels.find(\n\t\tmodel => model.id === modelName\n\t);\n\n\tif (!providerModel) {\n\t\treturn {\n\t\t\thasParallelToolCallSupport: false,\n\t\t\thasToolChoiceSupport: false\n\t\t};\n\t}\n\n\treturn {\n\t\thasToolChoiceSupport: providerModel.toolSupport?.toolChoice,\n\t\thasParallelToolCallSupport: providerModel.toolSupport?.parallelToolCalls\n\t};\n}\n","import type { Pipe, ToolCall } from 'types/pipe';\nimport { getProvider } from './get-provider';\nimport { getSupportedToolSettings, hasToolSupport } from './has-tool-support';\nimport type { ModelParams } from 'types/providers';\nimport type { PipeTool } from 'types/tools';\n\nexport function addToolsToParams(\n\tmodelParams: ModelParams,\n\tpipe: Pipe,\n\tparamsTools: PipeTool[] | undefined\n) {\n\tconst pipeTools = pipe.tools as unknown as string[];\n\tconst hasParamsTools = paramsTools && paramsTools.length > 0;\n\n\t// 1. If no tools are provided, return the modelParams as is\n\tif (!hasParamsTools && !pipeTools.length) return modelParams;\n\n\tconst [providerString, modelName] = pipe.model.split(':');\n\tconst provider = getProvider(providerString);\n\n\t// Check if the model supports tool calls\n\tconst hasToolCallSupport = hasToolSupport({\n\t\tmodelName,\n\t\tprovider\n\t});\n\n\t// 2. If the model does not support tool calls, return the modelParams as is\n\tif (!hasToolCallSupport) return modelParams;\n\n\t// If tools are provided in request param, prioritize and use them\n\tif (hasParamsTools) {\n\t\tmodelParams.tools = paramsTools as ToolCall[];\n\t}\n\n\t// If tools are not provided in request param, use the tools from the pipe config\n\tif (!hasParamsTools && pipeTools.length) {\n\t\tmodelParams.tools = pipe.tools as ToolCall[];\n\t}\n\n\tconst { hasParallelToolCallSupport, hasToolChoiceSupport } =\n\t\tgetSupportedToolSettings({\n\t\t\tmodelName,\n\t\t\tprovider\n\t\t});\n\n\tif (hasParallelToolCallSupport) {\n\t\tmodelParams.parallel_tool_calls = pipe.parallel_tool_calls;\n\t}\n\n\tif (hasToolChoiceSupport) {\n\t\tmodelParams.tool_choice = pipe.tool_choice;\n\t}\n}\n","import { dlog } from '../utils/dlog';\nimport transformToProviderRequest from '../utils/provider-handlers/transfrom-to-provider-request';\nimport { handleProviderRequest } from '../utils/provider-handlers/provider-request-handler';\nimport { ANTHROPIC } from '../data/models';\nimport { handleLlmError } from './utils';\nimport type { ModelParams } from 'types/providers';\nimport type { Message, Pipe } from 'types/pipe';\nimport { addToolsToParams } from '../utils/add-tools-to-params';\nimport type { PipeTool } from 'types/tools';\n\nexport async function callAnthropic({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream,\n\tparamsTools\n}: {\n\tpipe: Pipe;\n\tllmApiKey: string;\n\tstream: boolean;\n\tmessages: Message[];\n\tparamsTools: PipeTool[] | undefined;\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\t\taddToolsToParams(modelParams, pipe, paramsTools);\n\n\t\t// Transform params according to provider's format\n\t\tconst transformedRequestParams = transformToProviderRequest({\n\t\t\tprovider: ANTHROPIC,\n\t\t\tparams: modelParams,\n\t\t\tfn: 'chatComplete'\n\t\t});\n\t\tdlog('Anthropic request params', transformedRequestParams);\n\n\t\tconst providerOptions = { provider: ANTHROPIC, llmApiKey };\n\n\t\treturn await handleProviderRequest({\n\t\t\tproviderOptions,\n\t\t\tinputParams: modelParams,\n\t\t\tendpoint: 'chatComplete',\n\t\t\ttransformedRequestParams\n\t\t});\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: ANTHROPIC });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import { handleProviderRequest } from '../utils/provider-handlers/provider-request-handler';\nimport transformToProviderRequest from '../utils/provider-handlers/transfrom-to-provider-request';\nimport { dlog } from '../utils/dlog';\nimport { COHERE } from '../data/models';\nimport { handleLlmError } from './utils';\nimport type { ModelParams } from 'types/providers';\nimport type { Message, Pipe } from 'types/pipe';\n\nexport async function callCohere({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream\n}: {\n\tpipe: Pipe;\n\tllmApiKey: string;\n\tmessages: Message[];\n\tstream: boolean;\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\n\t\t// Transform params according to provider's format\n\t\tconst transformedRequestParams = transformToProviderRequest({\n\t\t\tprovider: COHERE,\n\t\t\tparams: modelParams,\n\t\t\tfn: 'chatComplete'\n\t\t});\n\t\tdlog('Cohere request params', transformedRequestParams);\n\n\t\tconst providerOptions = { provider: COHERE, llmApiKey };\n\n\t\treturn await handleProviderRequest({\n\t\t\tproviderOptions,\n\t\t\tinputParams: modelParams,\n\t\t\tendpoint: 'chatComplete',\n\t\t\ttransformedRequestParams\n\t\t});\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: COHERE });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import { dlog } from '../utils/dlog';\nimport transformToProviderRequest from '../utils/provider-handlers/transfrom-to-provider-request';\nimport { handleProviderRequest } from '../utils/provider-handlers/provider-request-handler';\nimport { FIREWORKS_AI } from '../data/models';\n\nimport { handleLlmError } from './utils';\nimport type { ModelParams } from 'types/providers';\nimport type { Message, Pipe } from 'types/pipe';\n\nexport async function callFireworks({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream\n}: {\n\tpipe: Pipe;\n\tllmApiKey: string;\n\tstream: boolean;\n\tmessages: Message[];\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\n\t\t// Transform params according to provider's format\n\t\tconst transformedRequestParams = transformToProviderRequest({\n\t\t\tprovider: FIREWORKS_AI,\n\t\t\tparams: modelParams,\n\t\t\tfn: 'chatComplete'\n\t\t});\n\t\tdlog('Fireworks request params', transformedRequestParams);\n\n\t\t// Fireworks llama-3.1 405b behaves weirdly with stop value. Bug on their side. Omitting it.\n\t\tif (modelParams?.model === 'llama-v3p1-405b-instruct')\n\t\t\tdelete transformedRequestParams['stop'];\n\n\t\tconst providerOptions = { provider: FIREWORKS_AI, llmApiKey };\n\n\t\treturn await handleProviderRequest({\n\t\t\tproviderOptions,\n\t\t\tinputParams: modelParams,\n\t\t\tendpoint: 'chatComplete',\n\t\t\ttransformedRequestParams\n\t\t});\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: FIREWORKS_AI });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\t// Create model strings for Fireworks AI\n\tconst pipeModel = pipe.model.split(':')[1];\n\tconst model =\n\t\tpipeModel === 'yi-large'\n\t\t\t? 'accounts/yi-01-ai/models/yi-large'\n\t\t\t: `accounts/fireworks/models/${pipeModel}`;\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import { dlog } from '../utils/dlog';\nimport transformToProviderRequest from '../utils/provider-handlers/transfrom-to-provider-request';\nimport { handleProviderRequest } from '../utils/provider-handlers/provider-request-handler';\nimport { GOOGLE } from '../data/models';\nimport { applyJsonModeIfEnabledForGoogle, handleLlmError } from './utils';\nimport type { ModelParams } from 'types/providers';\nimport type { Message, Pipe } from 'types/pipe';\nimport { addToolsToParams } from '../utils/add-tools-to-params';\nimport type { PipeTool } from 'types/tools';\n\nexport async function callGoogle({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream,\n\tparamsTools\n}: {\n\tpipe: Pipe;\n\tstream: boolean;\n\tllmApiKey: string;\n\tmessages: Message[];\n\tparamsTools: PipeTool[] | undefined;\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\t\taddToolsToParams(modelParams, pipe, paramsTools);\n\n\t\t// Transform params according to provider's format\n\t\tconst transformedRequestParams = transformToProviderRequest({\n\t\t\tprovider: GOOGLE,\n\t\t\tparams: modelParams,\n\t\t\tfn: 'chatComplete'\n\t\t});\n\n\t\tapplyJsonModeIfEnabledForGoogle(transformedRequestParams, pipe);\n\n\t\tdlog('Google request params', transformedRequestParams);\n\n\t\tconst providerOptions = { provider: GOOGLE, llmApiKey };\n\n\t\treturn await handleProviderRequest({\n\t\t\tproviderOptions,\n\t\t\tinputParams: modelParams,\n\t\t\tendpoint: 'chatComplete',\n\t\t\ttransformedRequestParams\n\t\t});\n\t} catch (error: any) {\n\t\timproveGoogleErrorMessage(error);\n\t\thandleLlmError({ error, provider: GOOGLE });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n\nfunction improveGoogleErrorMessage(error: any) {\n\tif (\n\t\terror.message.includes(\n\t\t\t`models/gemini-1.5-pro-latest is not found for API version v1`\n\t\t)\n\t) {\n\t\terror.message = `You don't have access to gemini-1.5-pro-latest by Google Cloud AI. Contact Google support.`;\n\t}\n\tif (\n\t\terror.message.includes(\n\t\t\t`models/gemini-1.5-flash is not found for API version v1`\n\t\t)\n\t) {\n\t\terror.message = `You don't have access to gemini-1.5-flash by Google Cloud AI. Contact Google support.`;\n\t}\n}\n","import OpenAI from 'openai';\nimport { dlog } from '../utils/dlog';\nimport { GROQ } from '../data/models';\nimport transformToProviderRequest from '../utils/provider-handlers/transfrom-to-provider-request';\nimport { applyJsonModeIfEnabled, handleLlmError } from './utils';\nimport type { ModelParams } from 'types/providers';\nimport type { Message, Pipe } from 'types/pipe';\n\nexport async function callGroq({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream\n}: {\n\tpipe: Pipe;\n\tllmApiKey: string;\n\tstream: boolean;\n\tmessages: Message[];\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\t\tconst groq = new OpenAI({\n\t\t\tapiKey: llmApiKey,\n\t\t\tbaseURL: 'https://api.groq.com/openai/v1'\n\t\t});\n\t\tapplyJsonModeIfEnabled(modelParams, pipe);\n\n\t\t// Transform params according to provider's format\n\t\tconst transformedRequestParams = transformToProviderRequest({\n\t\t\tprovider: GROQ,\n\t\t\tparams: modelParams as ModelParams,\n\t\t\tfn: 'chatComplete'\n\t\t});\n\t\tdlog('Groq request params', transformedRequestParams);\n\n\t\treturn await groq.chat.completions.create(\n\t\t\ttransformedRequestParams as any\n\t\t);\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: GROQ });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import { dlog } from '../utils/dlog';\nimport transformToProviderRequest from '../utils/provider-handlers/transfrom-to-provider-request';\nimport { handleProviderRequest } from '../utils/provider-handlers/provider-request-handler';\n\nimport { OLLAMA } from '../data/models';\nimport { handleLlmError } from './utils';\nimport type { Message, Pipe } from 'types/pipe';\nimport type { ModelParams } from 'types/providers';\n\nexport async function callOllama({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream\n}: {\n\tpipe: Pipe;\n\tllmApiKey: string;\n\tstream: boolean;\n\tmessages: Message[];\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\n\t\t// Transform params according to provider's format\n\t\tconst transformedRequestParams = transformToProviderRequest({\n\t\t\tprovider: OLLAMA,\n\t\t\tparams: modelParams,\n\t\t\tfn: 'chatComplete'\n\t\t});\n\t\tdlog('ollama request params', transformedRequestParams);\n\n\t\tconst providerOptions = { provider: OLLAMA, llmApiKey };\n\t\treturn await handleProviderRequest({\n\t\t\tproviderOptions,\n\t\t\tinputParams: modelParams,\n\t\t\tendpoint: 'chatComplete',\n\t\t\ttransformedRequestParams\n\t\t});\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: OLLAMA });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import { ApiError } from '@/dev/hono/errors';\nimport OpenAI from 'openai';\nimport { dlog } from '../utils/dlog';\nimport { moderate } from '../utils/moderate';\nimport { OPEN_AI } from '../data/models';\nimport { applyJsonModeIfEnabled, handleLlmError } from './utils';\nimport type { Message, Pipe } from 'types/pipe';\nimport type { ModelParams } from 'types/providers';\nimport { addToolsToParams } from '../utils/add-tools-to-params';\nimport type { PipeTool } from 'types/tools';\n\nexport async function callOpenAI({\n\tpipe,\n\tstream,\n\tllmApiKey,\n\tmessages,\n\tparamsTools\n}: {\n\tpipe: Pipe;\n\tstream: boolean;\n\tllmApiKey: string;\n\tmessages: Message[];\n\tparamsTools: PipeTool[] | undefined;\n}) {\n\ttry {\n\t\tvalidateInput(pipe, messages);\n\t\tconst openai = new OpenAI({ apiKey: llmApiKey });\n\t\tawait moderateContent(openai, messages, pipe.moderate);\n\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\t\taddToolsToParams(modelParams, pipe, paramsTools);\n\t\tapplyJsonModeIfEnabled(modelParams, pipe);\n\n\t\tdlog('modelParams', modelParams);\n\t\treturn await openai.chat.completions.create(modelParams as any);\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: OPEN_AI });\n\t}\n}\n\nfunction validateInput(pipe: Pipe, messages: Message[]) {\n\tif (!pipe || !pipe.model || !messages || messages.length === 0) {\n\t\tthrow new ApiError({\n\t\t\tcode: 'BAD_REQUEST',\n\t\t\tmessage: 'Invalid input: pipe or messages are missing or empty'\n\t\t});\n\t}\n}\n\nasync function moderateContent(\n\topenai: OpenAI,\n\tmessages: Message[],\n\tshouldModerate: boolean = true\n) {\n\tif (shouldModerate) {\n\t\tconst { flagged, reason } = await moderate({\n\t\t\topenai,\n\t\t\tprompt: { messages, variables: [] }\n\t\t});\n\n\t\tif (flagged) {\n\t\t\tthrow new ApiError({\n\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\tmessage: reason\n\t\t\t});\n\t\t}\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel: model || 'gpt-4o-mini',\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import OpenAI from 'openai';\nimport type { Message } from 'types/pipe';\n\nexport async function moderate({\n\topenai,\n\tprompt\n}: {\n\topenai: OpenAI;\n\tprompt: {\n\t\tmessages: Message[];\n\t\tvariables: any[];\n\t};\n}) {\n\t// Construct a string representation of the prompt\n\tlet promptText = '';\n\n\t// Process messages if they exist\n\tif (prompt.messages && prompt.messages.length > 0) {\n\t\tfor (const message of prompt.messages) {\n\t\t\tpromptText += message.content + '\\n';\n\t\t}\n\t}\n\n\t// Process variables if they exist\n\tif (prompt.variables && prompt.variables.length > 0) {\n\t\tfor (const variable of prompt.variables) {\n\t\t\tpromptText += `${variable.name}: ${variable.value}\\n`;\n\t\t}\n\t}\n\n\t// Perform moderation on the constructed prompt text\n\tconst moderation = await openai.moderations.create({\n\t\tmodel: 'omni-moderation-latest',\n\t\tinput: promptText\n\t});\n\tconst result = moderation?.results[0];\n\t// dlog('moderation:', result);\n\n\t// Content is flagged by OpenAI's moderation\n\tif (result.flagged) {\n\t\t// Filter categories to only include those that are true\n\t\tconst flaggedCategories = Object.entries(result.categories)\n\t\t\t.filter(([, value]) => value === true)\n\t\t\t.map(([key]) => key.replace('/', ' or ')); // Replace slashes for readability\n\n\t\tconst reasons = flaggedCategories.join(', ');\n\n\t\t// Construct and return the error message\n\t\treturn {\n\t\t\tflagged: result.flagged,\n\t\t\treason: `Content flagged by OpenAI moderation endpoint due to: ${reasons}`\n\t\t};\n\t}\n\n\treturn {\n\t\tflagged: result.flagged,\n\t\treason: 'Content passed OpenAI moderation successfully'\n\t};\n}\n","import { dlog } from '../utils/dlog';\nimport transformToProviderRequest from '../utils/provider-handlers/transfrom-to-provider-request';\nimport { handleProviderRequest } from '../utils/provider-handlers/provider-request-handler';\n\nimport { PERPLEXITY } from '../data/models';\nimport { handleLlmError } from './utils';\nimport type { Message, Pipe } from 'types/pipe';\nimport type { ModelParams } from 'types/providers';\n\nexport async function callPerplexity({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream\n}: {\n\tpipe: Pipe;\n\tllmApiKey: string;\n\tstream: boolean;\n\tmessages: Message[];\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\n\t\t// Transform params according to provider's format\n\t\tconst transformedRequestParams = transformToProviderRequest({\n\t\t\tprovider: PERPLEXITY,\n\t\t\tparams: modelParams,\n\t\t\tfn: 'chatComplete'\n\t\t});\n\t\tdlog('Perplexity request params', transformedRequestParams);\n\n\t\tconst providerOptions = { provider: PERPLEXITY, llmApiKey };\n\t\treturn await handleProviderRequest({\n\t\t\tproviderOptions,\n\t\t\tinputParams: modelParams,\n\t\t\tendpoint: 'chatComplete',\n\t\t\ttransformedRequestParams\n\t\t});\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: PERPLEXITY });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import OpenAI from 'openai';\nimport { dlog } from '../utils/dlog';\nimport { GROQ } from '../data/models';\nimport { applyJsonModeIfEnabled, handleLlmError } from './utils';\nimport type { Message, Pipe } from 'types/pipe';\nimport type { ModelParams } from 'types/providers';\nimport { addToolsToParams } from '../utils/add-tools-to-params';\nimport type { PipeTool } from 'types/tools';\n\nexport async function callTogether({\n\tpipe,\n\tmessages,\n\tllmApiKey,\n\tstream,\n\tparamsTools\n}: {\n\tpipe: Pipe;\n\tllmApiKey: string;\n\tstream: boolean;\n\tmessages: Message[];\n\tparamsTools: PipeTool[] | undefined;\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\n\t\t// LLM.\n\t\tconst together = new OpenAI({\n\t\t\tapiKey: llmApiKey,\n\t\t\tbaseURL: 'https://api.together.xyz/v1'\n\t\t});\n\n\t\t// Together behaves weirdly with stop value. Omitting it.\n\t\tdelete modelParams['stop'];\n\t\tapplyJsonModeIfEnabled(modelParams, pipe);\n\t\taddToolsToParams(modelParams, pipe, paramsTools);\n\t\tdlog('modelParams', modelParams);\n\n\t\treturn await together.chat.completions.create(modelParams as any);\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: GROQ });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import OpenAI from 'openai';\nimport { dlog } from '../utils/dlog';\nimport { X_AI } from '../data/models';\nimport { handleLlmError } from './utils';\nimport type { Message, Pipe } from 'types/pipe';\nimport type { ModelParams } from 'types/providers';\nimport { addToolsToParams } from '../utils/add-tools-to-params';\nimport type { PipeTool } from 'types/tools';\n\nexport async function callXAI({\n\tpipe,\n\tstream,\n\tllmApiKey,\n\tmessages,\n\tparamsTools\n}: {\n\tpipe: Pipe;\n\tstream: boolean;\n\tllmApiKey: string;\n\tmessages: Message[];\n\tparamsTools: PipeTool[] | undefined;\n}) {\n\ttry {\n\t\tconst modelParams = buildModelParams(pipe, stream, messages);\n\n\t\t// LLM.\n\t\tconst groq = new OpenAI({\n\t\t\tapiKey: llmApiKey,\n\t\t\tbaseURL: 'https://api.x.ai/v1'\n\t\t});\n\n\t\t// Add tools (functions) to modelParams\n\t\taddToolsToParams(modelParams, pipe, paramsTools);\n\t\tdlog('modelParams', modelParams);\n\n\t\treturn await groq.chat.completions.create(modelParams as any);\n\t} catch (error: any) {\n\t\thandleLlmError({ error, provider: X_AI });\n\t}\n}\n\nfunction buildModelParams(\n\tpipe: Pipe,\n\tstream: boolean,\n\tmessages: Message[]\n): ModelParams {\n\tconst model = pipe.model.split(':')[1];\n\tconst {\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t} = pipe;\n\treturn {\n\t\tmessages,\n\t\tstream,\n\t\tmodel,\n\t\ttop_p,\n\t\tmax_tokens,\n\t\ttemperature,\n\t\tpresence_penalty,\n\t\tfrequency_penalty,\n\t\tstop\n\t};\n}\n","import {\n\tANTHROPIC,\n\tCOHERE,\n\tFIREWORKS_AI,\n\tGOOGLE,\n\tGROQ,\n\tOLLAMA,\n\tOPEN_AI,\n\tPERPLEXITY,\n\tTOGETHER_AI,\n\tX_AI\n} from '@/dev/data/models';\n\nimport { addContextFromMemory } from '@/utils/memory/lib';\nimport type { Message, Pipe, VariablesI } from 'types/pipe';\nimport { ApiError } from '../hono/errors';\nimport { dlog } from '../utils/dlog';\nimport { getRunThread } from '../utils/thread/get-run-thread';\nimport { callAnthropic } from './call-anthropic';\nimport { callCohere } from './call-cohere';\nimport { callFireworks } from './call-fireworks';\nimport { callGoogle } from './call-google';\nimport { callGroq } from './call-groq';\nimport { callOllama } from './call-ollama';\nimport { callOpenAI } from './call-openai';\nimport { callPerplexity } from './call-perplexity';\nimport { callTogether } from './call-together';\nimport { callXAI } from './call-xai';\nimport { getProvider } from '../utils/get-provider';\nimport type { PipeTool } from 'types/tools';\n\nexport async function callLLM({\n\tpipe,\n\tstream,\n\tmessages,\n\tllmApiKey,\n\tvariables,\n\tparamsTools\n}: {\n\tpipe: Pipe;\n\tstream: boolean;\n\tllmApiKey: string;\n\tmessages: Message[];\n\tvariables?: VariablesI;\n\tparamsTools: PipeTool[] | undefined;\n}) {\n\ttry {\n\t\t// Get the model provider from the pipe.\n\t\tconst providerString = pipe.model.split(':')[0];\n\t\tconst modelProvider = getProvider(providerString);\n\n\t\tconst memoryNames = pipe.memory.map(memory => memory.name);\n\n\t\tconst similarChunks = await addContextFromMemory({\n\t\t\tmessages,\n\t\t\tmemoryNames\n\t\t});\n\n\t\t// Process the messages to be sent to the model provider.\n\t\tconst messagesThread = getRunThread({\n\t\t\tpipe,\n\t\t\tmessages,\n\t\t\tsimilarChunks,\n\t\t\tvariables\n\t\t});\n\t\tmessages = messagesThread;\n\n\t\tdlog('Messages for LLM', messages);\n\n\t\tif (modelProvider === OPEN_AI) {\n\t\t\tdlog('OPEN_AI', '✅');\n\t\t\treturn await callOpenAI({\n\t\t\t\tpipe,\n\t\t\t\tstream,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tparamsTools\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === ANTHROPIC) {\n\t\t\tdlog('ANTHROPIC', '✅');\n\t\t\treturn await callAnthropic({\n\t\t\t\tpipe,\n\t\t\t\tstream,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tparamsTools\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === TOGETHER_AI) {\n\t\t\tdlog('TOGETHER_AI', '✅');\n\t\t\treturn await callTogether({\n\t\t\t\tpipe,\n\t\t\t\tstream,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tparamsTools,\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === GROQ) {\n\t\t\tdlog('GROQ', '✅');\n\t\t\treturn await callGroq({\n\t\t\t\tpipe,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tstream\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === GOOGLE) {\n\t\t\tdlog('GOOGLE', '✅');\n\t\t\treturn await callGoogle({\n\t\t\t\tpipe,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tstream,\n\t\t\t\tparamsTools\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === X_AI) {\n\t\t\tdlog('XAI', '✅');\n\t\t\treturn await callXAI({\n\t\t\t\tpipe,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tstream,\n\t\t\t\tparamsTools\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === COHERE) {\n\t\t\tdlog('COHERE', '✅');\n\t\t\treturn await callCohere({\n\t\t\t\tpipe,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tstream\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === FIREWORKS_AI) {\n\t\t\tdlog('FIREWORKS_AI', '✅');\n\t\t\treturn await callFireworks({\n\t\t\t\tpipe,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tstream\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === PERPLEXITY) {\n\t\t\tdlog('PERPLEXITY', '✅');\n\t\t\treturn await callPerplexity({\n\t\t\t\tpipe,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tstream\n\t\t\t});\n\t\t}\n\n\t\tif (modelProvider === OLLAMA) {\n\t\t\tdlog('OLLAMA', '✅');\n\t\t\treturn await callOllama({\n\t\t\t\tpipe,\n\t\t\t\tmessages,\n\t\t\t\tllmApiKey,\n\t\t\t\tstream\n\t\t\t});\n\t\t}\n\n\t\tthrow new ApiError({\n\t\t\tstatus: 400,\n\t\t\tcode: `BAD_REQUEST`,\n\t\t\tmessage: `Invalid model provider: ${modelProvider}`\n\t\t});\n\t} catch (error: any) {\n\t\tdlog('Error call-llm.ts:', error);\n\n\t\t// If the model provider is rate limited, throw an error.\n\t\tif (error.status === 429) {\n\t\t\tthrow new ApiError({\n\t\t\t\tstatus: 429,\n\t\t\t\tcode: `RATE_LIMITED`,\n\t\t\t\tmessage: `Rate limited by the model provider. Please try again later. ${error.message}`\n\t\t\t});\n\t\t}\n\n\t\t// Main catch will handle all other errors.\n\t\tthrow new ApiError({\n\t\t\tstatus: error.status,\n\t\t\tcode: error.code || 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: error.message\n\t\t\t\t? error.message\n\t\t\t\t: 'Error calling the model provider.'\n\t\t});\n\t}\n}\n","import type { Context } from 'hono';\nimport { ApiError } from '@/dev/hono/errors';\nimport type { HonoEnv } from '@/dev/hono/env';\n\n/**\n * Handles streaming response from OpenAI and other providers.\n *\n * It handles the two cases accordingly\n * ReadableStream: Return as it is\n * Async Iterator: Convert to OpenAI SSE format Readable stream and return it\n * Returns the stream in OpenAI API SSE format\n *\n * @param {Response} response - The Streaming response.\n * @param {string} provider - The provider name string.\n * @param {any | undefined} headers - Optional headers to send with the streamed response\n * @returns {Promise<any>} - A promise that resolves to the processed response.\n */\nexport const handleStreamingResponse = async ({\n\tc,\n\tresponse,\n\theaders\n}: {\n\tc: Context<HonoEnv>;\n\tresponse: any;\n\theaders?: any;\n}): Promise<any> => {\n\ttry {\n\t\t// Response is from our provider transform\n\t\tif (response instanceof ReadableStream) {\n\t\t\t// Dulplicate the stream because a stream can only be consumed once.\n\t\t\tconst [streamForResponse] = response.tee();\n\n\t\t\treturn new Response(streamForResponse, {\n\t\t\t\t// Send headers if provided\n\t\t\t\theaders: { 'content-type': 'text/event-stream', ...headers }\n\t\t\t});\n\t\t} else {\n\t\t\t/**\n\t\t\t * Response is from OpenAI SDK:\n\t\t\t * It is an async iterator\n\t\t\t * We transform it into OpenAI SSE format and return it\n\t\t\t */\n\t\t\t// Handle async iterators (e.g., from OpenAI SDK)\n\t\t\tconst stream = new ReadableStream({\n\t\t\t\tasync start(controller) {\n\t\t\t\t\tconst encoder = new TextEncoder();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor await (const chunk of response) {\n\t\t\t\t\t\t\tconst data = JSON.stringify(chunk);\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(`data: ${data}\\n\\n`)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.error('Error processing stream:', error);\n\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcontroller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn new Response(stream, {\n\t\t\t\t// Send headers if provided\n\t\t\t\theaders: { 'content-type': 'text/event-stream', ...headers }\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tconsole.error('Error in handleStreamingResponse:', error);\n\t\tthrow new ApiError({\n\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: `Error while streaming: ${error}`\n\t\t});\n\t}\n};\n","import { ApiError, ApiErrorZod } from '@/dev/hono/errors';\nimport { callLLM } from '@/dev/llms/call-llm';\nimport { dlog } from '@/dev/utils/dlog';\nimport { handleStreamingResponse } from '@/dev/utils/provider-handlers/streaming-response-handler';\nimport { logger } from '@/utils/logger-utils';\nimport { Hono } from 'hono';\nimport {\n\tschemaMessage,\n\ttoolChoiceSchema,\n\tVariablesSchema,\n\ttype PipeModelT\n} from 'types/pipe';\nimport { pipeToolSchema } from 'types/tools';\nimport { z } from 'zod';\n\n// Schema definitions\nconst PipeSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string(),\n\tstatus: z.enum(['public', 'private']),\n\tmodel: z.string(),\n\tstream: z.boolean(),\n\tjson: z.boolean(),\n\tstore: z.boolean(),\n\tmoderate: z.boolean(),\n\ttop_p: z.number(),\n\tmax_tokens: z.number(),\n\ttemperature: z.number(),\n\tpresence_penalty: z.number(),\n\tfrequency_penalty: z.number(),\n\tstop: z.array(z.string()),\n\ttool_choice: z\n\t\t.union([z.enum(['auto', 'required', 'none']), toolChoiceSchema])\n\t\t.default('auto'),\n\tparallel_tool_calls: z.boolean(),\n\tmessages: z.array(schemaMessage),\n\tvariables: VariablesSchema,\n\ttools: z.array(pipeToolSchema).default([]),\n\tmemory: z.array(z.object({ name: z.string().trim().min(1) })).default([])\n});\n\nconst RequestBodySchema = z.object({\n\tpipe: PipeSchema,\n\tstream: z.boolean(),\n\tmessages: z.array(schemaMessage),\n\tllmApiKey: z.string(),\n\ttools: z.array(pipeToolSchema).optional(),\n\tvariables: VariablesSchema.optional()\n});\n\ntype RequestBody = z.infer<typeof RequestBodySchema>;\n\n// Helper functions\nconst validateRequestBody = (body: unknown): RequestBody => {\n\tconst result = RequestBodySchema.safeParse(body);\n\tif (!result.success) {\n\t\tthrow new ApiErrorZod({\n\t\t\tcode: 'BAD_REQUEST',\n\t\t\tvalidationResult: result,\n\t\t\tcustomMessage: 'Invalid request body'\n\t\t});\n\t}\n\treturn result.data;\n};\n\nconst processLlmResponse = (c: any, body: RequestBody, rawLlmResponse: any) => {\n\tconst isStreaming = body.stream;\n\n\t// Non-streaming\n\tif (!isStreaming && rawLlmResponse?.choices?.length > 0) {\n\t\tconst completion = rawLlmResponse.choices[0]?.message?.content ?? '';\n\t\tconst toolCalls = rawLlmResponse.choices[0]?.message?.tool_calls ?? [];\n\t\tconst isToolCall = toolCalls.length > 0;\n\n\t\tlogger('tool', isToolCall, 'Tool calls found');\n\t\tlogger('tool.calls', toolCalls);\n\t\tlogger('pipe.completion', completion, 'Pipe completion');\n\t\tlogger('pipe.response', rawLlmResponse, 'type: (non-streaming)');\n\n\t\treturn c.json({ completion, ...rawLlmResponse });\n\t}\n\n\t// Streaming\n\tif (isStreaming) {\n\t\tlogger('pipe.response', rawLlmResponse, 'type: (streaming)');\n\t\treturn handleStreamingResponse({\n\t\t\tresponse: rawLlmResponse,\n\t\t\theaders: {},\n\t\t\tc\n\t\t});\n\t}\n\treturn c.json({ body });\n};\n\nconst handleGenerateError = (c: any, error: unknown) => {\n\tif (error instanceof ApiErrorZod) {\n\t\tthrow error;\n\t}\n\n\tconst errorMessage =\n\t\terror instanceof Error\n\t\t\t? error.message\n\t\t\t: 'Unexpected error occurred in /pipe/v1/run';\n\n\tdlog('Error /pipe/v1/run.ts:', error);\n\n\tthrow new ApiError({\n\t\tstatus: error instanceof ApiError ? error.status : 500,\n\t\tcode: error instanceof ApiError ? error.code : 'INTERNAL_SERVER_ERROR',\n\t\tmessage: errorMessage,\n\t\tdocs: error instanceof ApiError ? error.docs : undefined\n\t});\n};\n\n// Main endpoint handler\nconst handleRun = async (c: any) => {\n\ttry {\n\t\tconst body = await c.req.json();\n\n\t\tconst llmKey = (body.llmApiKey as string) || '';\n\t\tconst hiddenChars = new Array(45).fill('*').join('');\n\t\tconst redactedKey = llmKey.length\n\t\t\t? llmKey.slice(0, 8) + hiddenChars\n\t\t\t: '';\n\n\t\tconst logData = { ...body, llmApiKey: redactedKey };\n\t\tlogger('pipe.request', logData, 'Pipe Request Body');\n\n\t\tconst validatedBody = validateRequestBody(body);\n\n\t\tconst { pipe, messages, llmApiKey, stream, variables } = validatedBody;\n\t\tconst model = pipe.model as PipeModelT;\n\n\t\tconst rawLlmResponse = await callLLM({\n\t\t\tpipe: {\n\t\t\t\t...pipe,\n\t\t\t\tmodel\n\t\t\t},\n\t\t\tmessages,\n\t\t\tllmApiKey,\n\t\t\tstream,\n\t\t\tvariables,\n\t\t\tparamsTools: validatedBody.tools\n\t\t});\n\n\t\treturn processLlmResponse(c, validatedBody, rawLlmResponse);\n\t} catch (error: unknown) {\n\t\treturn handleGenerateError(c, error);\n\t}\n};\n\n// Register the endpoint\nexport const registerV1PipesRun = (app: Hono) => {\n\tapp.post('/v1/pipes/run', handleRun);\n};\n","import { z } from 'zod';\nimport type {\n\tAnthropicModels,\n\tCohereModels,\n\tFireworksAIModels,\n\tGoogleModels,\n\tGroqModels,\n\tMistralAIModels,\n\tOllamaModels,\n\tOpenAIModels,\n\tPerplexityModels,\n\tTogetherModels\n} from './model';\nimport type { PipeTool } from './tools';\n\nexport const schemaMessage = z\n\t.object({\n\t\trole: z.enum(['system', 'user', 'assistant', 'function', 'tool']),\n\t\tcontent: z.string().nullable(),\n\t\ttool_call_id: z.string().optional(),\n\t\tname: z.string().optional(),\n\t\ttool_calls: z\n\t\t\t.array(\n\t\t\t\tz.object({\n\t\t\t\t\tid: z.string(),\n\t\t\t\t\ttype: z.string(),\n\t\t\t\t\tfunction: z.record(z.unknown())\n\t\t\t\t})\n\t\t\t)\n\t\t\t.optional()\n\t})\n\t.refine(\n\t\t({ content, role, tool_calls }) => {\n\t\t\t// If content is null, role isn't assistant and tool_calls is not present.\n\t\t\t// then the schema is invalid\n\t\t\t// because the message content is null and its not an assistant tool call\n\t\t\tconst isSchemaInvalid =\n\t\t\t\tcontent === null && role !== 'assistant' && !tool_calls;\n\n\t\t\tif (isSchemaInvalid) return false;\n\t\t\treturn true;\n\t\t},\n\t\t{\n\t\t\tmessage: 'Message content cannot be empty.'\n\t\t}\n\t);\n\nexport type Message = z.infer<typeof schemaMessage>;\n\nexport const VariableSchema = z.object({\n\tname: z.string(),\n\tvalue: z.string()\n});\n\nexport const VariablesSchema = z.array(VariableSchema).default([]);\n\nexport type VariablesI = z.infer<typeof VariablesSchema>;\nexport type VariableI = z.infer<typeof VariableSchema>;\n\ninterface ToolFunction {\n\tname: string;\n}\n\ninterface ToolChoiceFunction {\n\ttype: 'function';\n\tfunction: ToolFunction;\n}\n\nexport type ToolChoice = 'auto' | 'required' | 'none' | ToolChoiceFunction;\n\nexport type PipeModelT =\n\t| OpenAIModels\n\t| TogetherModels\n\t| AnthropicModels\n\t| GroqModels\n\t| GoogleModels\n\t| CohereModels\n\t| FireworksAIModels\n\t| PerplexityModels\n\t| MistralAIModels\n\t| OllamaModels;\n\nexport interface Pipe {\n\tapiKey?: string;\n\tname: string;\n\tdescription: string;\n\tstatus: 'public' | 'private';\n\tmodel: PipeModelT;\n\tstream: boolean;\n\tjson: boolean;\n\tstore: boolean;\n\tmoderate: boolean;\n\ttop_p: number;\n\tmax_tokens: number;\n\ttemperature: number;\n\tpresence_penalty: number;\n\tfrequency_penalty: number;\n\tstop: string[];\n\ttool_choice: ToolChoice;\n\tparallel_tool_calls: boolean;\n\tmessages: Message[];\n\tvariables: VariablesI;\n\ttools: PipeTool[];\n\tmemory: {\n\t\tname: string;\n\t}[];\n}\n\nexport interface PipeOld {\n\tname: string;\n\tdescription: string;\n\tstatus: string;\n\tconfig: {\n\t\tmeta: {\n\t\t\tstream: boolean;\n\t\t\tjson: boolean;\n\t\t\tstore: boolean;\n\t\t\tmoderate: boolean;\n\t\t};\n\t\tmodel: {\n\t\t\tname: string;\n\t\t\tprovider: string;\n\t\t\tparams: {\n\t\t\t\ttop_p: number;\n\t\t\t\tmax_tokens: number;\n\t\t\t\ttemperature: number;\n\t\t\t\tpresence_penalty: number;\n\t\t\t\tfrequency_penalty: number;\n\t\t\t\tstop: string[];\n\t\t\t};\n\t\t\ttool_choice: ToolChoice;\n\t\t\tparallel_tool_calls: boolean;\n\t\t};\n\t\tprompt: {\n\t\t\tsystem: string;\n\t\t\topening: string;\n\t\t\tsafety: string;\n\t\t\tmessages: { role: string; content: string }[];\n\t\t\tvariables: VariablesI;\n\t\t\tjson: string;\n\t\t\trag: string;\n\t\t};\n\t\ttools: any[];\n\t\tmemorysets: string[];\n\t};\n}\n\nexport interface ToolCall {\n\tid: string;\n\ttype: string;\n\tfunction: {\n\t\tname: string;\n\t\targuments: string;\n\t};\n}\n\nconst functionNameRegex = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n\nexport const toolChoiceSchema = z\n\t.object({\n\t\ttype: z.enum(['function']).default('function'),\n\t\tfunction: z.object({\n\t\t\tname: z.string().refine(value => functionNameRegex.test(value))\n\t\t})\n\t})\n\t.optional();\n","import { z } from 'zod';\n\nexport interface Tool {\n\trun: (...args: any[]) => Promise<any> | any;\n\ttype: 'function';\n\tfunction: {\n\t\tname: string;\n\t\tdescription?: string;\n\t\tparameters?: Record<string, any>;\n\t};\n}\n\nexport const pipeToolSchema = z.object({\n\ttype: z.literal('function'),\n\tfunction: z.object({\n\t\tname: z.string(),\n\t\tdescription: z.string().optional(),\n\t\tparameters: z.record(z.any()).optional()\n\t})\n});\n\nexport type PipeTool = z.infer<typeof pipeToolSchema>;\n","import { defaultConfig } from '@/utils/config/config-handler';\nimport { cyan, dimItalic } from '@/utils/formatting';\nimport { heading } from '@/utils/heading';\nimport { formatCode } from '@/utils/ts-format-code';\nimport { detect } from '@antfu/ni';\nimport * as p from '@clack/prompts';\nimport { execa } from 'execa';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport color from 'picocolors';\n\ntype PackageManager = 'yarn' | 'pnpm' | 'bun' | 'npm';\n\nfunction exitSetupFailed({\n\terrorMessage,\n\twarningMessage\n}: {\n\terrorMessage: string;\n\twarningMessage: string;\n}): never {\n\tp.log.error(`Setup failed: ${errorMessage}`);\n\tp.log.warn(warningMessage);\n\tp.cancel('Setup aborted.');\n\tprocess.exit(1);\n}\n\nasync function displayIntro({\n\tcalledAsCommand\n}: {\n\tcalledAsCommand: boolean;\n}): Promise<void> {\n\tif (calledAsCommand) {\n\t\tp.intro(heading({ text: 'SETUP', sub: 'Setting up BaseAI' }));\n\t}\n}\n\nasync function ensurePackageJson(): Promise<void> {\n\tconst exists = await checkFileExists('package.json');\n\tif (!exists) {\n\t\tconst create = await p.confirm({\n\t\t\tmessage: `No ${color.red('package.json')} found. Would you like to create one using ${color.cyan(color.bold('npm init -y'))}?`\n\t\t});\n\n\t\tif (p.isCancel(create)) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\tif (!create) {\n\t\t\texitSetupFailed({\n\t\t\t\terrorMessage: 'Cannot proceed without a package.json file.',\n\t\t\t\twarningMessage:\n\t\t\t\t\t'Run the command in a directory with a package.json file or allow the setup to create one.'\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tawait execa('npm', ['init', '-y']);\n\t\t\tp.log.success('Created package.json file.');\n\t\t} catch (error) {\n\t\t\texitSetupFailed({\n\t\t\t\terrorMessage: `Failed to create package.json: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\twarningMessage:\n\t\t\t\t\t'Ensure you have permission to create files in this directory and npm is installed.'\n\t\t\t});\n\t\t}\n\t}\n}\n\nasync function getPackageManager(targetDir: string): Promise<PackageManager> {\n\tconst packageManager = await detect({ programmatic: true, cwd: targetDir });\n\n\tif (packageManager === 'yarn@berry') return 'yarn';\n\tif (packageManager === 'pnpm@6') return 'pnpm';\n\tif (packageManager === 'bun') return 'bun';\n\n\treturn packageManager ?? 'npm';\n}\n\nasync function checkBaseAIInstalled(): Promise<boolean> {\n\ttry {\n\t\tconst packageJson = JSON.parse(\n\t\t\tawait fs.readFile('package.json', 'utf-8')\n\t\t);\n\t\tconst hasBaseAIDev = 'baseai' in (packageJson.devDependencies || {});\n\t\tconst hasBaseAICore =\n\t\t\t'@baseai/core' in (packageJson.dependencies || {});\n\t\treturn hasBaseAIDev && hasBaseAICore;\n\t} catch (error) {\n\t\treturn false;\n\t}\n}\n\nasync function installBaseAI(packageManager: PackageManager): Promise<void> {\n\tconst isInstalled = await checkBaseAIInstalled();\n\tif (isInstalled) {\n\t\treturn;\n\t}\n\n\tconst s = p.spinner();\n\ts.start('Installing BaseAI');\n\n\tconst installCmd = {\n\t\tnpm: 'install',\n\t\tyarn: 'add',\n\t\tpnpm: 'add',\n\t\tbun: 'add'\n\t}[packageManager];\n\n\ttry {\n\t\tawait execa(packageManager, [installCmd, '@baseai/core']);\n\t\tawait execa(packageManager, [installCmd, 'baseai', '--save-dev']);\n\t\ts.stop('BaseAI installed successfully.');\n\t} catch (error) {\n\t\texitSetupFailed({\n\t\t\terrorMessage: `BaseAI installation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\twarningMessage:\n\t\t\t\t'Ensure you have an active internet connection and the necessary permissions to install packages.'\n\t\t});\n\t}\n}\n\nasync function createDirIfNotExists(dir: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(dir);\n\t\treturn false; // Directory already exists\n\t} catch {\n\t\tawait fs.mkdir(dir, { recursive: true });\n\t\treturn true; // Directory was created\n\t}\n}\n\nasync function checkFileExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(filePath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function createBaseAIDirectories(): Promise<void> {\n\tconst baseaiFolder = path.join(process.cwd(), 'baseai');\n\tconst dotBaseaiFolder = path.join(process.cwd(), '.baseai');\n\n\ttry {\n\t\tconst baseaiCreated = await createDirIfNotExists(baseaiFolder);\n\t\tconst dotBaseaiCreated = await createDirIfNotExists(dotBaseaiFolder);\n\n\t\tif (baseaiCreated && dotBaseaiCreated) {\n\t\t\tp.log.success('Added `baseai` directory to your project.');\n\t\t}\n\t} catch (error) {\n\t\texitSetupFailed({\n\t\t\terrorMessage: `Error setting up directories: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\twarningMessage:\n\t\t\t\t'Ensure you have permission to create directories in this location.'\n\t\t});\n\t}\n}\n\nexport async function createConfigFile(): Promise<void> {\n\tconst configPath = path.join(process.cwd(), 'baseai', 'baseai.config.ts');\n\n\tconst exists = await checkFileExists(configPath);\n\tif (!exists) {\n\t\tconst configContent = `\nimport type {BaseAIConfig} from 'baseai';\n\nexport const config: BaseAIConfig = ${JSON.stringify(defaultConfig, null, 2)};\n`;\n\n\t\ttry {\n\t\t\tconst formattedCode = await formatCode(configContent);\n\t\t\tawait fs.writeFile(configPath, formattedCode);\n\t\t\tp.log.success(\n\t\t\t\t'Created `baseai.config.ts` with default configuration.'\n\t\t\t);\n\t\t} catch (error) {\n\t\t\texitSetupFailed({\n\t\t\t\terrorMessage: `Failed to create baseai.config.ts: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\twarningMessage:\n\t\t\t\t\t'Ensure you have permission to create files in the baseai directory.'\n\t\t\t});\n\t\t}\n\t}\n}\n\nasync function updatePackageJsonScript(): Promise<void> {\n\ttry {\n\t\tconst packageJsonPath = path.join(process.cwd(), 'package.json');\n\t\tconst packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');\n\t\tconst packageJson = JSON.parse(packageJsonContent);\n\n\t\tif (!packageJson.scripts) {\n\t\t\tpackageJson.scripts = {};\n\t\t}\n\n\t\tif (\n\t\t\t!packageJson.scripts.baseai ||\n\t\t\tpackageJson.scripts.baseai !== 'baseai'\n\t\t) {\n\t\t\tpackageJson.scripts.baseai = 'baseai';\n\t\t\tawait fs.writeFile(\n\t\t\t\tpackageJsonPath,\n\t\t\t\tJSON.stringify(packageJson, null, 2)\n\t\t\t);\n\t\t\tp.log.success('Added \"baseai\" script in package.json');\n\t\t} else {\n\t\t\t// p.log.info(\n\t\t\t// \t'\"baseai\" script already exists and is correct in package.json'\n\t\t\t// );\n\t\t}\n\t} catch (error) {\n\t\texitSetupFailed({\n\t\t\terrorMessage: `Failed to update package.json: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\twarningMessage:\n\t\t\t\t'Ensure you have permission to modify the package.json file.'\n\t\t});\n\t}\n}\n\nfunction displayOutro({ calledAsCommand }: { calledAsCommand: boolean }): void {\n\tif (calledAsCommand) {\n\t\tp.outro('All good. BaseAI setup completed successfully!');\n\t\tp.log.warning(\n\t\t\tdimItalic(\n\t\t\t\t`Make sure to set environment variables like mentioned in the ${cyan(`.env.baseai.example`)} file added to your project root.`\n\t\t\t)\n\t\t);\n\t} else {\n\t\tconsole.log();\n\t}\n}\n\nasync function updateGitignore({\n\tgitignoreEntry\n}: {\n\tgitignoreEntry: string;\n}): Promise<void> {\n\tconst gitignorePath = path.join(process.cwd(), '.gitignore');\n\n\ttry {\n\t\tlet gitignoreContent = '';\n\t\ttry {\n\t\t\tgitignoreContent = await fs.readFile(gitignorePath, 'utf-8');\n\t\t} catch (error) {\n\t\t\t// File doesn't exist, create it with the new entry\n\t\t\tawait fs.writeFile(gitignorePath, gitignoreEntry);\n\t\t\treturn; // Exit the function as we've already added the entry\n\t\t}\n\n\t\t// Check if the exact entry already exists\n\t\tif (!gitignoreContent.includes(gitignoreEntry)) {\n\t\t\t// Ensure there's a newline before adding the new entry if the file isn't empty\n\t\t\tconst updatedContent = gitignoreContent.endsWith('\\n')\n\t\t\t\t? gitignoreContent + gitignoreEntry\n\t\t\t\t: gitignoreContent + '\\n' + gitignoreEntry;\n\n\t\t\tawait fs.writeFile(gitignorePath, updatedContent);\n\t\t}\n\t} catch (error) {\n\t\tp.log.error(\n\t\t\t`Error updating .gitignore: ${error instanceof Error ? error.message : String(error)}`\n\t\t);\n\t}\n}\n\nasync function createEnvBaseAIExample(): Promise<void> {\n\tconst envBaseAIExamplePath = path.join(\n\t\tprocess.cwd(),\n\t\t'.env.baseai.example'\n\t);\n\tconst envBaseAIExampleContent = `# !! SERVER SIDE ONLY !!\n# Keep all your API keys secret — use only on the server side.\n\n# TODO: ADD: Both in your production and local env files.\n# Langbase API key for your User or Org account.\n# How to get this API key https://langbase.com/docs/api-reference/api-keys\nLANGBASE_API_KEY=\n\n# TODO: ADD: LOCAL ONLY. Add only to local env files.\n# Following keys are needed for local pipe runs. For providers you are using.\n# For Langbase, please add the key to your LLM keysets.\n# Read more: Langbase LLM Keysets https://langbase.com/docs/features/keysets\nOPENAI_API_KEY=\nANTHROPIC_API_KEY=\nCOHERE_API_KEY=\nFIREWORKS_API_KEY=\nGOOGLE_API_KEY=\nGROQ_API_KEY=\nMISTRAL_API_KEY=\nPERPLEXITY_API_KEY=\nTOGETHER_API_KEY=\nXAI_API_KEY=\n`;\n\n\ttry {\n\t\tconst exists = await checkFileExists(envBaseAIExamplePath);\n\t\tif (!exists) {\n\t\t\tawait fs.writeFile(envBaseAIExamplePath, envBaseAIExampleContent);\n\t\t\t// p.log.success('Created `.env.baseai.example` file.');\n\t\t} else {\n\t\t\t// p.log.info(\n\t\t\t// \t'`.env.baseai.example` file already exists. Skipping creation.'\n\t\t\t// );\n\t\t}\n\t} catch (error) {\n\t\tp.log.error(\n\t\t\t`Error creating .env.baseai.example: Check the example env file here https://github.com/LangbaseInc/baseai/blob/main/.env.baseai.example\\n Error: ${error instanceof Error ? error.message : String(error)}`\n\t\t);\n\t}\n}\n\nexport async function init({\n\tcalledAsCommand = false,\n\tdebug = false\n}: { calledAsCommand?: boolean; debug?: boolean } = {}): Promise<void> {\n\t// Add interrupt handler\n\tconst interruptHandler = () => {\n\t\tconsole.log('\\nInterrupted. Cleaning up...');\n\t\t// Add any necessary cleanup here\n\t\tprocess.exit(0);\n\t};\n\n\tprocess.on('SIGINT', interruptHandler);\n\n\ttry {\n\t\tawait displayIntro({ calledAsCommand });\n\t\tawait ensurePackageJson();\n\t\tconst packageManager = await getPackageManager(process.cwd());\n\t\tif (calledAsCommand) {\n\t\t\tp.log.info(`Detected package manager: ${packageManager}`);\n\t\t}\n\n\t\tconst isBaseAIInstalled = await checkBaseAIInstalled();\n\n\t\tif (!isBaseAIInstalled) {\n\t\t\tconst installBaseAIChoice = await p.confirm({\n\t\t\t\tmessage:\n\t\t\t\t\t'BaseAI is not installed but required to run. Would you like to install it?'\n\t\t\t});\n\n\t\t\tif (p.isCancel(installBaseAIChoice)) {\n\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\n\t\t\tif (installBaseAIChoice) {\n\t\t\t\tawait installBaseAI(packageManager);\n\t\t\t} else {\n\t\t\t\texitSetupFailed({\n\t\t\t\t\terrorMessage: 'BaseAI packages are required for setup.',\n\t\t\t\t\twarningMessage:\n\t\t\t\t\t\t'Run the setup again and allow installation of BaseAI packages to continue.'\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tawait createBaseAIDirectories();\n\t\tawait createConfigFile();\n\t\tawait updatePackageJsonScript();\n\t\tawait updateGitignore({ gitignoreEntry: `# baseai\\n**/.baseai/\\n` });\n\t\tawait updateGitignore({ gitignoreEntry: `# env file\\n.env\\n` });\n\t\tawait createEnvBaseAIExample();\n\n\t\tdisplayOutro({ calledAsCommand });\n\t} catch (error: any) {\n\t\tdebug && console.error('Error:', error);\n\t\tp.cancel(`baseai init error ${error.message ? error.message : error}`);\n\t\tprocess.exit(1);\n\t} finally {\n\t\t// Remove the interrupt handler after initialization\n\t\tprocess.off('SIGINT', interruptHandler);\n\t}\n}\n","import { cyan, dim, dimItalic } from '@/utils/formatting';\nimport { heading } from '@/utils/heading';\nimport { createDb } from '@/utils/memory/db/lib';\nimport * as p from '@clack/prompts';\nimport slugify from '@sindresorhus/slugify';\nimport camelCase from 'camelcase';\nimport figures from 'figures';\nimport fs from 'fs';\nimport path from 'path';\nimport { memoryNameSchema } from 'types/memory';\nimport { fromZodError } from 'zod-validation-error';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nconst defaultConfig = {\n\tname: 'ai-agent-memory',\n\tdescription: 'My list of docs as memory for an AI agent pipe'\n};\n\nconst MEMORY_CONSTANTS = {\n\tdocumentsDir: 'documents'\n};\n\nexport async function createMemory() {\n\tp.intro(heading({ text: 'MEMORY', sub: 'Create a new memory' }));\n\n\tconst memoryInfo = await p.group(\n\t\t{\n\t\t\tname: () =>\n\t\t\t\tp.text({\n\t\t\t\t\tmessage: 'Name of the memory',\n\t\t\t\t\tplaceholder: defaultConfig.name,\n\t\t\t\t\tvalidate: value => {\n\t\t\t\t\t\tconst validatedName = memoryNameSchema.safeParse(value);\n\t\t\t\t\t\tif (!validatedName.success) {\n\t\t\t\t\t\t\tconst validationError = fromZodError(\n\t\t\t\t\t\t\t\tvalidatedName.error\n\t\t\t\t\t\t\t).toString();\n\t\t\t\t\t\t\treturn validationError;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\tdescription: () =>\n\t\t\t\tp.text({\n\t\t\t\t\tmessage: 'Description of the memory',\n\t\t\t\t\tplaceholder: defaultConfig.description\n\t\t\t\t}),\n\t\t\tuseGit: () =>\n\t\t\t\tp.confirm({\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t'Do you want to create memory from current project git repository?',\n\t\t\t\t\tinitialValue: false\n\t\t\t\t})\n\t\t},\n\t\t{\n\t\t\tonCancel: () => {\n\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t);\n\n\tconst memoryNameSlugified = slugify(memoryInfo.name);\n\tconst memoryNameCamelCase = camelCase('memory-' + memoryNameSlugified);\n\tconst baseDir = path.join(process.cwd(), 'baseai', 'memory');\n\tconst memoryDir = path.join(baseDir, memoryNameSlugified);\n\tconst filePath = path.join(memoryDir, 'index.ts');\n\tconst dbDir = path.join(process.cwd(), '.baseai', 'db');\n\n\tif (memoryInfo.useGit) {\n\t\ttry {\n\t\t\tawait execAsync('git rev-parse --is-inside-work-tree');\n\t\t} catch (error) {\n\t\t\tp.cancel('The current directory is not a Git repository.');\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tconst memoryContent = `import {MemoryI} from '@baseai/core';\n\nconst ${memoryNameCamelCase} = (): MemoryI => ({\n\tname: '${memoryNameSlugified}',\n\tdescription: ${JSON.stringify(memoryInfo.description || '')},\n\tgit: {\n\t\tenabled: ${memoryInfo.useGit},${\n\t\t\tmemoryInfo.useGit\n\t\t\t\t? `\n\t\tinclude: ['**/*'],\n\t\tgitignore: true,`\n\t\t\t\t: `\n\t\tinclude: ['${MEMORY_CONSTANTS.documentsDir}/**/*'],\n\t\tgitignore: false,`\n\t\t}\n\t\tdeployedAt: '',\n\t\tembeddedAt: ''\n\t}\n});\n\nexport default ${memoryNameCamelCase};`;\n\n\ttry {\n\t\tawait fs.promises.mkdir(baseDir, { recursive: true });\n\t\tawait fs.promises.mkdir(memoryDir, { recursive: true });\n\t\tawait fs.promises.writeFile(filePath, memoryContent);\n\t\tawait fs.promises.mkdir(dbDir, { recursive: true });\n\n\t\tif (!memoryInfo.useGit) {\n\t\t\tconst memoryDocumentsPath = path.join(\n\t\t\t\tmemoryDir,\n\t\t\t\tMEMORY_CONSTANTS.documentsDir\n\t\t\t);\n\t\t\tawait fs.promises.mkdir(memoryDocumentsPath, { recursive: true });\n\t\t\tp.note(\n\t\t\t\t`Add documents in baseai/memory/${memoryNameSlugified}/${cyan(`documents`)} to use them in the memory.`\n\t\t\t);\n\t\t} else {\n\t\t\tp.note(\n\t\t\t\t[\n\t\t\t\t\t'All files in this Git repository will be tracked by default.',\n\t\t\t\t\t'',\n\t\t\t\t\t`To modify which files are being tracked, update the config at:`,\n\t\t\t\t\tcyan(filePath)\n\t\t\t\t].join('\\n')\n\t\t\t);\n\t\t}\n\n\t\tawait createDb(memoryNameSlugified);\n\n\t\tp.outro(\n\t\t\theading({\n\t\t\t\ttext: memoryNameCamelCase,\n\t\t\t\tsub: `created as a new memory \\n ${dim(figures.pointer)} ${dimItalic(` ${filePath}`)}`,\n\t\t\t\tgreen: true\n\t\t\t})\n\t\t);\n\t\tprocess.exit(0);\n\t} catch (error: any) {\n\t\tp.cancel(`Error creating memory: ${error.message}`);\n\t\tprocess.exit(1);\n\t}\n}\n","import { heading } from '@/utils/heading';\nimport { checkMemoryExists } from '@/utils/memory/check-memory-exist';\nimport { deleteDocumentFromDB, loadDb } from '@/utils/memory/db/lib';\nimport { generateEmbeddings } from '@/utils/memory/generate-embeddings';\nimport {\n\thandleGitSyncMemories,\n\tupdateEmbeddedCommitHash\n} from '@/utils/memory/git-sync/handle-git-sync-memories';\nimport { validateMemoryName } from '@/utils/memory/lib';\nimport loadMemoryConfig from '@/utils/memory/load-memory-config';\nimport { loadMemoryFiles } from '@/utils/memory/load-memory-files';\nimport * as p from '@clack/prompts';\nimport color from 'picocolors';\n\nexport async function embedMemory({\n\tmemoryName: memoryNameInput,\n\toverwrite,\n\tuseLocalEmbeddings\n}: {\n\tmemoryName: string;\n\toverwrite?: boolean;\n\tuseLocalEmbeddings?: boolean;\n}) {\n\t// Spinner to show current action.\n\tconst s = p.spinner();\n\n\ttry {\n\t\tp.intro(\n\t\t\theading({\n\t\t\t\ttext: 'EMBED',\n\t\t\t\tsub: `Creating embeddings of ${color.cyan(memoryNameInput)}`\n\t\t\t})\n\t\t);\n\n\t\tif (!memoryNameInput) {\n\t\t\tp.cancel(\n\t\t\t\t'Memory name is required. Use --memory or -m flag to specify.'\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\t// 1- Check memory exists.\n\t\tconst memoryName = validateMemoryName(memoryNameInput);\n\t\tawait checkMemoryExists(memoryName);\n\n\t\t// 2- Load memory data.\n\t\ts.start('Processing memory docs...');\n\t\tlet memoryFiles = await loadMemoryFiles(memoryName);\n\n\t\tif (memoryFiles.length === 0) {\n\t\t\tp.cancel(`No valid documents found in memory '${memoryName}'.`);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\t// 3- Get memory config.\n\t\tconst memoryConfig = await loadMemoryConfig(memoryName);\n\n\t\tlet filesToEmbed: string[] = [];\n\t\tlet filesToDelete: string[] = [];\n\n\t\tif (memoryConfig.git.enabled) {\n\t\t\tconst { filesToDeploy, filesToDelete: gitFilesToDelete } =\n\t\t\t\tawait handleGitSyncMemories({\n\t\t\t\t\tmemoryName: memoryName,\n\t\t\t\t\tconfig: memoryConfig\n\t\t\t\t});\n\n\t\t\tfilesToEmbed = filesToDeploy;\n\t\t\tfilesToDelete = gitFilesToDelete;\n\n\t\t\t// Filter memory files to emebed\n\t\t\tmemoryFiles = memoryFiles.filter(doc =>\n\t\t\t\tfilesToEmbed.includes(doc.name)\n\t\t\t);\n\t\t}\n\n\t\t// 4- Generate embeddings.\n\t\tlet embedResult = 'Embeddings updated.';\n\t\tif (memoryFiles && memoryFiles.length > 0) {\n\t\t\ts.message('Generating embeddings...');\n\t\t\tconst shouldOverwrite = memoryConfig.git.enabled ? true : overwrite;\n\t\t\tembedResult = await generateEmbeddings({\n\t\t\t\tmemoryFiles,\n\t\t\t\tmemoryName,\n\t\t\t\toverwrite: shouldOverwrite || false,\n\t\t\t\tuseLocalEmbeddings\n\t\t\t});\n\t\t}\n\n\t\tif (memoryConfig.git.enabled) {\n\t\t\tif (filesToDelete.length > 0) {\n\t\t\t\tawait deleteDocumentsFromDB({\n\t\t\t\t\tmemoryName,\n\t\t\t\t\tfilesToDelete\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait updateEmbeddedCommitHash(memoryName);\n\t\t\tp.log.info('Updated embedded commit hash.');\n\t\t\tp.log.success('Synced memory files with git repository.');\n\t\t}\n\n\t\ts.stop(embedResult);\n\t} catch (error: any) {\n\t\ts.stop(`Stopped!`);\n\t\tp.cancel(`FAILED: ${error.message}`);\n\t\tprocess.exit(1);\n\t}\n}\n\nexport async function deleteDocumentsFromDB({\n\tmemoryName,\n\tfilesToDelete\n}: {\n\tmemoryName: string;\n\tfilesToDelete: string[];\n}) {\n\tconst s = p.spinner();\n\ts.start('Detected files to delete. Deleting...');\n\n\ttry {\n\t\tconst memoryDb = await loadDb(memoryName);\n\n\t\tfor (const docName of filesToDelete) {\n\t\t\tif (memoryDb.data.documents[docName]) {\n\t\t\t\tawait deleteDocumentFromDB({ db: memoryDb, docName });\n\t\t\t\tp.log.info(`Deleted document: ${color.cyan(docName)}`);\n\t\t\t}\n\t\t}\n\n\t\ts.stop(`Documents deleted from memory ${memoryName}.`);\n\t} catch (error) {\n\t\ts.stop('Stopped!');\n\t\tif (error instanceof Error) {\n\t\t\tp.cancel(`Failed to delete documents: ${error.message}`);\n\t\t} else {\n\t\t\tp.cancel(`Failed to delete documents. An unknown error occurred.`);\n\t\t}\n\t\tprocess.exit(1);\n\t}\n}\n","import { heading } from '@/utils/heading';\nimport { isMemoryDocExist } from '@/utils/memory/check-memory-doc-exists';\nimport { generateEmbeddings } from '@/utils/memory/generate-embeddings';\nimport * as p from '@clack/prompts';\nimport color from 'picocolors';\n\nexport async function embedDoc({\n\tmemoryName,\n\tdocumentName,\n\toverwrite = false\n}: {\n\tmemoryName: string;\n\tdocumentName: string;\n\toverwrite?: boolean;\n}) {\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'EMBED DOC',\n\t\t\tsub: `Creating embeddings of Doc: ${color.cyan(documentName)} in memory ${color.cyan(memoryName)}`\n\t\t})\n\t);\n\n\t// Spinner to show current action.\n\tconst spinner = p.spinner();\n\n\ttry {\n\t\tconst { memoryFile, validMemoryName } = await isMemoryDocExist({\n\t\t\tspinner,\n\t\t\tmemoryName,\n\t\t\tdocumentName\n\t\t});\n\n\t\t// Generate embeddings.\n\t\tspinner.message('Generating embeddings...');\n\t\tconst result = await generateEmbeddings({\n\t\t\tmemoryFiles: [memoryFile],\n\t\t\tmemoryName: validMemoryName,\n\t\t\toverwrite: overwrite || false\n\t\t});\n\n\t\tspinner.stop(result);\n\t} catch (error: any) {\n\t\tspinner.stop(`FAILED from here: ${error.message}`);\n\t\tprocess.exit(1);\n\t}\n}\n","import path from 'path';\nimport fs from 'fs';\n\nexport async function getAvailableMemories() {\n\ttry {\n\t\t// Construct the path containing all memories folders.\n\t\tconst memoryPath = path.join(process.cwd(), 'baseai', 'memory');\n\n\t\t// Check if the baseai directory exists.\n\t\tif (!fs.existsSync(memoryPath)) return [];\n\n\t\t// Get all directories names in the memory path.\n\t\tconst memoryNames = await fs.promises.readdir(memoryPath);\n\n\t\t// Return the memory names.\n\t\treturn memoryNames;\n\t} catch (error: any) {\n\t\treturn [];\n\t}\n}\n","import { heading } from '@/utils/heading';\nimport icons from '@/utils/icons';\nimport { getAvailableMemories } from '@/utils/memory/get-available-memories';\nimport * as p from '@clack/prompts';\n\nexport async function listMemory() {\n\tconst availableMemories = await getAvailableMemories();\n\tif (availableMemories.length === 0) {\n\t\tp.log.message('No memory available.');\n\t\treturn;\n\t}\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'MEMORY',\n\t\t\tsub: 'List of all available memory sets'\n\t\t})\n\t);\n\tconsole.log('');\n\tavailableMemories.forEach(item => {\n\t\tconsole.log(`${icons.memory} ${item}`);\n\t});\n\n\tprocess.exit(0);\n}\n","import { heading } from '@/utils/heading';\nimport { checkMemoryExists } from '@/utils/memory/check-memory-exist';\nimport { MEMORYSETS } from '@/utils/memory/constants';\nimport {\n\tcosineSimilaritySearch,\n\tgetDocumentsFromMemory\n} from '@/utils/memory/db/lib';\nimport color from 'picocolors';\n// import { generateLocalEmbeddings } from '@/utils/memory/generate-local-embeddings';\nimport { getOpenAIEmbeddings } from '@/utils/memory/generate-openai-embeddings';\nimport { validateMemoryName } from '@/utils/memory/lib';\nimport * as p from '@clack/prompts';\nimport { generateLocalEmbeddings } from '@/utils/memory/generate-local-embeddings';\nimport { loadConfig } from '@/utils/config/config-handler';\nimport { dlog } from '@/dev/utils/dlog';\n\nexport async function retrieveMemory({\n\tmemory,\n\tquery\n}: {\n\tmemory: string;\n\tquery: string;\n}) {\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'RETRIEVE',\n\t\t\tsub: 'Retrieve similar chunks of a memory'\n\t\t})\n\t);\n\n\t// Spinner to show current action.\n\tconst spin = p.spinner();\n\n\ttry {\n\t\tif (!memory) {\n\t\t\tp.log.error(\n\t\t\t\t'Memory name is required. Use --memory or -m flag to specify.'\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tif (!query) {\n\t\t\tp.log.error(\n\t\t\t\t'Query is required. Use --query, or -q flag to specify.'\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\t// 1- Check memory exists.\n\t\tconst memoryName = validateMemoryName(memory); // Throws error if invalid so no need to check success\n\t\tawait checkMemoryExists(memoryName);\n\n\t\t// 2- Load memory data.\n\t\tspin.start('Processing memory data...');\n\t\tconst memoryChunks = await getDocumentsFromMemory([memory]);\n\t\tif (memoryChunks.length === 0)\n\t\t\treturn p.log.error(\n\t\t\t\t'Please make sure the memory has one or more documents and they are embedded.'\n\t\t\t);\n\n\t\t// 3- Generate embeddings of query\n\t\tspin.message('Generating embeddings...');\n\n\t\t// Read config to determine which embedding to use.\n\t\tconst config = await loadConfig();\n\t\tconst useLocalEmbeddings = config.memory?.useLocalEmbeddings || false;\n\n\t\tlet queryEmbedding = [];\n\t\tif (useLocalEmbeddings) {\n\t\t\t// Use local embeddings\n\t\t\tdlog('Generating local embeddings');\n\t\t\tqueryEmbedding = await generateLocalEmbeddings([query]);\n\t\t} else {\n\t\t\t// Use OpenAI embeddings\n\t\t\tdlog('Generating OpenAI embeddings');\n\t\t\tqueryEmbedding = await getOpenAIEmbeddings([query]);\n\t\t}\n\n\t\t// 4- Get similar chunks from the memorysets.\n\t\tspin.message('Searching for similar chunks...');\n\t\tconst similarChunks = cosineSimilaritySearch({\n\t\t\tchunks: memoryChunks,\n\t\t\tqueryEmbedding: queryEmbedding[0].embedding,\n\t\t\ttopK: MEMORYSETS.MAX_CHUNKS_ATTACHED_TO_LLM\n\t\t});\n\n\t\tif (similarChunks.length === 0)\n\t\t\treturn p.log.message('No similar chunks found.');\n\n\t\t// 5- Log the similar chunks\n\t\tp.log.info('Similar Chunks:');\n\t\tsimilarChunks.forEach((chunk, index) => {\n\t\t\tconst header = color.cyan(color.bold(`#${index + 1}`));\n\t\t\tconst similarity = `Similarity: ${color.green(chunk.similarity.toFixed(6))}`;\n\t\t\tconst source = `Source: ${chunk.attributes.docName}`;\n\t\t\tconst text = chunk.text;\n\n\t\t\tp.note(`${header}\\n${similarity}\\n${source}`);\n\t\t\tp.log.message(`${color.cyan(`Text Chunk:`)}\\n${text}\\n`);\n\t\t});\n\n\t\tp.outro('Memory retrieval completed successfully.');\n\t} catch (error: any) {\n\t\tp.cancel(`FAILED: ${error.message}`);\n\t} finally {\n\t\tspin.stop('Finished');\n\t}\n}\n","import { cyan, dim, dimItalic, lineItem } from '@/utils/formatting';\nimport { getAvailableTools } from '@/utils/get-available-tools';\nimport { heading } from '@/utils/heading';\nimport { defaultRagPrompt } from '@/utils/memory/constants';\nimport { getAvailableMemories } from '@/utils/memory/get-available-memories';\nimport { formatCode } from '@/utils/ts-format-code';\nimport * as p from '@clack/prompts';\nimport slugify from '@sindresorhus/slugify';\nimport camelCase from 'camelcase';\nimport figures from 'figures';\nimport fs from 'fs';\nimport path from 'path';\nimport { z } from 'zod';\n\ntype PipeStatus = 'public' | 'private';\n\nconst pipeNameSchema = z\n\t.string()\n\t.min(3, 'Pipe name must be at least 3 characters long')\n\t.max(50, 'Pipe name must not exceed 50 characters')\n\t.regex(\n\t\t/^[a-zA-Z0-9.-]+$/,\n\t\t'Pipe name can only contain letters, numbers, dots, and hyphens'\n\t);\n\nconst multiselectHelper = `${dimItalic(`(optional)`)} \\n${dimItalic(`${lineItem} Press ${cyan(`space`)} to select, ${cyan(`enter`)} to submit or skip`)}`;\n\nexport async function createPipe() {\n\tconst tools = await getAvailableTools();\n\tconst memories = await getAvailableMemories();\n\tconst hasTools = tools.length > 0;\n\tconst hasMemories = memories.length > 0;\n\n\tp.intro(heading({ text: 'PIPE', sub: 'Create a new agent pipe' }));\n\n\tconst pipeInfo = await p.group(\n\t\t{\n\t\t\tname: () =>\n\t\t\t\tp.text({\n\t\t\t\t\tmessage: 'Name of the pipe',\n\t\t\t\t\tplaceholder: 'ai-agent-pipe',\n\t\t\t\t\tvalidate: value => {\n\t\t\t\t\t\tconst result = pipeNameSchema.safeParse(value);\n\t\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\t\treturn result.error.issues[0].message;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\tdescription: () =>\n\t\t\t\tp.text({\n\t\t\t\t\tmessage: 'Description of the pipe',\n\t\t\t\t\tplaceholder: 'This is a test pipe'\n\t\t\t\t}),\n\t\t\tstatus: () =>\n\t\t\t\tp.select({\n\t\t\t\t\tmessage: 'Status of the pipe',\n\t\t\t\t\toptions: [\n\t\t\t\t\t\t{ value: 'public', label: 'Public' },\n\t\t\t\t\t\t{ value: 'private', label: 'Private' }\n\t\t\t\t\t]\n\t\t\t\t}) as Promise<PipeStatus>,\n\t\t\tsystemPrompt: () =>\n\t\t\t\tp.text({\n\t\t\t\t\tmessage: 'System prompt',\n\t\t\t\t\tplaceholder: 'You are a helpful AI assistant.',\n\t\t\t\t\tinitialValue: 'You are a helpful AI assistant.'\n\t\t\t\t}),\n\t\t\t...(hasMemories && {\n\t\t\t\tmemory: async () =>\n\t\t\t\t\tp.multiselect({\n\t\t\t\t\t\tmessage: `Select memory for this pipe ${multiselectHelper}`,\n\t\t\t\t\t\toptions: memories.map(memoryName => ({\n\t\t\t\t\t\t\tvalue: memoryName,\n\t\t\t\t\t\t\tlabel: memoryName\n\t\t\t\t\t\t})),\n\t\t\t\t\t\trequired: false\n\t\t\t\t\t})\n\t\t\t}),\n\t\t\t...(hasTools && {\n\t\t\t\ttools: async () =>\n\t\t\t\t\tp.multiselect({\n\t\t\t\t\t\tmessage: `Select tools for this pipe ${multiselectHelper}`,\n\t\t\t\t\t\toptions: tools.map(tool => ({\n\t\t\t\t\t\t\tvalue: tool,\n\t\t\t\t\t\t\tlabel: tool\n\t\t\t\t\t\t})),\n\t\t\t\t\t\trequired: false\n\t\t\t\t\t})\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\tonCancel: () => {\n\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t);\n\n\tlet selectedTools = ``;\n\tlet toolNames: string[] = [];\n\n\t// If the user selected tools, add them to the pipe content\n\tconst pipeTools = pipeInfo.tools;\n\tif (pipeTools) {\n\t\tpipeTools.map(tool => {\n\t\t\tconst name = `${camelCase(tool as string)}Tool`;\n\t\t\ttoolNames.push(`${name}()`);\n\t\t\tselectedTools += `\\nimport ${name} from '../tools/${tool}';`;\n\t\t});\n\t}\n\n\tlet selectedMemories = ``;\n\tlet selectedMemoriesNames: string[] = [];\n\n\t// If the user selected memories, add them to the pipe content\n\tconst pipeMemories = pipeInfo.memory;\n\tif (pipeMemories) {\n\t\tpipeMemories.map(memory => {\n\t\t\tconst name = `${camelCase(memory as string)}Memory`;\n\t\t\tselectedMemoriesNames.push(\n\t\t\t\t`${camelCase(memory as string)}Memory()`\n\t\t\t);\n\t\t\tselectedMemories += `\\nimport ${name} from '../memory/${memory}';`;\n\t\t});\n\t}\n\n\tconst isMemoryAttached = selectedMemoriesNames.length > 0;\n\n\tconst pipeNameSlugified = slugify(pipeInfo.name);\n\tconst pipeNameCamelCase = camelCase('pipe-' + pipeInfo.name);\n\tconst pipeContent = `import { PipeI } from '@baseai/core';${selectedTools}${selectedMemories}\n\nconst ${pipeNameCamelCase} = (): PipeI => ({\n    // Replace with your API key https://langbase.com/docs/api-reference/api-keys\n\tapiKey: process.env.LANGBASE_API_KEY!,\n    name: '${pipeNameSlugified}',\n    description: ${JSON.stringify(pipeInfo.description) || ''},\n    status: '${pipeInfo.status}',\n    model: 'openai:gpt-4o-mini',\n    stream: true,\n    json: false,\n    store: true,\n    moderate: true,\n    top_p: 1,\n    max_tokens: 1000,\n    temperature: 0.7,\n    presence_penalty: 1,\n    frequency_penalty: 1,\n    stop: [],\n    tool_choice: 'auto',\n    parallel_tool_calls: true,\n    messages: [\n        { role: 'system', content: \\`${pipeInfo.systemPrompt}\\` },\n        ${\n\t\t\tisMemoryAttached\n\t\t\t\t? `{ role: 'system', name: 'rag', content: \"${defaultRagPrompt.replace(/\\n/g, '\\\\n')}\" }`\n\t\t\t\t: ''\n\t\t}\n    ],\n    variables: [],\n    memory: [${selectedMemoriesNames.join(', ')}],\n    tools: [${toolNames.join(', ')}],\n});\n\nexport default ${pipeNameCamelCase};\n    `;\n\n\tconst formattedCode = await formatCode(pipeContent);\n\n\tconst baseDir = path.join(process.cwd(), 'baseai', 'pipes');\n\tconst filePath = path.join(baseDir, `${pipeNameSlugified}.ts`);\n\n\ttry {\n\t\tawait fs.promises.mkdir(baseDir, { recursive: true });\n\t\tawait fs.promises.writeFile(filePath, formattedCode);\n\t\tp.outro(\n\t\t\theading({\n\t\t\t\ttext: pipeNameCamelCase,\n\t\t\t\tsub: `created as a new pipe \\n ${dim(figures.pointer)} ${dimItalic(` ${filePath}`)}`,\n\t\t\t\tgreen: true\n\t\t\t})\n\t\t);\n\t\tprocess.exit(0);\n\t} catch (error: any) {\n\t\tp.cancel(`Error creating pipe: ${error.message}`);\n\t\tprocess.exit(1);\n\t}\n}\n","import { getAvailableTools } from '@/utils/get-available-tools';\nimport { heading } from '@/utils/heading';\nimport { isToolPresent } from '@/utils/is-tool-present';\nimport { formatCode } from '@/utils/ts-format-code';\nimport * as p from '@clack/prompts';\nimport slugify from '@sindresorhus/slugify';\nimport camelCase from 'camelcase';\nimport figures from 'figures';\nimport fs from 'fs';\nimport path from 'path';\nimport color from 'picocolors';\nimport { z } from 'zod';\n\nconst defaultTool = {\n\ttype: 'function',\n\tfunction: {\n\t\tname: 'get_current_weather',\n\t\tdescription: 'Get the current weather in a given location',\n\t\tparameters: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tlocation: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'The city and state, e.g. San Francisco, CA'\n\t\t\t\t},\n\t\t\t\tunit: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tenum: ['celsius', 'fahrenheit']\n\t\t\t\t}\n\t\t\t},\n\t\t\trequired: ['location']\n\t\t}\n\t}\n};\n\nconst toolNameSchema = z\n\t.string()\n\t.min(3, 'Tool name must be at least 3 characters long')\n\t.max(50, 'Tool name must not exceed 50 characters');\n\n/**\n * Asynchronously creates a new tool by prompting the user for tool details,\n * validates the input, and generates a new tool file with the provided information.\n *\n * @async\n * @function\n * @returns {Promise<void>} A promise that resolves when the tool is created successfully.\n *\n * @throws Will throw an error if there is an issue creating the tool file.\n */\nexport async function createTool() {\n\tconst allTools = await getAvailableTools();\n\tp.intro(heading({ text: 'TOOL', sub: 'Create a new tool' }));\n\n\tconst toolInfo = await p.group(\n\t\t{\n\t\t\tname: () =>\n\t\t\t\tp.text({\n\t\t\t\t\tmessage: 'Name of the tool',\n\t\t\t\t\tplaceholder: defaultTool.function.name,\n\t\t\t\t\tvalidate: value => {\n\t\t\t\t\t\tconst result = toolNameSchema.safeParse(value);\n\t\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\t\treturn result.error.issues[0].message;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst hasTool = isToolPresent({\n\t\t\t\t\t\t\tname: value,\n\t\t\t\t\t\t\tallTools\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (hasTool) {\n\t\t\t\t\t\t\treturn `Tool with name ${value} already exists!`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\tdescription: () =>\n\t\t\t\tp.text({\n\t\t\t\t\tmessage: 'Description of the tool',\n\t\t\t\t\tplaceholder: defaultTool.function.description,\n\t\t\t\t\tvalidate(value) {\n\t\t\t\t\t\tif (value.length === 0)\n\t\t\t\t\t\t\treturn `Tool description is required!`;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t},\n\t\t{\n\t\t\tonCancel: () => {\n\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t);\n\n\tconst slugifiedName = slugify(toolInfo.name);\n\tconst camelCaseNameToolName = camelCase('tool-' + toolInfo.name);\n\tconst camelCaseNameFnName = camelCase(toolInfo.name);\n\tconst description = toolInfo.description || '';\n\n\tconst toolContent = `import { ToolI } from '@baseai/core';\n\nexport async function ${camelCaseNameFnName}() {\n\t// Add your tool logic here\n\t// This function will be called when the tool is executed\n}\n\nconst ${camelCaseNameToolName} = (): ToolI => ({\n\trun: ${camelCaseNameFnName},\n\ttype: 'function' as const,\n\tfunction: {\n\t\tname: '${camelCaseNameToolName}',\n\t\tdescription: ${JSON.stringify(description) || ''},\n\t\tparameters: {},\n\t},\n});\n\nexport default ${camelCaseNameToolName};\n`;\n\n\tconst baseDir = path.join(process.cwd(), 'baseai', 'tools');\n\tconst filePath = path.join(baseDir, `${slugifiedName}.ts`);\n\tconst formattedCode = await formatCode(toolContent);\n\n\ttry {\n\t\tawait fs.promises.mkdir(baseDir, { recursive: true });\n\t\tawait fs.promises.writeFile(filePath, formattedCode);\n\n\t\tp.outro(\n\t\t\theading({\n\t\t\t\ttext: camelCaseNameToolName,\n\t\t\t\tsub: `created as a new tool \\n ${color.dim(`${figures.pointer} ${filePath}`)}`,\n\t\t\t\tgreen: true\n\t\t\t})\n\t\t);\n\t\tprocess.exit(0);\n\t} catch (error: any) {\n\t\tp.cancel(`Error creating tool: ${error.message}`);\n\t\tprocess.exit(1);\n\t}\n}\n","import meowHelp from 'cli-meow-help';\nimport meow from 'meow';\n\nconst flags = {\n\tclear: {\n\t\ttype: `boolean`,\n\t\tdefault: false,\n\t\tdesc: `Clear the console`\n\t},\n\tdebug: {\n\t\ttype: `boolean`,\n\t\tdefault: false,\n\t\tshortFlag: `d`,\n\t\tdesc: `Print debug info`\n\t},\n\tmemory: {\n\t\ttype: `string`,\n\t\tshortFlag: `m`,\n\t\tdesc: `Memory to use` // For embed as well as retrieve\n\t},\n\toverwrite: {\n\t\ttype: `boolean`,\n\t\tshortFlag: `o`,\n\t\tdesc: `Overwrite existing memory embeddings`\n\t},\n\tdocument: {\n\t\ttype: `string`,\n\t\tshortFlag: `d`,\n\t\tdesc: `Document to embed` // For embedding a single document.\n\t},\n\tquery: {\n\t\ttype: `string`,\n\t\tshortFlag: `q`,\n\t\tdesc: `Query string`\n\t},\n\tlist: {\n\t\ttype: `boolean`,\n\t\tshortFlag: `l`,\n\t\tdesc: `List available memory`\n\t},\n\tlocal: {\n\t\ttype: `boolean`,\n\t\tshortFlag: `L`,\n\t\tdesc: `Set use local embeddings (true/false)`\n\t}\n};\n\nconst commands = {\n\tdev: { desc: `Run BaseAI in dev mode` },\n\tauth: { desc: `Authenticate with Langbase` },\n\tadd: { desc: `Add an agent Pipe from Langbase` },\n\tdeploy: { desc: `Deploy BaseAI to Langbase` },\n\tpipe: { desc: `Create a pipe` },\n\ttool: { desc: `Create a tool` },\n\tmemory: { desc: `Create a memory` },\n\tembed: { desc: `Create embeddings of a memory` },\n\tretrieve: { desc: `Retrieve similar chunks of a memory` },\n\tconfig: {\n\t\tdesc: `Configure BaseAI`,\n\t\tsubcommands: {\n\t\t\tembeddings: {\n\t\t\t\tdesc: `Enable or disable local embeddings`\n\t\t\t}\n\t\t}\n\t},\n\tbuild: { desc: `Build BaseAI files` },\n\tinit: { desc: `Set up BaseAI files and add packages` },\n\thelp: { desc: `Print help info` }\n};\n\nconst helpText = meowHelp({\n\tname: `baseai`,\n\tflags,\n\tcommands,\n\tdesc: false,\n\theader: false,\n\tfooter: `Made by Langbase. For more https://langbase.com/docs`\n});\n\nconst options = {\n\timportMeta: import.meta,\n\tinferType: true,\n\tdescription: false,\n\thardRejection: false,\n\tflags\n};\n\nexport default meow(helpText, options);\n","import * as p from '@clack/prompts';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport { heading } from '../heading';\nimport { getAvailableMemories } from '../memory/get-available-memories';\nimport { embedMemory } from '@/memory/embed';\n\nconst configDir = path.join(process.cwd(), 'baseai');\nconst configFilePath = path.join(configDir, 'baseai.config.ts');\n\nexport async function setLocalEmbeddingsConfig(value: boolean) {\n\ttry {\n\t\tp.intro(heading({ text: 'CONFIG', sub: 'Configure embeddings' }));\n\n\t\t// Read the config file content\n\t\tconst configContent = await fs.readFile(configFilePath, 'utf-8');\n\n\t\t// Extract the current value of useLocalEmbeddings\n\t\tconst match = configContent.match(\n\t\t\t/([\"']?useLocalEmbeddings[\"']?\\s*:\\s*)(true|false)/\n\t\t);\n\t\tif (!match) {\n\t\t\tconsole.log('useLocalEmbeddings not found in the config file.');\n\t\t\treturn null;\n\t\t}\n\n\t\tconst oldValue = match[2] === 'true';\n\n\t\t// Update the useLocalEmbeddings value using regex\n\t\tconst updatedContent = configContent.replace(\n\t\t\t/([\"']?useLocalEmbeddings[\"']?\\s*:\\s*)(true|false)/,\n\t\t\t`$1${value}`\n\t\t);\n\n\t\t// Write the updated content back to the config file\n\t\tawait fs.writeFile(configFilePath, updatedContent.trim());\n\n\t\t// Check if the new value is different from the old value\n\t\tconst isNewAndOldValueSame = value === oldValue;\n\n\t\t// If the new value is the same as the old value, log a message and return\n\t\tif (isNewAndOldValueSame) {\n\t\t\tconsole.log(`\\nuseLocalEmbeddings is already set to ${value}.\\n`);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the new and old are different, log a message and update the memory embeddings\n\t\tconsole.log(\n\t\t\t`\\nUpdated useLocalEmbeddings to ${value} successfully in ${configFilePath}`\n\t\t);\n\n\t\tconst oldModel = oldValue === true ? 'local Ollama' : 'OpenAI';\n\t\tconst newModel = value === true ? 'local Ollama' : 'OpenAI';\n\n\t\tp.log.info(\n\t\t\t`\\nSwitching from ${oldModel} embeddings to ${newModel} embeddings.\\n`\n\t\t);\n\n\t\t// Get all memory.\n\t\tconst memories = await getAvailableMemories();\n\n\t\t// Embed all memories\n\t\tfor (const memory of memories) {\n\t\t\tawait embedMemory({\n\t\t\t\tmemoryName: memory,\n\t\t\t\toverwrite: true,\n\t\t\t\tuseLocalEmbeddings: value\n\t\t\t});\n\t\t}\n\n\t\t// Log a note that users should restart dev server\n\t\tp.log.info(\n\t\t\t'Please restart the dev server to apply the changes to the memory embeddings configuration.'\n\t\t);\n\t} catch (error: any) {\n\t\tconsole.error(`Error updating useLocalEmbeddings: ${error.message}`);\n\t}\n}\n","import * as p from '@clack/prompts';\nimport { heading } from './heading';\n\nexport default function debugMode(cli: any) {\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'DEBUG MODE',\n\t\t\tsub: 'logs will be verbose...',\n\t\t\tdim: true\n\t\t})\n\t);\n\tconsole.log();\n\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'cwd',\n\t\t\tdim: true\n\t\t})\n\t);\n\tconsole.log(process.cwd());\n\tconsole.log();\n\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'cli.flags',\n\t\t\tdim: true\n\t\t})\n\t);\n\tconsole.log(cli.flags);\n\tconsole.log();\n\n\tp.intro(\n\t\theading({\n\t\t\ttext: 'cli.input',\n\t\t\tsub: 'commands',\n\t\t\tdim: true\n\t\t})\n\t);\n\tconsole.log(cli.input);\n\tconsole.log();\n}\n","import unhandled from 'cli-handle-unhandled';\nimport welcome from 'cli-welcome';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport fs from 'fs';\n\nexport default async ({ clear = false }) => {\n\tunhandled();\n\n\t// Get the directory of the current module\n\tconst __filename = fileURLToPath(import.meta.url);\n\tconst __dirname = path.dirname(__filename);\n\n\t// Go up two levels to find the package.json\n\tconst pkgJsonPath = path.join(__dirname, '..', 'package.json');\n\n\tif (!fs.existsSync(pkgJsonPath)) {\n\t\tconsole.error('Unable to find package.json');\n\t\tprocess.exit(1);\n\t}\n\n\tconst pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));\n\n\tawait welcome({\n\t\ttitle: `baseai`,\n\t\ttagLine: `by Langbase`,\n\t\tdescription: pkgJson.description,\n\t\tversion: pkgJson.version,\n\t\tbgColor: '#A699EA',\n\t\tcolor: '#000000',\n\t\tbold: true,\n\t\tclear\n\t});\n};\n"]}