first commit for refactored project

This commit is contained in:
KS Jannette
2026-05-23 17:08:47 -04:00
commit 6545f8f549
166 changed files with 48911 additions and 0 deletions

View File

@@ -0,0 +1,764 @@
const fs = require("fs");
const path = require("path");
const { updateDB } = require("../firebase/firebase.js");
const OpenAI = require("openai");
const {
iteratePathsReturnString,
makeDir,
saveCompletions,
selectRequestPath,
selectResponsePath,
} = require("./utilities.js");
const {
createArrayFromSingleDocPrompt,
createResponseFromOneQuestionPrompt,
createArrayOfInterrogatoriesPlaintiffPrompt,
createArrayOfInterrogatoriesDefendantPrompt,
createVerboseResponseFromOneQuestionPrompt,
createArrayFromStringBlobPrompt,
} = require("./promptTemplates.js");
const { OPENAI_API_KEY } = require("./secrets_1.js");
const { v4: uuidv4 } = require("uuid");
const dJSON = require("dirty-json");
const openai = new OpenAI({
apiKey: OPENAI_API_KEY,
});
class ModelController {
/*
* LLM PROMPT CONTROLLER
* RETURNS ANSWERS FROM JSON ARRAY OF REQUEST Qs
*
*/
async arrayGenAnswers(docId, reqType, isRequests) {
/*
const basePath = process.cwd();
if (reqType == "combined-numbered") {
filePath = `${basePath}/Documents/Requests/combined-numbered/${docId}/${docId}-jbk-parsedRequests.json`;
} else if (reqType == "interrogatories") {
filePath = `${basePath}/Documents/Requests/interrogatories/${docId}/${docId}-jbk-parsedRequests.json`;
} else if (reqType == "admissions") {
filePath = `${basePath}/Documents/Requests/admissions/${docId}/${docId}-jbk-parsedRequests.json`;
} else if (reqType == "production") {
filePath = `${basePath}/Documents/Requests/production/${docId}/${docId}-jbk-parsedRequests.json`;
}
*/
const filePath = path.join(
__dirname,
"..",
"Documents",
"Requests",
`${reqType}`,
`${docId}`,
`${docId}-jbk-parsedRequests.json`
);
console.log(
"**arrayGenAnswers ------------------------- reqType, isRequests",
reqType,
isRequests
);
const fileData = fs.readFileSync(filePath, "utf8");
const rogs = await JSON.parse(fileData);
const requests = rogs[0].requests;
let completions;
if (reqType == "combined-numbered") {
completions = await this.start(requests, reqType, isRequests);
} else {
completions = await this.start(requests, reqType, isRequests);
}
//moved makedir up - race condition
const saveDirectory = path.join(
__dirname,
"..",
"Documents",
"Responses",
`${reqType}`,
`${docId}`
);
fs.mkdir(`${saveDirectory}`, function (err) {
if (err) {
console.log("arrayGenAnswers error creating directory: " + err);
}
});
let masterArray = [];
const completionsArray = [];
const completionsObject = { type: `response to ${reqType}` };
const finalArray = completions[0];
let temp;
finalArray?.forEach((comp) => {
let obj = {};
const responseId = uuidv4();
obj["responseId"] = responseId;
obj["text"] = comp;
completionsArray.push(obj);
});
completionsObject["responses"] = completionsArray;
masterArray.push(completionsObject);
temp = docId;
temp = masterArray;
const data = JSON.stringify(temp);
const fileSuffix = "-jbk-responses.json";
fs.writeFile(
`${saveDirectory}/${docId}${fileSuffix}`,
data,
function (err) {
if (err) {
return console.log("arrayGenAnswers err in writeFile:", err);
}
}
);
updateDB(docId, reqType);
return temp;
}
/*
* LLM PROMPT CONTROLLER
*
* FOR docPARSER FAILS(?)/docCLASSIFIER DETERMINES COMBINED-NUMBERED
* CREATES JSON ARRAY OF QUESTIONS FROM STRING BLOB OF INCOMING REQ
*/
async createArrayOfQuestions(docId, reqType, isRequests, countObject) {
const masterArray = [];
//const clientPosition = countObject.clientPosition;
console.log(
"----------------------------------------------------------------------"
);
console.log("createArrayOfQuestions docId:", docId);
console.log("createArrayOfQuestions reqType:", reqType);
console.log("createArrayOfQuestions isRequests:", isRequests);
console.log(
"----------------------------------------------------------------------"
);
const directionVar = isRequests ? "Requests" : "Responses";
const saveDirectory = path.join(
__dirname,
"..",
"Documents",
"Requests",
`${reqType}`,
`${docId}`
);
const dirPath = path.join(
__dirname,
"..",
"Documents",
"Textfiles",
`${docId}`
);
fs.mkdir(`${saveDirectory}`, function (err) {
if (err) {
console.log("arrayGenAnswers error creating directory: " + err);
}
});
let fileNames = fs.readdirSync(dirPath);
const dirArray = fileNames.map((name) => {
return `${dirPath}/${name}`;
});
let requestStr;
let completes;
let newArray = [];
let flatReq;
let parsedRequests = [];
if (dirArray.length > 12) {
const splitAt = Math.floor(dirArray.length / 2);
const temp1 = dirArray.slice(0, splitAt);
const temp2 = dirArray.slice(splitAt, dirArray.length);
newArray.push(temp1);
newArray.push(temp2);
completes = await Promise.all(
newArray.map(async (arr) => {
requestStr = await iteratePathsReturnString(arr);
const comp = await this.startOne(requestStr, reqType, isRequests);
return comp;
})
);
let fooz = null;
let barz = null;
try {
try {
fooz = JSON.parse(completes[0]);
if (!fooz) {
fooz = dJSON.parse(completes[0]);
}
} catch (err) {
console.log("err in first fooz try", err);
}
} catch (err) {
console.log("Error in createArrayOfQuestions at :", err);
}
try {
try {
barz = JSON.parse(completes[1]);
if (!barz) {
fooz = dJSON.parse(completes[1]);
}
} catch (err) {
console.log("err in first barz try", err);
}
} catch (err) {
console.log("Error in createArrayOfQuestions :", err);
}
fooz.forEach((item) => {
parsedRequests.push(item);
});
barz.forEach((item) => {
parsedRequests.push(item);
});
} else {
requestStr = await iteratePathsReturnString(dirArray);
flatReq = await this.startOne(requestStr, reqType, isRequests);
try {
parsedRequests = JSON.parse(flatReq);
} catch (err) {
console.log(
"Error parsing json in ModelController.createArrayOfQuestions: ",
err
);
}
}
const completionsObject = { type: "combined-numbered" };
completionsObject["requests"] = parsedRequests;
masterArray.push(completionsObject);
let temp = docId;
temp = masterArray;
const fileSuffix = isRequests
? "-jbk-parsedRequests.json"
: "-jbk-responses.json";
const data = JSON.stringify(temp);
//change back
fs.writeFile(
`${saveDirectory}/${docId}${fileSuffix}`,
data,
function (err) {
if (err) {
return console.log("arrayGenAnswers err in writeFile:", err);
}
}
);
updateDB(docId, reqType);
return temp;
}
//****************** Create Array of Interrogatories from Complaint **********************/
async createArrayOfInterrogatories(
docId,
clientPosition,
reqType = "interrogatories-out"
) {
const masterArray = [];
const isRequests = false;
const fdirup = path.resolve(
process.cwd() + `/Documents/Textfiles/${docId}/`
);
console.log(
"****************** Create Array of Interrogatories from Complaint fdirup for text files:",
fdirup
);
const dirPath = `../Documents/Textfiles/${docId}/`;
let fileNames = fs.readdirSync(fdirup);
const dirArray = fileNames.map((name) => {
return `${fdirup}/${name}`;
});
let requestStr;
let completes;
let newArray = [];
let flatReq;
let parsedRequests = [];
if (dirArray.length > 10) {
const splitAt = Math.floor(dirArray.length / 2);
const temp1 = dirArray.slice(0, splitAt);
const temp2 = dirArray.slice(splitAt, dirArray.length);
newArray.push(temp1);
newArray.push(temp2);
completes = await Promise.all(
newArray.map(async (arr) => {
requestStr = await iteratePathsReturnString(arr);
const comp = await this.startOne(
requestStr,
reqType,
isRequests,
reqType
);
return comp;
})
);
let fooz = JSON.parse(completes[0]);
let barz = JSON.parse(completes[1]);
fooz.forEach((item) => {
parsedRequests.push(item);
});
barz.forEach((item) => {
parsedRequests.push(item);
});
} else {
requestStr = await iteratePathsReturnString(dirArray);
flatReq = await this.startOneCreateOutgoing(
requestStr,
reqType,
isRequests,
clientPosition
);
try {
if (flatReq) {
parsedRequests = JSON.parse(flatReq);
}
} catch (err) {
console.log(
"Error parsing json in ModelController.createArrayOfQuestions: ",
err
);
}
}
const saveDirectory = path.join(
__dirname,
"..",
"Documents",
"RequestsOut",
`${docId}`
);
fs.mkdir(`${saveDirectory}`, function (err) {
if (err) {
console.log("makeDir utilities error creating directory: " + err);
}
});
const completionsObject = { type: "interrogatories-out" };
completionsObject["requests"] = parsedRequests;
masterArray.push(completionsObject);
let temp = docId;
temp = masterArray;
const data = JSON.stringify(temp);
const fileSuffix = "-jbk-requests-out.json";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
await sleep(1000);
try {
fs.writeFile(
`${saveDirectory}/${docId}${fileSuffix}`,
data,
function (err) {
if (err) {
console.log(
"Error in createArrayOfInterrogatories writeFile:",
err
);
}
}
);
} catch (err) {
console.log("Error writing file in createArrayOfInterrogatories:", err);
}
//updateDB(docId, reqType); //need to fix
return temp;
}
/*
* LLM PROMPT CONTROLLER
* RETURNS REQUESTS FROM STRING BLOB
* FOR VERY LONG REQUEST DOCUMENTS
* (> 50 pages?? ... guestimate; determined by timer in tesseWatcher)
*/
async createArrayOfQuestionsLarge(docId, reqType) {
const masterArray = [];
const isRequests = true;
const dirPath = `../Documents/Textfiles/${docId}/`;
let fileNames = fs.readdirSync(dirPath);
const dirArray = fileNames.map((name) => {
return dirPath + name;
});
let requestStr;
let completes;
let newArray = [];
let flatReq;
let parsedRequests = [];
const arrSize = 20;
while (dirArray.length > 0) {
newArray.push(dirArray.splice(0, arrSize));
}
completes = await Promise.all(
newArray.map(async (arr) => {
requestStr = await iteratePathsReturnString(arr);
const comp = await this.startOne(requestStr, reqType, isRequests);
return comp;
})
);
const num = newArray.length - 1;
for (let i = 0; i < num; i++) {
try {
let temp = dJSON.parse(completes[i]);
temp.forEach((item) => {
parsedRequests.push(item);
});
} catch (err) {
console.log(
`Error parsing JSON in completions for item at index no ${i}`,
err
);
}
}
/*
const foo = dJSON.parse(completes[0]);
const bar = dJSON.parse(completes[1]);
console.log("foo", foo);
parsedRequests = completes.flat(Infinity);
parsedRequests = foo.concat(bar);
*/
const directionVar = isRequests ? "Requests" : "Responses";
const saveDirectory = path.join(
__dirname,
"..",
"Documents",
`${directionVar}`,
`${reqType}`,
`${docId}`
);
fs.mkdir(`${saveDirectory}`, function (err) {
if (err) {
console.log("makeDir utilities error creating directory: " + err);
}
});
const completionsObject2 = { type: "combined-numbered" };
completionsObject2["requests"] = parsedRequests;
masterArray.push(completionsObject2);
let temp2 = docId;
temp2 = masterArray;
const fileSuffix = isRequests
? "-jbk-parsedRequests.json"
: "-jbk-responses.json";
fs.writeFile(
`${saveDirectory}/${docId}${fileSuffix}`,
data,
function (err) {
if (err) {
return console.log(
"createArrayOfQuestionsLargeError in writeFile:",
err
);
}
}
);
updateDB(docId, reqType);
return temp2;
}
/*
* LLM PROMPT CYCLE
* CREATE RESPONSES TO JSON ARRAY OF REQUEST Qs
*
*/
async start(requests, reqType) {
const answersResponses = await Promise.all(
requests.map(async (request) => {
const prompt = createVerboseResponseFromOneQuestionPrompt(request.text);
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: prompt,
});
console.log("completion.choices[0].message.content");
return completion.choices[0].message.content;
})
);
const fooBar = [];
fooBar.push(answersResponses);
fooBar.push(reqType);
return fooBar;
}
/*
* LLM PROMPT CYCLE
* PULL ARRAY OF Qs FROM STRING BLOB OF INCOMING REQUEST DOC
*
*/
async startOne(requestStr, reqType, isRequests) {
let prompt;
if (reqType === "interrogatories-out") {
//prompt = createArrayOfInterrogatoriesPrompt(request);
} else {
prompt = createArrayFromStringBlobPrompt(requestStr);
}
//prompt = createArrayOfInterrogatoriesPlaintiffPrompt(requestStr);
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: prompt,
});
console.log(
"completion.choices[0].message.content",
completion.choices[0].message.content
);
return completion.choices[0].message.content;
}
/*
* LLM PROMPT CYCLE
* CREATE OUTGOING REQUESTS FROM COMPLAINT
*
*/
async startOneCreateOutgoing(
requestStr,
reqType,
isRequests,
clientPosition
) {
let prompt;
if (clientPosition?.toLowerCase() === "plaintiff") {
prompt = createArrayOfInterrogatoriesPlaintiffPrompt(requestStr);
} else {
prompt = createArrayOfInterrogatoriesDefendantPrompt(requestStr);
}
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: prompt,
});
console.log(
"completion.choices[0].message.content",
completion.choices[0].message.content
);
return completion.choices[0].message.content;
}
// for development
async testSaveFunction(docId, reqType, isRequests) {
const directionVar = isRequests ? "Requests" : "Responses";
const temp = [
{ one: "one", two: "two", three: "three", four: "ddd", five: "mmm" },
];
const data = JSON.stringify(temp);
const saveDirectory = path.join(
__dirname,
"..",
"Documents",
`${directionVar}`,
`${reqType}`,
`${docId}`
);
const fileSuffix = isRequests
? "-jbk-parsedRequests.json"
: "-jbk-responses.json";
console.log("-----------------------------------------");
console.log("saveDirectory:", saveDirectory);
console.log("-----------------------------------------");
console.log(
"saveDirectory AND FILE",
`${saveDirectory}/${docId}${fileSuffix}`
);
console.log("-----------------------------------------");
fs.writeFile(
`${saveDirectory}/${docId}${fileSuffix}`,
data,
function (err) {
if (err) {
return console.log(
"createArrayOfQuestionsLargeError in writeFile:",
err
);
}
}
);
}
}
module.exports = new ModelController();
/* ******** **************************************************************************
fs.writeFile(
`/Users/kjannette/workspace/ax3/ax3Services/Documents/Requests/${reqType}/${docId}`,
data,
(err) => {
console.log("test err:", err);
}
);
* LLM PROMPT CONTROLLER
* CREATES ANSWERS FROM ARRAY OF REQUESTS - COMBINED TYPE
*
async arrayGenAnswersCombined(docId, reqType, isRequests) {
let filePath;
const basePath = process.cwd();
if (reqType == "combined-numbered") {
filePath = `${basePath}/Documents/Requests/Parsedcombined/${docId}/${docId}-jbk-parsedRequests.json`;
//filePath = `${basePath}/Documents/Requests/Parsedcombined/${docId}/${docId}-jbk-parsedRequests.json`;
} else if (reqType == "interrogatories") {
filePath = `${basePath}/Documents/Requests/Parsedrogs/${docId}/${docId}-jbk-parsedRequests.json`;
} else if (reqType == "admissions") {
filePath = `${basePath}/Documents/Requests/Parsedadmit/${docId}/${docId}-jbk-parsedRequests.json`;
} else if (reqType == "production") {
filePath = `${basePath}/Documents/Requests/Parsedprod/${docId}/${docId}-jbk-parsedRequests.json`;
}
const path = path.join(
__dirname,
"..",
"Documents",
"Requests",
`${reqType}`,
`${docId}`
);
const fileData = fs.readFileSync(
`${path}/${docId}-jbk-parsedRequests.json`,
"utf8"
);
const rogs = await JSON.parse(fileData);
const requests = rogs[0].requests;
let completions;
completions = await this.start(requests, reqType, isRequests);
let masterArray = [];
const completionsArray = [];
const completionsObject = { type: `response to ${reqType}` };
const finalArray = completions[0];
finalArray?.forEach((comp) => {
console.log("comp", comp);
let obj = {};
const responseId = uuidv4();
obj["responseId"] = responseId;
obj["text"] = comp;
completionsArray.push(obj);
});
completionsObject["responses"] = completionsArray;
masterArray.push(completionsObject);
const directionVar = isRequests ? "Requests" : "Responses";
const saveDirectory = path.join(
__dirname,
"..",
"Documents",
`${directionVar}`,
`${reqType}`,
`${docId}`
);
const fileSuffix = isRequests
? "-jbk-parsedRequests.json"
: "-jbk-responses.json";
let temp;
temp = docId;
temp = masterArray;
return temp;
}
async combinedGenAnswers(docId, reqType, isRequests) {
console.log(
"_____________________________________________________________ fired combinedGenAnswers"
);
const masterArray = [];
let dirPath;
if (reqType === "combined-numbered") {
dirPath = `../Documents/Textfiles/${docId}/`;
} else {
//
}
let fileNames = fs.readdirSync(dirPath);
const dirArray = fileNames.map((name) => {
return dirPath + name;
});
const requestString = iteratePathsReturnString(dirArray);
const completions = await this.startOne(requestString, reqType, isRequests); //START
const completionsObject = { type: `response to combined-requests` };
completionsObject["responses"] = completions;
masterArray.push(completionsObject);
const directionVar = isRequests ? "Requests" : "Responses";
const saveDirectory = path.join(
__dirname,
"..",
"Documents",
`${directionVar}`,
`${reqType}`,
`${docId}`
);
fs.mkdir(`${saveDirectory}`, function (err) {
if (err) {
console.log("makeDir utilities error creating directory: " + err);
}
});
temp = docId;
temp = masterArray;
const data = JSON.stringify(temp);
const fileSuffix = isRequests
? "-jbk-parsedRequests.json"
: "-jbk-responses.json";
fs.writeFile(
`${saveDirectory}/${docId}${fileSuffix}`,
data,
function (err) {
if (err) {
return console.log("Error in saveCompletions writeFile:", err);
}
}
);
return temp;
}
*/

