需要环境变量填写多个key的兄弟们看过来! #461
buwanyuanshen
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
找到src/pages/api/generate.ts文件,编辑,全部删除修改为:
// #vercel-disable-blocks
import { ProxyAgent, fetch } from 'undici'
// #vercel-end
import { generatePayload, parseOpenAIStream } from '@/utils/openAI'
import { verifySignature } from '@/utils/auth'
import type { APIRoute } from 'astro'
const apiKeys = import.meta.env.OPENAI_API_KEY.split(',') || []
const httpsProxy = import.meta.env.HTTPS_PROXY
const baseUrl = ((import.meta.env.OPENAI_API_BASE_URL) || 'https://api.openai.com').trim().replace(/\/$/, '')
const sitePassword = import.meta.env.SITE_PASSWORD || ''
const passList = sitePassword.split(',') || []
export const post: APIRoute = async(context) => {
const body = await context.request.json()
const { sign, time, messages, pass, temperature } = body
if (!messages) {
return new Response(JSON.stringify({
error: {
message: 'No input text.',
},
}), { status: 400 })
}
if (sitePassword && !(sitePassword === pass || passList.includes(pass))) {
return new Response(JSON.stringify({
error: {
message: 'Invalid password.',
},
}), { status: 401 })
}
if (import.meta.env.PROD && !await verifySignature({ t: time, m: messages?.[messages.length - 1]?.content || '' }, sign)) {
return new Response(JSON.stringify({
error: {
message: 'Invalid signature.',
},
}), { status: 401 })
}
const apiKey = apiKeys[Math.floor(Math.random() * apiKeys.length)]
const initOptions = generatePayload(apiKey, messages, temperature)
// #vercel-disable-blocks
if (httpsProxy)
initOptions.dispatcher = new ProxyAgent(httpsProxy)
// #vercel-end
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const response = await fetch(
${baseUrl}/v1/chat/completions
, initOptions).catch((err: Error) => {console.error(err)
return new Response(JSON.stringify({
error: {
code: err.name,
message: err.message,
},
}), { status: 500 })
}) as Response
return parseOpenAIStream(response) as Response
}
也可以删除原来的
const apiKey = import.meta.env.OPENAI_API_KEY
修改为:
const apiKeys = import.meta.env.OPENAI_API_KEY.split(',') || []
const apiKey = apiKeys[Math.floor(Math.random() * apiKeys.length)]
Beta Was this translation helpful? Give feedback.
All reactions