🐛 Update array parsing

This commit is contained in:
Asim Shrestha
2023-04-09 20:32:26 -07:00
parent 5e872e0c91
commit 8a5f5dff45
4 changed files with 26 additions and 6 deletions

View File

@@ -112,7 +112,7 @@ class AutonomousAgent {
async getInitialTasks(): Promise<string[]> {
const res = await axios.post(`/api/chain`, { goal: this.goal });
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument
return JSON.parse(res.data.tasks) as string[];
return res.data.tasks as string[];
}
async getAdditionalTasks(
@@ -126,7 +126,7 @@ class AutonomousAgent {
result: result,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-member-access
return JSON.parse(res.data.tasks) as string[];
return res.data.tasks as string[];
}
async executeTask(task: string): Promise<string> {

View File

@@ -1,5 +1,5 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { startGoalAgent } from "../../utils/chain";
import { extractArray, startGoalAgent } from "../../utils/chain";
export interface ChainAPIRequest extends NextApiRequest {
body: {
@@ -17,5 +17,6 @@ export default async function handler(
) {
const completion = await startGoalAgent(req.body.goal);
console.log(completion.text);
res.status(200).json({ tasks: completion.text as string[] });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
res.status(200).json({ tasks: extractArray(completion.text) });
}

View File

@@ -1,4 +1,4 @@
import { executeCreateTaskAgent } from "../../utils/chain";
import { executeCreateTaskAgent, extractArray } from "../../utils/chain";
import type { NextApiRequest } from "next";
import type { NextApiResponse } from "next";
@@ -28,5 +28,6 @@ export default async function handler(
req.body.result
);
console.log(completion.text);
res.status(200).json({ tasks: completion.text as string[] });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
res.status(200).json({ tasks: extractArray(completion.text) });
}

View File

@@ -49,3 +49,21 @@ export const executeCreateTaskAgent = async (
result,
});
};
export const extractArray = (inputStr: string): string[] => {
// Match an outer array of strings (including nested arrays)
const regex = /(\[(?:\s*"(?:[^"\\]|\\.)*"\s*,?)+\s*\])/;
const match = inputStr.match(regex);
if (match && match[0]) {
try {
// Parse the matched string to get the array
return JSON.parse(match[0]) as string[];
} catch (error) {
console.error("Error parsing the matched array:", error);
}
}
console.error("Error, could not extract array from inputString:", inputStr);
return [];
};