| 1 | // Copyright 2023 Lance Developers. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | import { type EmbeddingFunction } from '../index' |
| 16 | import type OpenAI from 'openai' |
| 17 | |
| 18 | export class OpenAIEmbeddingFunction implements EmbeddingFunction<string> { |
| 19 | private readonly _openai: OpenAI |
| 20 | private readonly _modelName: string |
| 21 | |
| 22 | constructor (sourceColumn: string, openAIKey: string, modelName: string = 'text-embedding-ada-002') { |
| 23 | /** |
| 24 | * @type {import("openai").default} |
| 25 | */ |
| 26 | let Openai |
| 27 | try { |
| 28 | // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 29 | Openai = require('openai') |
| 30 | } catch { |
| 31 | throw new Error('please install openai@^4.24.1 using npm install openai') |
| 32 | } |
| 33 | |
| 34 | this.sourceColumn = sourceColumn |
| 35 | const configuration = { |
| 36 | apiKey: openAIKey |
| 37 | } |
| 38 | |
| 39 | this._openai = new Openai(configuration) |
| 40 | this._modelName = modelName |
| 41 | } |
| 42 | |
| 43 | async embed (data: string[]): Promise<number[][]> { |
| 44 | const response = await this._openai.embeddings.create({ |
| 45 | model: this._modelName, |
| 46 | input: data |
| 47 | }) |
| 48 | |
| 49 | const embeddings: number[][] = [] |
| 50 | for (let i = 0; i < response.data.length; i++) { |
| 51 | embeddings.push(response.data[i].embedding) |
| 52 | } |
| 53 | return embeddings |
| 54 | } |
| 55 | |
| 56 | sourceColumn: string |
| 57 | } |