MCPcopy
hub / github.com/QuantumNous/new-api / convertOpenRouterToRatioData

Function convertOpenRouterToRatioData

controller/ratio_sync.go:724–807  ·  view source on GitHub ↗

convertOpenRouterToRatioData parses OpenRouter's /v1/models response and converts per-token USD pricing into the local ratio format. model_ratio = prompt_price_per_token * 1_000_000 * (USD / 1000) since 1 ratio unit = $0.002/1K tokens and USD=500, the factor is 500_000 completion_ratio = completi

(reader io.Reader)

Source from the content-addressed store, hash-verified

722//
723// completion_ratio = completion_price / prompt_price (output/input multiplier)
724func convertOpenRouterToRatioData(reader io.Reader) (map[string]any, error) {
725 var orResp struct {
726 Data []struct {
727 ID string `json:"id"`
728 Pricing struct {
729 Prompt string `json:"prompt"`
730 Completion string `json:"completion"`
731 InputCacheRead string `json:"input_cache_read"`
732 } `json:"pricing"`
733 } `json:"data"`
734 }
735
736 if err := common.DecodeJson(reader, &orResp); err != nil {
737 return nil, fmt.Errorf("failed to decode OpenRouter response: %w", err)
738 }
739
740 modelRatioMap := make(map[string]any)
741 completionRatioMap := make(map[string]any)
742 cacheRatioMap := make(map[string]any)
743
744 for _, m := range orResp.Data {
745 promptPrice, promptErr := strconv.ParseFloat(m.Pricing.Prompt, 64)
746 completionPrice, compErr := strconv.ParseFloat(m.Pricing.Completion, 64)
747
748 if promptErr != nil && compErr != nil {
749 // Both unparseable — skip this model
750 continue
751 }
752
753 // Treat parse errors as 0
754 if promptErr != nil {
755 promptPrice = 0
756 }
757 if compErr != nil {
758 completionPrice = 0
759 }
760
761 // Negative values are sentinel values (e.g., -1 for dynamic/variable pricing) — skip
762 if promptPrice < 0 || completionPrice < 0 {
763 continue
764 }
765
766 if promptPrice == 0 && completionPrice == 0 {
767 // Free model
768 modelRatioMap[m.ID] = 0.0
769 continue
770 }
771 if promptPrice <= 0 {
772 // No meaningful prompt baseline, cannot derive ratios safely.
773 continue
774 }
775
776 // Normal case: promptPrice > 0
777 ratio := promptPrice * 1000 * ratio_setting.USD
778 ratio = roundRatioValue(ratio)
779 modelRatioMap[m.ID] = ratio
780
781 compRatio := completionPrice / promptPrice

Callers 1

FetchUpstreamRatiosFunction · 0.85

Calls 2

DecodeJsonFunction · 0.92
roundRatioValueFunction · 0.85

Tested by

no test coverage detected