( model: string, promptTokens = 0, completionTokens = 0, useCachedInput = false, inputMultiplier?: number, outputMultiplier?: number )
| 695 | * @returns Cost calculation results with input, output and total costs |
| 696 | */ |
| 697 | export function calculateCost( |
| 698 | model: string, |
| 699 | promptTokens = 0, |
| 700 | completionTokens = 0, |
| 701 | useCachedInput = false, |
| 702 | inputMultiplier?: number, |
| 703 | outputMultiplier?: number |
| 704 | ) { |
| 705 | let pricing = getEmbeddingModelPricing(model) |
| 706 | |
| 707 | if (!pricing) { |
| 708 | pricing = getModelPricingFromDefinitions(model) |
| 709 | } |
| 710 | |
| 711 | if (!pricing) { |
| 712 | const defaultPricing = { |
| 713 | input: 1.0, |
| 714 | cachedInput: 0.5, |
| 715 | output: 5.0, |
| 716 | updatedAt: '2025-03-21', |
| 717 | } |
| 718 | return { |
| 719 | input: 0, |
| 720 | output: 0, |
| 721 | total: 0, |
| 722 | pricing: defaultPricing, |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | const inputCost = |
| 727 | promptTokens * |
| 728 | (useCachedInput && pricing.cachedInput |
| 729 | ? pricing.cachedInput / 1_000_000 |
| 730 | : pricing.input / 1_000_000) |
| 731 | |
| 732 | const outputCost = completionTokens * (pricing.output / 1_000_000) |
| 733 | const finalInputCost = inputCost * (inputMultiplier ?? 1) |
| 734 | const finalOutputCost = outputCost * (outputMultiplier ?? 1) |
| 735 | const finalTotalCost = finalInputCost + finalOutputCost |
| 736 | |
| 737 | return { |
| 738 | input: Number.parseFloat(finalInputCost.toFixed(8)), |
| 739 | output: Number.parseFloat(finalOutputCost.toFixed(8)), |
| 740 | total: Number.parseFloat(finalTotalCost.toFixed(8)), |
| 741 | pricing, |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | /** |
| 746 | * Recursively enforces OpenAI strict-mode requirements on a JSON schema: |
no test coverage detected