|
import fetch from 'node-fetch'; |
|
import { SECRET_KEYS, readSecret } from '../endpoints/secrets.js'; |
|
|
|
const SOURCES = { |
|
'togetherai': { |
|
secretKey: SECRET_KEYS.TOGETHERAI, |
|
url: 'api.together.xyz', |
|
model: 'togethercomputer/m2-bert-80M-32k-retrieval', |
|
}, |
|
'mistral': { |
|
secretKey: SECRET_KEYS.MISTRALAI, |
|
url: 'api.mistral.ai', |
|
model: 'mistral-embed', |
|
}, |
|
'openai': { |
|
secretKey: SECRET_KEYS.OPENAI, |
|
url: 'api.openai.com', |
|
model: 'text-embedding-ada-002', |
|
}, |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export async function getOpenAIBatchVector(texts, source, directories, model = '') { |
|
const config = SOURCES[source]; |
|
|
|
if (!config) { |
|
console.error('Unknown source', source); |
|
throw new Error('Unknown source'); |
|
} |
|
|
|
const key = readSecret(directories, config.secretKey); |
|
|
|
if (!key) { |
|
console.warn('No API key found'); |
|
throw new Error('No API key found'); |
|
} |
|
|
|
const url = config.url; |
|
const response = await fetch(`https://${url}/v1/embeddings`, { |
|
method: 'POST', |
|
headers: { |
|
'Content-Type': 'application/json', |
|
Authorization: `Bearer ${key}`, |
|
}, |
|
body: JSON.stringify({ |
|
input: texts, |
|
model: model || config.model, |
|
}), |
|
}); |
|
|
|
if (!response.ok) { |
|
const text = await response.text(); |
|
console.warn('API request failed', response.statusText, text); |
|
throw new Error('API request failed'); |
|
} |
|
|
|
|
|
const data = await response.json(); |
|
|
|
if (!Array.isArray(data?.data)) { |
|
console.warn('API response was not an array'); |
|
throw new Error('API response was not an array'); |
|
} |
|
|
|
|
|
data.data.sort((a, b) => a.index - b.index); |
|
|
|
const vectors = data.data.map(x => x.embedding); |
|
return vectors; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export async function getOpenAIVector(text, source, directories, model = '') { |
|
const vectors = await getOpenAIBatchVector([text], source, directories, model); |
|
return vectors[0]; |
|
} |
|
|