/ src / frontend / utils / utils.ts
utils.ts
 1  import { json } from 'react-router-dom';
 2  import { ModelResponse } from './types';
 3  
 4  export const parseResponse = (jsonString: string) => {
 5    // Assert the type of the parsed object.
 6    console.log(jsonString);
 7  
 8    // uses regex to remove comments that llama sometimes includes in the JSON string
 9    // ranges from // to the end of the line or the end of the string
10    // jsonString = jsonString.replace(/(?<!\\)\/\/.*?(?=\n|$)/gm, '');
11    let parsed: string;
12    try {
13      parsed = JSON.parse(jsonString);
14    } catch (error) {
15      new Error('Ollama error');
16      return { response: 'error', action: {} };
17    }
18    if (isModelResponse(parsed)) {
19      return { response: parsed.response, action: parsed.action };
20    } else {
21      throw new Error('Invalid ModelResponse format');
22    }
23  };
24  
25  const isModelResponse = (object: any): object is ModelResponse => {
26    return 'response' in object && 'action' in object;
27  };