37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
export async function generateBgeM3Embedding(text: string): Promise<number[] | null> {
|
|
try {
|
|
// 动态获取当前协议和主机(不含端口),然后指定后端端口 8001
|
|
const { protocol, host } = window.location;
|
|
const hostname = host.split(":")[0];
|
|
const apiUrl = `${protocol}//${hostname}:8001/v1/embeddings`;
|
|
|
|
const response = await fetch(apiUrl, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
// OpenAI 兼容请求字段
|
|
input: text,
|
|
model: "text-embedding-bge-m3"
|
|
})
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to fetch BGE-M3 embedding: ${response.status}`);
|
|
}
|
|
|
|
// 返回结构为 { object, data: [{ embedding, … }], model, usage }
|
|
const result = await response.json();
|
|
|
|
// 取 data[0].embedding
|
|
if (Array.isArray(result.data) && result.data.length > 0) {
|
|
return result.data[0].embedding as number[];
|
|
} else {
|
|
console.error("Unexpected embedding response format:", result);
|
|
return null;
|
|
}
|
|
} catch (err) {
|
|
console.error("Error in generateBgeM3Embedding:", err);
|
|
return null;
|
|
}
|
|
}
|