Skip to content

Commit

Permalink
Fix json regex more robust to catch the response
Browse files Browse the repository at this point in the history
  • Loading branch information
HyeonseoNam committed May 3, 2023
1 parent c09fca3 commit a9321e6
Showing 1 changed file with 9 additions and 25 deletions.
34 changes: 9 additions & 25 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,34 +117,18 @@ export default class AutoClassifierPlugin extends Plugin {
// ------- [API Processing] -------
// Call API
const responseRaw = await ChatGPT.callAPI(system_role, user_prompt, this.settings.apiKey);

// String type to JSON type
const regexToJson = /\{([^}]+)\}/g;
const match = responseRaw.match(regexToJson);
const jsonRegex = /reliability.*\s*:\s*([\d.]+).*output.*\s*:\s*"?([^"^}]+)/;
const match = responseRaw.match(jsonRegex);
let resOutput;
let resReliabity;
if (match) {
const resJson = JSON.parse(match[0]);
// Property check
if (!resJson.hasOwnProperty('output') || !resJson.hasOwnProperty('reliability')) {
new Notice(`⛔ ${this.manifest.name}: output format error (No 'output' and 'reliability' key)`);
return null;
}
resOutput = resJson.output;
resReliabity = resJson.reliability;
} else
if (!match) {
// Property check
const resOutputRegex = /utput:\s*([^\n\r]+)/;
const resReliabityRegex = /eliability:\s*([^\n\r]+)/;
try {
resOutput = String(responseRaw.match(resOutputRegex)?.[1]);
resReliabity = parseFloat(String(responseRaw.match(resReliabityRegex)?.[1]));
} catch (err) {
new Notice(`⛔ ${this.manifest.name}: output format error`);
return null;
}
}
resOutput = match[2];
resReliabity = parseFloat(match[1]);
} else {
new Notice(`⛔ ${this.manifest.name}: output format error`);
return null;
}


// Avoid row reliability
if (resReliabity <= 0.2) {
Expand Down

0 comments on commit a9321e6

Please sign in to comment.