Commit a159bed1 authored by jaden's avatar jaden

fix: fix openai porxy use deno

parent 311f4e5e
...@@ -266,6 +266,7 @@ export function AIWrapper({ ...@@ -266,6 +266,7 @@ export function AIWrapper({
loading, loading,
messageList, messageList,
currentAssistantMessage, currentAssistantMessage,
setCurrentAssistantMessage,
input, input,
handleButtonClickSuccess, handleButtonClickSuccess,
scrollContainer, scrollContainer,
...@@ -759,14 +760,14 @@ export function AIWrapper({ ...@@ -759,14 +760,14 @@ export function AIWrapper({
} }
export default function Ai(props: AIProps) { export default function Ai(props: AIProps) {
const [_, refresh] = useReducer(state => state++, 0); const [initNun, refresh] = useReducer(state => ++state, 0);
useEffect(() => { useEffect(() => {
(async () => {
if (window && !useSpeechToText) { if (window && !useSpeechToText) {
useSpeechToText = (await import('react-hook-speech-to-text')).default; import('react-hook-speech-to-text').then(({ default: fx }) => {
useSpeechToText = fx;
refresh(); refresh();
});
} }
})();
}, []); }, []);
return useSpeechToText ? <AIWrapper {...props} /> : null; return initNun || useSpeechToText ? <AIWrapper {...props} /> : null;
} }
import { Application, proxy } from 'https://deno.land/x/oak/mod.ts';
const app = new Application();
app.use(proxy('https://api.openai.com'));
app.listen({ port: 8000 });
import { NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) { const url = new URL(`${process.env.OPENAI_PROXY_URL || 'https://api.openai.com'}`);
// Clone the request headers const PROTOCOL = url.protocol;
// You can modify them with headers API: https://developer.mozilla.org/en-US/docs/Web/API/Headers const BASE_URL = url.host;
const requestHeaders = new Headers(request.headers); const DISABLE_GPT4 = !!process.env.DISABLE_GPT4;
console.log(PROTOCOL, BASE_URL);
// Add new request headers export async function requestOpenai(req: NextRequest) {
requestHeaders.set('authorization', `Bearer ${process.env.NEXT_PUBLIC_OPEN_AI_API_KEY || ''}`); const controller = new AbortController();
const authValue = `Bearer ${process.env.NEXT_PUBLIC_OPEN_AI_API_KEY || ''}`;
const openaiPath = `${req.nextUrl.pathname}${req.nextUrl.search}`.replaceAll('/openai/', '');
//Todo 需要获取questionType,动态添加Prompt let baseUrl = BASE_URL;
// You can also set request headers in NextResponse.rewrite if (!baseUrl.startsWith('http')) {
return NextResponse.next({ baseUrl = `${PROTOCOL}//${baseUrl}`;
request: { }
// New request headers
headers: requestHeaders, console.log('[Proxy] ', openaiPath);
console.log('[Base Url]', baseUrl);
if (process.env.OPENAI_ORG_ID) {
console.log('[Org ID]', process.env.OPENAI_ORG_ID);
}
const timeoutId = setTimeout(() => {
controller.abort();
}, 10 * 60 * 1000);
const fetchUrl = `${baseUrl}/${openaiPath}`;
const fetchOptions: RequestInit = {
headers: {
'Content-Type': 'application/json',
Authorization: authValue,
...(process.env.OPENAI_ORG_ID && {
'OpenAI-Organization': process.env.OPENAI_ORG_ID,
}),
},
cache: 'no-store',
method: req.method,
body: req.body,
// @ts-ignore
duplex: 'half',
signal: controller.signal,
};
// #1815 try to refuse gpt4 request
if (DISABLE_GPT4 && req.body) {
try {
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody);
if ((jsonBody?.model ?? '').includes('gpt-4')) {
return NextResponse.json(
{
error: true,
message: 'you are not allowed to use gpt-4 model',
}, },
{
status: 403,
}
);
}
} catch (e) {
console.error('[OpenAI] gpt4 filter', e);
}
}
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete('www-authenticate');
// to disbale ngnix buffering
newHeaders.set('X-Accel-Buffering', 'no');
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: res.headers,
}); });
} finally {
clearTimeout(timeoutId);
}
}
export async function middleware(request: NextRequest) {
// Only process requests that start with /openai/
console.log(new URL(request.url).pathname, 'targetUrl');
const path = new URL(request.url).pathname;
if (!path.startsWith('/openai/')) {
return NextResponse.next();
}
try {
return await requestOpenai(request);
} catch (e) {
console.log(e);
}
} }
...@@ -10,10 +10,10 @@ ...@@ -10,10 +10,10 @@
const rewrites = async () => { const rewrites = async () => {
const ret = [ const ret = [
{ // {
source: '/openai/:path*', // source: '/openai/:path*',
destination: `${process.env.OPENAI_PROXY_URL || 'https://api.openai.com'}/:path*`, // destination: `${process.env.OPENAI_PROXY_URL || 'https://api.openai.com'}/:path*`,
}, // },
{ {
source: '/google-fonts/:path*', source: '/google-fonts/:path*',
destination: 'https://fonts.googleapis.com/:path*', destination: 'https://fonts.googleapis.com/:path*',
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment