All files / ragchat-api/controllers AI.js

92.67% Statements 177/191
73.33% Branches 22/30
100% Functions 10/10
92.67% Lines 177/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 19515x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x 1x 1x 1x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x     2x 15x 15x 15x 15x 15x 15x 2x 2x 1x 1x 1x 1x 2x 15x 15x 15x 15x 15x 15x 2x 2x 1x 1x 1x 1x 1x 1x 2x 15x 15x 15x 15x 15x 15x 2x 2x 1x 1x 1x 1x 2x 15x 15x 15x 15x 15x 15x 15x 3x 3x 1x 1x 1x 1x 1x 1x 1x     1x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x     3x 15x 15x 15x 15x 15x 1x 1x 1x 1x     1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 15x 15x 15x 15x 15x 15x 4x 4x     4x 4x 4x 1x 1x 3x 3x 3x 15x 15x 15x 15x 15x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     7x        
import { Ollama } from 'ollama';
import Chat from "../models/Chat.js";
import { aiDeleteModel, aiGetModels, aiGetModel, aiInstallModel, aiIsRunning, summarizeText } from "../utils/handleAI.js";
import { mapStoredMessagesToChatMessages } from "@langchain/core/messages";
import { createRecord, findOneRecord, findRecordByID, findRecords } from '../utils/handleDB.js';
import { prefillDocumentObject } from '../utils/handleSchemes.js';
import { performance } from "node:perf_hooks";
 
 
 
 
// PROVIDE OLLAMA CONNECTION TO ALL ROUTES
export const ollama = new Ollama({ host: process.env.AI_API_URL });
 
/** *******************************************************
 * CHECK RUNNING
 */
export const getStatus = async (req, res, next) => {
  // check if ollama is reachable
  const running = await aiIsRunning();
  // NOT reachable
  if (!running) return res.status(404).json({ running });
  // reachable
  return res.json({ running });
};
 
 
/** *******************************************************
 * GET MODELS
 */
export const getModels = async (req, res, next) => {
  try {
    const foundModels = await aiFilterModelsByName(req.body.filter);
    return res.json(foundModels);
  } catch (error) {
    next(error);
  }
};
 
 
/** *******************************************************
 * GET MODEL
 */
export const getModel = async (req, res, next) => {
  try {
    const model = await aiGetModel(req.body.model);
    return res.json(model);
  } catch (error) {
    next(error);
  }
};
 
 
/** *******************************************************
 * INSTALL SINGLE
 */
export const installModel = async (req, res, next) => {
  try {
    const response = await aiInstallModel(req.body.model);
    const model = await aiFilterModelsByName(req.body.model);
 
    return res.json({ message: response.message, model });
  } catch (error) {
    next(error);
  }
};
 
 
/** *******************************************************
 * DELETE SINGLE
 */
export const deleteModel = async (req, res, next) => {
  try {
    const response = await aiDeleteModel(req.body.model);
    return res.json(response);
  } catch (error) {
    next(error);
  }
};
 
 
 
/** *******************************************************
 * FETCH CHAT
 */
export const getChat = async (req, res, next) => {
  // IF NO CHATID GIVEN
  if (!req.body.chatId) {
    try {
      // create chat and remember ID
      req.body.chatId = await createChat(req.body.model, req.body.input);
 
      // return
      return next();
    } catch (error) {
      return next(error);
    }
  }
 
  // IF CHATID GIVEN
  try {
    // fetch chat record
    const record = await findRecordByID(Chat, req.body.chatId);
    if (!record) {
      return res.status(404).json({ message: `No chat history with ID ${req.body.chatId} found.` });
    }
    // remember chat history
    // cite: https://js.langchain.com/v0.1/docs/modules/memory/chat_messages/custom/
    performance.mark('mapStoredMessagesToChatMessages:start');
    req.body.chatHistory = mapStoredMessagesToChatMessages(record.chatHistory);
    performance.mark('mapStoredMessagesToChatMessages:end');
    // go on
    next();
  } catch (error) {
    next(error);
  }
};
 
/** *******************************************************
 * GET CHATS
 */
export const getChats = async (req, res, next) => {
  try {
    const chats = await findRecords(Chat, { createdBy: global.currentUserId });
    return res.json({ chats });
  } catch (error) {
    next(error);
  }
};
 
/** *******************************************************
 ####################### FUNCTIONS #######################
 ******************************************************* */
 
/**
* CREATE CHAT
* return id
*/
export const createChat = async (model, input) => {
  try {
    performance.mark('create_chat:start');
    // create chat title
    const title = await summarizeText(model, input);
    // create record
    const record = await createRecord(Chat, prefillDocumentObject(Chat, { title }));
    // return record id
    performance.mark('create_chat:end');
    return record.id;
  } catch (error) {
    throw error;
  }
};
 
 
/** *******************************************************
 * CHECK IF REQUESTED MODEL IS AVAILABLE
 */
export const checkRequestedModel = async (req, res, next) => {
  performance.mark('checkRequestedModel:start');
  if (!req.body.model) {
    return res.status(500).json({ error: `No chat model requested.` });
  }
  const models = await aiFilterModelsByName(req.body.model);
  // return if missing
  if (!models.length) {
    return res.status(500).json({ error: `Chat model ${req.body.model} not found.` });
  }
  performance.mark('checkRequestedModel:end');
  next();
};
 
/** *******************************************************
 * FILTER AVAILABLE MODELS BY NAME
 */
export const aiFilterModelsByName = async (strFilter = '') => {
  try {
    performance.mark('aiFilterModelsByName:start');
    // fetch all available models
    const avail = await aiGetModels();
 
    // return all if no regex query provided
    if (strFilter === '') return avail;
    // set regex query
    const regex = new RegExp(strFilter, 'i');
    // filter models by regex query
    performance.mark('aiFilterModelsByName:end');
    return avail.models.filter((model) => regex.test(model.name));
  } catch (error) {
    throw error;
  }
};