|
| 1 | +import OpenAI from 'openai' |
| 2 | +import { Stream } from 'openai/streaming' |
| 3 | + |
| 4 | +import { |
| 5 | + CompletionParams, |
| 6 | + OpenAICompatibleModel, |
| 7 | + ProviderCompletionParams, |
| 8 | +} from '../chat/index.js' |
| 9 | +import { |
| 10 | + CompletionResponse, |
| 11 | + StreamCompletionResponse, |
| 12 | +} from '../userTypes/index.js' |
| 13 | +import { BaseHandler } from './base.js' |
| 14 | +import { InputError } from './types.js' |
| 15 | + |
| 16 | +async function* streamOpenAI( |
| 17 | + response: Stream<OpenAI.Chat.Completions.ChatCompletionChunk> |
| 18 | +): StreamCompletionResponse { |
| 19 | + for await (const chunk of response) { |
| 20 | + yield chunk |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +// To support a new provider, we just create a handler for them extending the BaseHandler class and implement the create method. |
| 25 | +// Then we update the Handlers object in src/handlers/utils.ts to include the new handler. |
| 26 | +export class OpenAICompatibleHandler extends BaseHandler<OpenAICompatibleModel> { |
| 27 | + protected validateInputs(body: CompletionParams): void { |
| 28 | + super.validateInputs(body) |
| 29 | + |
| 30 | + if (!this.opts.baseURL) { |
| 31 | + throw new InputError( |
| 32 | + 'No baseURL option provided for openai compatible provider. You must define a baseURL option to use a generic openai compatible API with Token.js' |
| 33 | + ) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + async create( |
| 38 | + body: ProviderCompletionParams<'openai'> |
| 39 | + ): Promise<CompletionResponse | StreamCompletionResponse> { |
| 40 | + this.validateInputs(body) |
| 41 | + |
| 42 | + // Uses the OPENAI_API_KEY environment variable, if the apiKey is not provided. |
| 43 | + // This makes the UX better for switching between providers because you can just |
| 44 | + // define all the environment variables and then change the model field without doing anything else. |
| 45 | + const apiKey = this.opts.apiKey ?? process.env.OPENAI_COMPATIBLE_API_KEY |
| 46 | + const openai = new OpenAI({ |
| 47 | + ...this.opts, |
| 48 | + apiKey, |
| 49 | + }) |
| 50 | + |
| 51 | + // We have to delete the provider field because it's not a valid parameter for the OpenAI API. |
| 52 | + const params: any = body |
| 53 | + delete params.provider |
| 54 | + |
| 55 | + if (body.stream) { |
| 56 | + const stream = await openai.chat.completions.create(body) |
| 57 | + return streamOpenAI(stream) |
| 58 | + } else { |
| 59 | + return openai.chat.completions.create(body) |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments