{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Copyright 2024 The Fire Company\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ActionMetadata } from 'genkit';\nimport { ResolvableAction, genkitPluginV2 } from 'genkit/plugin';\nimport { ActionType } from 'genkit/registry';\nimport OpenAI, { type ClientOptions } from 'openai';\nimport { compatOaiModelRef, defineCompatOpenAIModel } from './model.js';\nimport { toModelName } from './utils.js';\n\nexport {\n  SpeechConfigSchema,\n  TranscriptionConfigSchema,\n  compatOaiSpeechModelRef,\n  compatOaiTranscriptionModelRef,\n  defineCompatOpenAISpeechModel,\n  defineCompatOpenAITranscriptionModel,\n  type SpeechRequestBuilder,\n  type TranscriptionRequestBuilder,\n} from './audio.js';\nexport { defineCompatOpenAIEmbedder } from './embedder.js';\nexport {\n  ImageGenerationCommonConfigSchema,\n  compatOaiImageModelRef,\n  defineCompatOpenAIImageModel,\n  type ImageRequestBuilder,\n} from './image.js';\nexport {\n  ChatCompletionCommonConfigSchema,\n  compatOaiModelRef,\n  defineCompatOpenAIModel,\n  openAIModelRunner,\n  type ModelRequestBuilder,\n} from './model.js';\nexport {\n  TranslationConfigSchema,\n  compatOaiTranslationModelRef,\n  defineCompatOpenAITranslationModel,\n  type TranslationRequestBuilder,\n} from './translate.js';\n\nexport interface PluginOptions extends Partial<Omit<ClientOptions, 'apiKey'>> {\n  apiKey?: ClientOptions['apiKey'] | false;\n  name: string;\n  initializer?: (client: OpenAI) => Promise<ResolvableAction[]>;\n  resolver?: (\n    client: OpenAI,\n    actionType: ActionType,\n    actionName: string\n  ) => Promise<ResolvableAction | undefined> | ResolvableAction | undefined;\n  listActions?: (client: OpenAI) => Promise<ActionMetadata[]>;\n}\n\n/**\n * This module provides the `openAICompatible` plugin factory for Genkit. It\n * enables interaction with OpenAI-compatible API endpoints, allowing users to\n * leverage various AI models by configuring API keys and other client options.\n *\n * The core export is `openAICompatible`, a function that accepts\n * `PluginOptions` and returns a Genkit plugin.\n *\n * Key `PluginOptions` include:\n *  - `name`: A string to uniquely identify this plugin instance\n *    (e.g., 'deepSeek', 'customOpenAI').\n *  - `apiKey`: The API key for the service. If not provided directly, the\n *    plugin will attempt to use the `OPENAI_API_KEY` environment variable.\n *  - `initializer`: An optional asynchronous function for custom setup after\n *    the OpenAI client is initialized. It receives the Genkit instance and the\n *    OpenAI client.\n *  - Additional properties from OpenAI's `ClientOptions` (like `baseURL`,\n *    `timeout`, etc.) can be passed to customize the OpenAI client.\n *\n * The returned plugin initializes an OpenAI client tailored to the provided\n * options, making configured models available for use within Genkit flows.\n *\n * @param {PluginOptions} options - Configuration options for the plugin.\n * @returns A Genkit plugin configured for an OpenAI-compatible service.\n *\n * Usage: Import `openAICompatible` (or your chosen import name for the default\n * export) from this package (e.g., `genkitx-openai`). Then, invoke it within\n * the `plugins` array of `configureGenkit`, providing the necessary\n * `PluginOptions`.\n *\n * Example:\n * ```typescript\n * import myOpenAICompatiblePlugin from 'genkitx-openai'; // Default import\n *\n * export default configureGenkit({\n *  plugins: [\n *    myOpenAICompatiblePlugin({\n *      name: 'gpt4o', // Name for this specific plugin configuration\n *      apiKey: process.env.OPENAI_API_KEY,\n *      // For a non-OpenAI compatible endpoint:\n *      // baseURL: 'https://api.custom-llm-provider.com/v1',\n *    }),\n *    myOpenAICompatiblePlugin({\n *      name: 'localLlama',\n *      apiKey: 'ollama', // Or specific key if required by local server\n *      baseURL: 'http://localhost:11434/v1', // Example for Ollama\n *    }),\n *    // ... other plugins\n *  ],\n * });\n * ```\n */\nexport const openAICompatible = (options: PluginOptions) => {\n  let listActionsCache;\n  var client: OpenAI;\n  function createClient() {\n    if (client) return client;\n    const { apiKey, ...restofOptions } = options;\n    client = new OpenAI({\n      ...restofOptions,\n      apiKey: apiKey === false ? 'placeholder' : apiKey,\n    });\n    return client;\n  }\n  return genkitPluginV2({\n    name: options.name,\n    async init() {\n      if (!options.initializer) {\n        return [];\n      }\n      return await options.initializer(createClient());\n    },\n    async resolve(actionType: ActionType, actionName: string) {\n      if (options.resolver) {\n        return await options.resolver(createClient(), actionType, actionName);\n      } else {\n        if (actionType === 'model') {\n          return defineCompatOpenAIModel({\n            name: toModelName(actionName, options.name),\n            client: createClient(),\n            pluginOptions: options,\n            modelRef: compatOaiModelRef({\n              name: actionName,\n              namespace: options.name,\n            }),\n          });\n        }\n        return undefined;\n      }\n    },\n    list:\n      // Don't attempt to list models if apiKey set to false\n      options.listActions && options.apiKey !== false\n        ? async () => {\n            if (listActionsCache) return listActionsCache;\n            listActionsCache = await options.listActions!(createClient());\n            return listActionsCache;\n          }\n        : undefined,\n  });\n};\n\nexport default openAICompatible;\n"],"mappings":"AAiBA,SAA2B,sBAAsB;AAEjD,OAAO,YAAoC;AAC3C,SAAS,mBAAmB,+BAA+B;AAC3D,SAAS,mBAAmB;AAE5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,kCAAkC;AAC3C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA,qBAAAA;AAAA,EACA,2BAAAC;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAkEA,MAAM,mBAAmB,CAAC,YAA2B;AAC1D,MAAI;AACJ,MAAI;AACJ,WAAS,eAAe;AACtB,QAAI,OAAQ,QAAO;AACnB,UAAM,EAAE,QAAQ,GAAG,cAAc,IAAI;AACrC,aAAS,IAAI,OAAO;AAAA,MAClB,GAAG;AAAA,MACH,QAAQ,W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