You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.2 KiB

11 months ago
  1. class MistralEmbedder {
  2. constructor() {
  3. if (!process.env.MISTRAL_API_KEY)
  4. throw new Error("No Mistral API key was set.");
  5. const { OpenAI: OpenAIApi } = require("openai");
  6. this.openai = new OpenAIApi({
  7. baseURL: "https://api.mistral.ai/v1",
  8. apiKey: process.env.MISTRAL_API_KEY ?? null,
  9. });
  10. this.model = process.env.EMBEDDING_MODEL_PREF || "mistral-embed";
  11. }
  12. async embedTextInput(textInput) {
  13. try {
  14. const response = await this.openai.embeddings.create({
  15. model: this.model,
  16. input: textInput,
  17. });
  18. return response?.data[0]?.embedding || [];
  19. } catch (error) {
  20. console.error("Failed to get embedding from Mistral.", error.message);
  21. return [];
  22. }
  23. }
  24. async embedChunks(textChunks = []) {
  25. try {
  26. const response = await this.openai.embeddings.create({
  27. model: this.model,
  28. input: textChunks,
  29. });
  30. return response?.data?.map((emb) => emb.embedding) || [];
  31. } catch (error) {
  32. console.error("Failed to get embeddings from Mistral.", error.message);
  33. return new Array(textChunks.length).fill([]);
  34. }
  35. }
  36. }
  37. module.exports = {
  38. MistralEmbedder,
  39. };