ai-utils.js
Version:
Build AI applications, chatbots, and agents with JavaScript and TypeScript.
68 lines (67 loc) • 2.56 kB
JavaScript
import { calculateOpenAIImageGenerationCostInMillicents, } from "./OpenAIImageGenerationModel.js";
import { calculateOpenAIEmbeddingCostInMillicents, isOpenAIEmbeddingModel, } from "./OpenAITextEmbeddingModel.js";
import { calculateOpenAITextGenerationCostInMillicents, isOpenAITextGenerationModel, } from "./OpenAITextGenerationModel.js";
import { calculateOpenAITranscriptionCostInMillicents, } from "./OpenAITranscriptionModel.js";
import { calculateOpenAIChatCostInMillicents, isOpenAIChatModel, } from "./chat/OpenAIChatModel.js";
export class OpenAICostCalculator {
constructor() {
Object.defineProperty(this, "provider", {
enumerable: true,
configurable: true,
writable: true,
value: "openai"
});
}
async calculateCostInMillicents(call) {
const type = call.type;
const model = call.model.modelName;
switch (type) {
case "image-generation": {
return calculateOpenAIImageGenerationCostInMillicents({
settings: call.settings,
});
}
case "text-embedding": {
if (model == null) {
return null;
}
if (isOpenAIEmbeddingModel(model)) {
return calculateOpenAIEmbeddingCostInMillicents({
model,
responses: call.response,
});
}
break;
}
case "json-generation":
case "text-generation": {
if (model == null) {
return null;
}
if (isOpenAIChatModel(model)) {
return calculateOpenAIChatCostInMillicents({
model,
response: call.response,
});
}
if (isOpenAITextGenerationModel(model)) {
return calculateOpenAITextGenerationCostInMillicents({
model,
response: call.response,
});
}
break;
}
case "transcription": {
if (model == null) {
return null;
}
return calculateOpenAITranscriptionCostInMillicents({
model: model,
response: call.response,
});
}
}
return null;
}
}