View File

@@ -0,0 +1,137 @@
/// this is used when you already ahve an array of questions -- plain old answers
const createResponseFromOneQuestionPrompt = (request) => {
const regularPrompt = [
{
role: "user",
content: `You are a paralegal assisting trial attorneys in drafting discovery responses, including interrogatories, requests for production and requests for admissions. Draft a response to the following request. Include only objections, but thoroughly include all possible, non-frivolous, objections. Do not assume facts about the case. Refer to our client, who is responding here, as 'Respondent'. Begin each response with "RESPONDENT OBJECTS TO THE REQUEST" (or, where appropriate, "RESPONDENT FURTHER OBJECTS" which should always be uppersace and always start on a new line). Do not preface or suffix your response with observations, notes, analysis or comments. Do not add any signature block, such as 'Executed on this __ day of _______, 20__.'. Do not preface any response with numbering, such as 'RESPONSE NO. 1'. End each response with 'SUBJECT TO AND WITHOUT WAIVING these objections, Respondent states as follows:' then stop there, write nothing further. This is the request:${request}`,
},
];
return regularPrompt;
};
const createVerboseResponseFromOneQuestionPrompt = (request) => {
const verbosePrompt = [
{
role: "user",
content: `You are a paralegal assisting trial attorneys in drafting discovery responses, including interrogatories, requests for production and requests for admissions. Draft a response to the following request. In responding, first state applicable objections. Be sure to thoroughly include all possible, non-frivolous, objections. Refer to our client, who is responding here, as 'Respondent'. Begin each response with "RESPONDENT OBJECTS TO THE REQUEST" (or, where appropriate, "RESPONDENT FURTHER OBJECTS" (which should always be uppercase and always start on a new line). Once you have stated the objections, then continue with 'SUBJECT TO AND WITHOUT WAIVING these objections, Respondent states as follows:' and state your substantive response. Do not preface or suffix your response with observations, notes, analysis or comments. Do not add any signature block, such as 'Executed on this __ day of _______, 20__.'. Do not preface any response with numbering, such as 'RESPONSE NO. 1'. This is the request: ${request}`,
},
];
return verbosePrompt;
};
// create an array of the questions for a combined numbered type
const createArrayFromSingleDocPrompt = (request) => {
console.log(">>9980989cteArrayFromSingleDocPrompt FIRED~~~~~~~~~~~~~~~~~~~");
const parseRequestsPrompt = [
{
role: "user",
content: `You are an AI paralegal assisting attorneys in drafting discovery requests. Your firm represents the defendant in a lawsuit against it for an injury
allegedly sustained by the plaintiff. To prevail, the plaintiff must prove that 1. your client owed him/her a duty of care, 2. breached that duty, and
3. the breach was the proximate (direct) cause of his/her 4. actual damages (actual damages must be proven). It is the plaintiffs duty to prove each of those elements.
It is not the defendant's duty to disprove them. I will provide you with the complaint filed in court, then some technical instructions.
Review the complaint carefully. Asd you do, think about the facts the plaintiff will need to prove to satisfy each of those four elements.
Then, draft 20 interrogatories. They should seek all evidence the plaintiff has in his/her possession to prove the claim. The technical instructions: return the
interrogatories in JSON format. The JSON should be in the form of an array of objects. There should be one object for each interrogatory The object should contain
two key/value pairs: first, “requestId": this key's value will be a randomly generated version 4 UUID The second key is ”text": its value will be the substantive
content of the individual interrogatory. This is an example sequence of three interrogatories: [{ "requestId": "73a855af-4fdc-4b8b-9e7f-34d57a2c084a",
"text": "example - Please identify the person or persons responding to these Interrogatories, and identify each person who has provided information in connection
with these Interrogatories.”}, { "requestId": "36fe8375-240d-4a08-8a71-9b2ba5bda348", "text": "example - Identify the owner of the premises described in complaint."},
{ "requestId": "cfaf4a36-20de-44ff-8673-5a725bddca03", "text": "example - Identify any person not already named as a party to this lawsuit whom you contend caused
or contributed to the occurrence which you contend proximately caused your injuries and/or other damages .“}]. Lastly, do not add introductory comments, analysis,
or observations. Return only the interrogatories in the manner previously described. This is the complaint: ${complaint}`,
},
];
return parseRequestsPrompt;
};
const createArrayOfInterrogatoriesPlaintiffPrompt = (complaint) => {
console.log(
"createArrayOfInterrogatoriesPlaintiffPrompt fired-----------------------------------------"
);
const parseRequestsPrompt = [
{
role: "user",
content: `You are an AI paralegal assisting attorneys in drafting discovery requests. You represent the plaintiff in a negligence lawsuit. To prevail, the plaintiff must satisfy these legal elements: 1) the defendant owed it a duty of care, 2) the defendant breached that duty; 3) which was the proximate cause of 4) plaintiffs damages (typically physical injuries, may include losses stemming from injuries, i.e. lost wages).
Your task is to draft ten (10) interrogatories to the defendant. I will provide technical instructions and the Complaint (for background). Review the complaint carefully, thinking about the above legal elements stated, and what facts would satisfy them. Then, think about the information the defendant might possess that would satisfy them. That is the information you seek.
The technical instructions: return interrogatories in JSON format. The JSON should be an array of objects, with one object for each interrogatory. An object will contain two key/value pairs: First key: “requestId", value: a random version 4 UUID Second key is ”text", its value is the individual interrogatory. I will give you examples of the form. They are hypothetical in substance, (not necessarily similar to this cases facts).
Use them to think about the legal writing style youll employ. (Reference to paragraphs of a complaint in the examples are hypothetical and for illustration. They do not refer to the facts in this case. However, if they are similar, you may reuse/paraphrase them.) THIS IS IMPORTANT, FOLLOW THIS INSTRUCTION: Accurately cite the complaint where appropriate, using the phrase 'as set forth in paragraph <you will insert appropriate number(s) here> of the complaint'. Do not include foundational questions in your interrogatories, such as asking the respondents name, address, age, etc. These will be supplied elsewhere.
Do not add introductory comments, analysis, or observations, such as "Based on your request, I have parsed the complaint and..," etc. This will be problematic for later data processing. Here are the examples:
[{ "requestId": "73a855af-4fdc-4b8b-9e7f-34d57a2c084a", "text": "Give a detailed statement of how you contend the occurrence took place, including where you were traveling from and traveling to, any stops made along the way, the date, time, location of the accident.”}, { "requestId": "36fe8375-240d-4a08-8a71-9b2ba5bda348", "text": "State whether you were the driver and/or owner of the vehicle involved in the occurrence on the date,
time and location as outlined in the Complaint. If you were not the driver, then state who you claim was driving the vehicle.”}, { "requestId": "cfaf4a36-20de-44ff-8673-5a725bddca03",
"text": "If you were employed at the time of the occurrence, as indicated in the Complaint, and working within the scope of that employment when the occurrence took place, identify your employer and the nature of the work you were performing.“}]. This is the complaint: ${complaint}`,
},
];
return parseRequestsPrompt;
};
const createArrayOfInterrogatoriesDefendantPrompt = (complaint) => {
console.log(
"createArrayOfInterrogatoriesDefendantPrompt fired-----------------------------------------"
);
const parseRequestsPrompt = [
{
role: "user",
content: `You are an AI paralegal assisting attorneys in drafting discovery requests. You represent the defendant in a negligence lawsuit. To prevail, the plaintiff must show facts sufficient to satisfy these legal elements: 1) the defendant owed it a duty of care, 2) the defendant breached that duty, which 3) was the proximate cause, of 4) plaintiffs damages (typically physical injuries, and may include losses stemming from injuries, i.e. lost wages).
Your task is to draft ten (10) interrogatories to the plaintiff. I will provide technical instructions and the Complaint (for background). Review the Complaint carefully, thinking about the above legal elements, and what facts the plaintiff must prove to satisfy them. That is the information you seek. In other words, the interrogatories goal is to discover if the plaintiff can prove its case.
The technical instructions: return the ten (10) interrogatories in JSON format. The JSON should be an array of objects, with one object for each interrogatory. An object will contain two key/value pairs: First key: “requestId", value: a random version 4 UUID Second key is ”text", its value is the individual interrogatory. I will give you examples. They are hypothetical in substance, not necessarily similar to this cases facts. Use them to think about the legal writing style youll employ. (Reference to paragraphs of a complaint in the examples are hypothetical and for illustration. They do not refer to the facts in this case. However, if they are similar, you may reuse/paraphrase them.) THIS IS IMPORTANT, FOLLOW THIS INSTRUCTION: Accurately cite the Complaint where appropriate, using the phrase 'as set forth in paragraph(s) <you will insert appropriate number(s) here> of the Complaint.' Do not include foundational questions in your interrogatories, such as asking the respondents name, address, age, etc. These will be supplied elsewhere.
Do not add introductory comments, analysis, or observations, such as "Based on your request, I have parsed the Complaint and..," etc. This will be problematic for later data processing. Here are the examples:
[{ "requestId": "73a855af-4fdc-4b8b-9e7f-34d57a2c084a", "text": "Give a detailed statement of how you contend the occurrence took place, including where you were traveling from and traveling to, any stops made along the way, the date, time, location of the accident.”}, { "requestId": "36fe8375-240d-4a08-8a71-9b2ba5bda348", "text": "State whether you were the driver and/or owner of the vehicle involved in the occurrence on the date,
time and location as outlined in the Complaint. If you were not the driver, then state who you claim was driving the vehicle.”}, { "requestId": "cfaf4a36-20de-44ff-8673-5a725bddca03",
"text": "If you were employed at the time of the occurrence, as indicated in the Complaint, and working within the scope of that employment when the occurrence took place, identify your employer and the nature of the work you were performing.“}]. This is the Complaint: ${complaint}`,
},
];
return parseRequestsPrompt;
};
const createArrayFromStringBlobPrompt = (request) => {
console.log(
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>createArrayFromStringBlobPrompt FIRED~~~~~~~~~~~~~~~~~~~"
);
const parseRequestsPrompt = [
{
role: "user",
content: `You are an AI paralegal assisting attorneys in drafting discovery responses. Part of your job is to convert discovery request documents from text to other formats, such as JSON, for processing. I will provide you with some instructions, then a discovery request document, then you will perform a parsing operation.
The instructions: Review the discovery request document and return the numbered requests, and only the requests, as JSON. This JSON should be in the following form: an array of objects. There should be one object for each numbered discovery request. The object should contain two key/value pairs: first, a “requestId". This key's value will be a randomly generated, version 4 UUID The second key is ”text", its value will be the substantive content of the individual request. This is an example response to a hypothetical sequence of three requests: [{ "requestId": "73a855af-4fdc-4b8b-9e7f-34d57a2c084a",
"text": "example - you would put an individual request here.”}, { "requestId": "36fe8375-240d-4a08-8a71-9b2ba5bda348",
"text": "example - you would put an individual request here."}, { "requestId": "cfaf4a36-20de-44ff-8673-5a725bddca03",
"text": "you would put an individual request here.“}]. Some documents may contain sections before the requests. such as “Definitions”, or “Instructions,” do not include definitions, instructions or any other text that precedes the requests. Return the text of the question only, do not respond to it. Note the following CAREFULLY, it is important: some documents may have two kinds of requests - 1. Interrogatories and 2. requests for production of documents. You MUST be sure to include both the interrogatories and the requests for production of documents. Do not add introductory comments, analysis, or observations, such as "Based on your request, I have parsed the document and..," etc. Such comments will be problematic for later. This is the request document: ${request}`,
},
];
return parseRequestsPrompt;
};
module.exports = {
createArrayFromSingleDocPrompt,
createResponseFromOneQuestionPrompt,
createArrayOfInterrogatoriesPlaintiffPrompt,
createArrayOfInterrogatoriesDefendantPrompt,
createVerboseResponseFromOneQuestionPrompt,
createArrayFromStringBlobPrompt,
};
/*
this is used for combined-numbered -- skip right to answers no middle of parsing out the quesitons into an array
const singleDocPrompt = [
{
role: "user",
content: `You are a paralegal assisting trial attorneys in drafting discovery, including responses to interrogatories and requests for production of documents.
Draft a response to the discovery request I will give you,
after some instructions. The instructions: Respond
to each request, wether it is an interrogatory or a request for production. Include only objections, but thoroughly include all possible,
non-frivolous objections. Do not assume facts about the case. Refer to your client, the party
responding here, as 'Respondent'. Begin each response with "RESPONDENT OBJECTS TO THE REQUEST (or, where appropriate,
"RESPONDENT FURTHER OBJECTS"). End each response with 'SUBJECT TO AND WITHOUT WAIVING these
objections, Respondent states as follows:'. Your overall response should be in the form of an array, containing
one JSON object for each discrete response. This JSON object
should contain two key/value pairs with the following data: 1. A “requestId,” the value for this key
will be a randomly-generated version 4 UUID, and 2. "text," the value for this key will be your
substantive response, This is an example to
illustrate form, it exemplifies a hypothetical response sequence : [{ requestId: 73a855af-4fdc-4b8b-9e7f-34d57a2c084a,
text: 'example - response text would be stated here'}, { requestId: 16e82593-0b71-4c1a-9c3c-04f54ec4db9a,
text: 'example - response text would be stated here'}, { requestId: 0fe87371-bee8-439d-a672-bff256c75d43,
text: 'example - response text would be stated here'}]. That concludes the instructions.
This is the request: ${request}`,
},
];
*/

