11import { NextResponse } from "next/server" ;
22import { cookies } from "next/headers" ;
3- import { inArray } from "drizzle-orm" ;
3+ import { inArray , desc } from "drizzle-orm" ;
44import { config } from "@/lib/config" ;
55import { db } from "@/lib/db/client" ;
6- import { modelPrices } from "@/lib/db/schema" ;
6+ import { modelPrices , usageRecords } from "@/lib/db/schema" ;
77
88export const runtime = "nodejs" ;
99
@@ -83,12 +83,6 @@ export async function POST(request: Request) {
8383 syncInFlight = true ;
8484 syncStartedAt = now ;
8585
86- // 使用服务端配置的 API Key,而不是客户端传入
87- const apiKey = config . cliproxy . apiKey ;
88- if ( ! apiKey ) {
89- return NextResponse . json ( { error : "服务端未配置 CLIPROXY_SECRET_KEY" } , { status : 500 } ) ;
90- }
91-
9286 if ( ! config . cliproxy . baseUrl ) {
9387 return NextResponse . json ( { error : "服务端未配置 CLIPROXY_API_BASE_URL" } , { status : 500 } ) ;
9488 }
@@ -97,6 +91,19 @@ export async function POST(request: Request) {
9791 return NextResponse . json ( { error : "服务端未配置 DATABASE_URL" } , { status : 500 } ) ;
9892 }
9993
94+ // 从数据库获取最新的 route 值作为 API Key
95+ const latestRecord = await db
96+ . select ( { route : usageRecords . route } )
97+ . from ( usageRecords )
98+ . orderBy ( desc ( usageRecords . id ) )
99+ . limit ( 1 ) ;
100+
101+ if ( ! latestRecord . length || ! latestRecord [ 0 ] . route ) {
102+ return NextResponse . json ( { error : "数据库中没有可用的 API Key 记录" } , { status : 500 } ) ;
103+ }
104+
105+ const apiKey = latestRecord [ 0 ] . route ;
106+
100107 // 1. 从 models.dev 获取价格数据
101108 const modelsDevHeaders : Record < string , string > = { "Accept" : "application/json" } ;
102109 if ( modelsDevETag ) modelsDevHeaders [ "If-None-Match" ] = modelsDevETag ;
@@ -149,7 +156,9 @@ export async function POST(request: Request) {
149156 }
150157
151158 // 3. 从 CLIProxyAPI 获取当前模型列表
152- const modelsUrl = `${ config . cliproxy . baseUrl } /models` ;
159+ // 使用 OpenAI 兼容的 /v1/models 端点而非管理 API
160+ const baseUrlWithoutManagement = config . cliproxy . baseUrl . replace ( / \/ v 0 \/ m a n a g e m e n t \/ ? $ / , "" ) ;
161+ const modelsUrl = `${ baseUrlWithoutManagement } /v1/models` ;
153162 const cliproxyRes = await fetch ( modelsUrl , {
154163 headers : { "Authorization" : `Bearer ${ apiKey } ` , "Accept" : "application/json" } ,
155164 cache : "no-store"
0 commit comments