72 lines
1.9 KiB
TypeScript
72 lines
1.9 KiB
TypeScript
/**
|
||
* RAG Chat 服务端 API 模块
|
||
*
|
||
* 提供 Node.js 服务端调用 FastAPI 后端的基础功能。
|
||
* 现已改为走自有 RAG 接口:
|
||
* Remix Server -> FastAPI /api/v3/rag/*
|
||
*
|
||
* @module api/dify-chat/client.server
|
||
*/
|
||
|
||
import { API_BASE_URL } from '~/config/api-config';
|
||
|
||
const RAG_API_ROOT = `${API_BASE_URL}/v3/rag`;
|
||
|
||
export interface DifyFetchOptions extends RequestInit {
|
||
appId?: string;
|
||
}
|
||
|
||
function buildHeaders(fetchOptions: RequestInit, jwt?: string): HeadersInit {
|
||
const headers: HeadersInit = {
|
||
'Content-Type': 'application/json',
|
||
...fetchOptions.headers,
|
||
};
|
||
|
||
if (jwt) {
|
||
(headers as Record<string, string>).Authorization = `Bearer ${jwt}`;
|
||
} else {
|
||
console.warn('[RAG Chat] 没有提供 JWT,FastAPI 请求可能失败');
|
||
}
|
||
|
||
return headers;
|
||
}
|
||
|
||
export async function difyFetch(
|
||
endpoint: string,
|
||
options: DifyFetchOptions = {},
|
||
jwt?: string
|
||
): Promise<Response> {
|
||
const { appId, ...fetchOptions } = options;
|
||
const cleanEndpoint = endpoint.replace(/^\//, '');
|
||
let url = `${RAG_API_ROOT}/${cleanEndpoint}`;
|
||
|
||
if (appId) {
|
||
const separator = url.includes('?') ? '&' : '?';
|
||
url = `${url}${separator}appId=${encodeURIComponent(appId)}`;
|
||
}
|
||
|
||
const response = await fetch(url, {
|
||
...fetchOptions,
|
||
headers: buildHeaders(fetchOptions, jwt),
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errorText = await response.text();
|
||
console.error('[RAG Chat] API 转发错误:', {
|
||
status: response.status,
|
||
statusText: response.statusText,
|
||
error: errorText,
|
||
});
|
||
|
||
if (response.status === 401) {
|
||
throw new Error('JWT认证失败,请重新登录');
|
||
}
|
||
|
||
throw new Error(`RAG API Error: ${response.status} ${response.statusText}`);
|
||
}
|
||
|
||
return response;
|
||
}
|
||
|
||
export { difyClient } from './chat';
|