ai.services.ts212 lines, 8.0 KB
| 1 | import redis from "../config/redis"; |
| 2 | import { getDocument } from "pdfjs-dist"; |
| 3 | import { GoogleGenerativeAI } from "@google/generative-ai"; |
| 4 | |
| 5 | const AI_MODEL = "gemini-pro"; |
| 6 | const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!); |
| 7 | const aiModel = genAI.getGenerativeModel({ model: AI_MODEL }); |
| 8 | |
| 9 | export const extractTextFromPDF = async (fileKey: string) => { |
| 10 | try { |
| 11 | const fileData = await redis.get(fileKey); |
| 12 | if (!fileData) { |
| 13 | throw new Error("File not found"); |
| 14 | } |
| 15 | |
| 16 | let fileBuffer: Uint8Array; |
| 17 | if (Buffer.isBuffer(fileData)) { |
| 18 | fileBuffer = new Uint8Array(fileData); |
| 19 | } else if (typeof fileData === "object" && fileData !== null) { |
| 20 | // check if the the object has the expected structure |
| 21 | const bufferData = fileData as { type?: string; data?: number[] }; |
| 22 | if (bufferData.type === "Buffer" && Array.isArray(bufferData.data)) { |
| 23 | fileBuffer = new Uint8Array(bufferData.data); |
| 24 | } else { |
| 25 | throw new Error("Invalid file data"); |
| 26 | } |
| 27 | } else { |
| 28 | throw new Error("Invalid file data"); |
| 29 | } |
| 30 | |
| 31 | const pdf = await getDocument({ data: fileBuffer }).promise; |
| 32 | let text = ""; |
| 33 | for (let i = 1; i <= pdf.numPages; i++) { |
| 34 | const page = await pdf.getPage(i); |
| 35 | const content = await page.getTextContent(); |
| 36 | text += content.items.map((item: any) => item.str).join(" ") + "\n"; |
| 37 | } |
| 38 | return text; |
| 39 | } catch (error) { |
| 40 | console.log(error); |
| 41 | throw new Error( |
| 42 | `Failed to extract text from PDF. Error: ${JSON.stringify(error)}` |
| 43 | ); |
| 44 | } |
| 45 | }; |
| 46 | |
| 47 | export const detectContractType = async ( |
| 48 | contractText: string |
| 49 | ): Promise<string> => { |
| 50 | const prompt = ` |
| 51 | Analyze the following contract text and determine the type of contract it is. |
| 52 | Provide only the contract type as a single string (e.g., "Employment", "Non-Disclosure Agreement", "Sales", "Lease", etc.). |
| 53 | Do not include any additional explanation or text. |
| 54 | |
| 55 | Contract text: |
| 56 | ${contractText.substring(0, 2000)} |
| 57 | `; |
| 58 | |
| 59 | const results = await aiModel.generateContent(prompt); |
| 60 | const response = results.response; |
| 61 | return response.text().trim(); |
| 62 | }; |
| 63 | |
| 64 | export const analyzeContractWithAI = async ( |
| 65 | contractText: string, |
| 66 | tier: "free" | "premium", |
| 67 | contractType: string |
| 68 | ) => { |
| 69 | let prompt; |
| 70 | if (tier === "premium") { |
| 71 | prompt = ` |
| 72 | Analyze the following ${contractType} contract and provide: |
| 73 | 1. A list of at least 10 potential risks for the party receiving the contract, each with a brief explanation and severity level (low, medium, high). |
| 74 | 2. A list of at least 10 potential opportunities or benefits for the receiving party, each with a brief explanation and impact level (low, medium, high). |
| 75 | 3. A comprehensive summary of the contract, including key terms and conditions. |
| 76 | 4. Any recommendations for improving the contract from the receiving party's perspective. |
| 77 | 5. A list of key clauses in the contract. |
| 78 | 6. An assessment of the contract's legal compliance. |
| 79 | 7. A list of potential negotiation points. |
| 80 | 8. The contract duration or term, if applicable. |
| 81 | 9. A summary of termination conditions, if applicable. |
| 82 | 10. A breakdown of any financial terms or compensation structure, if applicable. |
| 83 | 11. Any performance metrics or KPIs mentioned, if applicable. |
| 84 | 12. A summary of any specific clauses relevant to this type of contract (e.g., intellectual property for employment contracts, warranties for sales contracts). |
| 85 | 13. An overall score from 1 to 100, with 100 being the highest. This score represents the overall favorability of the contract based on the identified risks and opportunities. |
| 86 | |
| 87 | Format your response as a JSON object with the following structure: |
| 88 | { |
| 89 | "risks": [{"risk": "Risk description", "explanation": "Brief explanation", "severity": "low|medium|high"}], |
| 90 | "opportunities": [{"opportunity": "Opportunity description", "explanation": "Brief explanation", "impact": "low|medium|high"}], |
| 91 | "summary": "Comprehensive summary of the contract", |
| 92 | "recommendations": ["Recommendation 1", "Recommendation 2", ...], |
| 93 | "keyClauses": ["Clause 1", "Clause 2", ...], |
| 94 | "legalCompliance": "Assessment of legal compliance", |
| 95 | "negotiationPoints": ["Point 1", "Point 2", ...], |
| 96 | "contractDuration": "Duration of the contract, if applicable", |
| 97 | "terminationConditions": "Summary of termination conditions, if applicable", |
| 98 | "overallScore": "Overall score from 1 to 100", |
| 99 | "financialTerms": { |
| 100 | "description": "Overview of financial terms", |
| 101 | "details": ["Detail 1", "Detail 2", ...] |
| 102 | }, |
| 103 | "performanceMetrics": ["Metric 1", "Metric 2", ...], |
| 104 | "specificClauses": "Summary of clauses specific to this contract type" |
| 105 | } |
| 106 | `; |
| 107 | } else { |
| 108 | prompt = ` |
| 109 | Analyze the following ${contractType} contract and provide: |
| 110 | 1. A list of at least 5 potential risks for the party receiving the contract, each with a brief explanation and severity level (low, medium, high). |
| 111 | 2. A list of at least 5 potential opportunities or benefits for the receiving party, each with a brief explanation and impact level (low, medium, high). |
| 112 | 3. A brief summary of the contract |
| 113 | 4. An overall score from 1 to 100, with 100 being the highest. This score represents the overall favorability of the contract based on the identified risks and opportunities. |
| 114 | |
| 115 | { |
| 116 | "risks": [{"risk": "Risk description", "explanation": "Brief explanation"}], |
| 117 | "opportunities": [{"opportunity": "Opportunity description", "explanation": "Brief explanation"}], |
| 118 | "summary": "Brief summary of the contract", |
| 119 | "overallScore": "Overall score from 1 to 100" |
| 120 | } |
| 121 | `; |
| 122 | } |
| 123 | |
| 124 | prompt += ` |
| 125 | Important: Provide only the JSON object in your response, without any additional text or formatting. |
| 126 | |
| 127 | |
| 128 | Contract text: |
| 129 | ${contractText} |
| 130 | `; |
| 131 | |
| 132 | const results = await aiModel.generateContent(prompt); |
| 133 | const response = await results.response; |
| 134 | let text = response.text(); |
| 135 | |
| 136 | // remove any markdown formatting |
| 137 | text = text.replace(/```json\n?|\n?```/g, "").trim(); |
| 138 | |
| 139 | try { |
| 140 | // Attempt to fix common JSON errors |
| 141 | text = text.replace(/([{,]\s*)(\w+)(\s*:)/g, '$1"$2"$3'); // Ensure all keys are quoted |
| 142 | text = text.replace(/:\s*"([^"]*)"([^,}\]])/g, ': "$1"$2'); // Ensure all string values are properly quoted |
| 143 | text = text.replace(/,\s*}/g, "}"); // Remove trailing commas |
| 144 | |
| 145 | const analysis = JSON.parse(text); |
| 146 | return analysis; |
| 147 | } catch (error) { |
| 148 | console.log("Error parsing JSON:", error); |
| 149 | } |
| 150 | |
| 151 | interface IRisk { |
| 152 | risk: string; |
| 153 | explanation: string; |
| 154 | } |
| 155 | |
| 156 | interface IOpportunity { |
| 157 | opportunity: string; |
| 158 | explanation: string; |
| 159 | } |
| 160 | |
| 161 | interface FallbackAnalysis { |
| 162 | risks: IRisk[]; |
| 163 | opportunities: IOpportunity[]; |
| 164 | summary: string; |
| 165 | } |
| 166 | |
| 167 | const fallbackAnalysis: FallbackAnalysis = { |
| 168 | risks: [], |
| 169 | opportunities: [], |
| 170 | summary: "Error analyzing contract", |
| 171 | }; |
| 172 | |
| 173 | // Extract risks |
| 174 | const risksMatch = text.match(/"risks"\s*:\s*\[([\s\S]*?)\]/); |
| 175 | if (risksMatch) { |
| 176 | fallbackAnalysis.risks = risksMatch[1].split("},").map((risk) => { |
| 177 | const riskMatch = risk.match(/"risk"\s*:\s*"([^"]*)"/); |
| 178 | const explanationMatch = risk.match(/"explanation"\s*:\s*"([^"]*)"/); |
| 179 | return { |
| 180 | risk: riskMatch ? riskMatch[1] : "Unknown", |
| 181 | explanation: explanationMatch ? explanationMatch[1] : "Unknown", |
| 182 | }; |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | //Extact opportunities |
| 187 | const opportunitiesMatch = text.match(/"opportunities"\s*:\s*\[([\s\S]*?)\]/); |
| 188 | if (opportunitiesMatch) { |
| 189 | fallbackAnalysis.opportunities = opportunitiesMatch[1] |
| 190 | .split("},") |
| 191 | .map((opportunity) => { |
| 192 | const opportunityMatch = opportunity.match( |
| 193 | /"opportunity"\s*:\s*"([^"]*)"/ |
| 194 | ); |
| 195 | const explanationMatch = opportunity.match( |
| 196 | /"explanation"\s*:\s*"([^"]*)"/ |
| 197 | ); |
| 198 | return { |
| 199 | opportunity: opportunityMatch ? opportunityMatch[1] : "Unknown", |
| 200 | explanation: explanationMatch ? explanationMatch[1] : "Unknown", |
| 201 | }; |
| 202 | }); |
| 203 | } |
| 204 | |
| 205 | // Extract summary |
| 206 | const summaryMatch = text.match(/"summary"\s*:\s*"([^"]*)"/); |
| 207 | if (summaryMatch) { |
| 208 | fallbackAnalysis.summary = summaryMatch[1]; |
| 209 | } |
| 210 | |
| 211 | return fallbackAnalysis; |
| 212 | }; |