View File

@@ -0,0 +1,153 @@
const fs = require("fs");
const path = require("path");
/*
*
* Strore returned completions
*/
function saveCompletions(responses, folder, reqType, isRequests) {
const data = JSON.stringify(responses);
if (reqType === "") {
}
if (isRequests === true) {
dir = selectRequestPath(reqType, isRequests, folder);
} else {
dir = selectResponsePath(reqType, isRequests, folder);
}
let fileSuffix;
if (isRequests === true) {
fileSuffix = `-jbk-parsedRequests.json`;
} else {
fileSuffix = `-jbk-responses.json`;
}
try {
fs.writeFile(`${dir}${folder}${fileSuffix}`, data, function (err) {
if (err) {
return console.log(
"utilities Error in saveCompletions writeFile:",
err
);
}
});
} catch (err) {
console.log("Error writing file:", err);
}
}
function selectRequestPath(reqType, isRequests, folder) {
let dir;
const fdirup = path.resolve(process.cwd() + "/../Documents/Requests");
const fdir = path.resolve(
process.cwd() + "/../Documents/Requests/Parsedcombined"
);
if (reqType == "interrogatories") {
dir = `${fdirup}/Parsedrogs/${folder}/`;
} else if (reqType == "admissions") {
dir = `${fdirup}/Parsedadmit/${folder}/`;
} else if (reqType == "production") {
dir = `${fdirup}/Parsedprod/${folder}/`;
} else if (reqType == "combined-numbered") {
dir = `${fdir}/${folder}/`;
}
return dir;
}
function selectResponsePath(reqType, isRequests, folder) {
let dir;
//const fdirup = path.resolve(process.cwd() + "/Documents/Responses");
const fdirup = path.join(__dirname, "..", "Documents");
const fdir = path.resolve(
process.cwd() + "/Documents/Responses/Combinedresp"
);
console.log("fdirup in selectResponsePath", fdirup);
if (reqType === "interrogatories") {
dir = `${fdirup}/interrogatories/${folder}/`;
} else if (reqType == "admissions") {
dir = `${fdirup}/admissions/${folder}/`;
} else if (reqType == "production") {
dir = `${fdirup}/production/${folder}/`;
} else if (reqType == "combined-numbered") {
dir = `${fdir}/${folder}/`;
}
console.log("dir returned in selectResponsePath", dir);
return dir;
}
//const directoryPath = `/Users/kjannette/workspace/agentxa2new/Backend/Documents/Textfiles/`;
/**
*
* Takes path to directory returns
* concat path + fileName
*/
async function readDir(docId, direcPath = directoryPath) {
try {
const fullPath = direcPath + `${docId}`;
let fileNames = fs.readdirSync(direcPath);
const dirArray = fileNames.map((name) => {
return direcPath + name;
});
return dirArray;
} catch (err) {
console.log("read error", err);
}
}
/**
* Create directory w/its location based on if
* 1. request or response and
* 2. request/response type
*/
///Users/kjannette/workspace/ax3/ax3Services/Documents/Requests/Parsedcombined
async function makeDir(folder, reqType, isRequests) {
let dir;
if (reqType)
if (isRequests === true) {
dir = selectRequestPath(reqType, isRequests, folder);
} else {
dir = selectResponsePath(reqType, isRequests, folder);
}
console.log("dir in mkDir", dir);
fs.mkdir(`${dir}`, function (err) {
if (err) {
console.log("makeDir utilities error creating directory: " + err);
}
});
}
/**
* Takes an array of file paths, reads all files,
* pushes string contents to an array, then
* joins into massive string to stream to LLM
*
*/
async function iteratePathsReturnString(paths) {
const masterArray = [];
for (let path of paths) {
if (path == undefined || path == null) {
return;
}
const fileData = await fs.promises.readFile(path, "utf8");
masterArray.push(fileData);
}
const massiveString = masterArray.join();
return massiveString;
}
module.exports = {
readDir,
makeDir,
iteratePathsReturnString,
selectResponsePath,
selectRequestPath,
saveCompletions,
};