@postalsys/email-ai-tools 1.14.14 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,400 +0,0 @@
1
- 'use strict';
2
-
3
- const { apiRequest } = require('./api-request');
4
- const { estimateTokens, fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS } = require('./token-estimate');
5
-
6
- const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
7
-
8
- const OPENAI_API_URL_CHAT = '/v1/chat/completions';
9
- const OPENAI_API_URL_INSTRUCT = '/v1/completions';
10
-
11
- const DEFAULT_SYSTEM_PROMPT = `
12
- You are an automated system designed to extract and provide information based on stored emails.
13
- `.trim();
14
-
15
- const SCHEMA_PROMPT = `
16
- **Input Information:**
17
-
18
- - **Question Format:** The query is presented using the JSON schema: \`{"name": "John Doe", "email": "john@example.com", "question":"What was the date of our last meeting?"}\`
19
-
20
- - **Question Structure** The question format includes the asked question, and the name and the email address of the user who asked the question, if available.
21
-
22
- - **Email Context:** We are provided with a series of emails to analyze.
23
-
24
- - **Email Structure:** Each email is divided into two sections: a header and its content. These sections are separated by an empty line.
25
-
26
- - **Email Content:** This pertains exclusively to the plain text of the email. No attachments or their contents are provided.
27
-
28
- - **Sample Header:**
29
- \`\`\`
30
- - EMAIL #1:
31
- From: James <james@example.com>
32
- To: Andris <andris@example.com>
33
- Subject: Hello
34
- Message-ID: <example@value>
35
- Date: 1 Oct 2023 06:30:26 +0200
36
- Attachments: image.png, invoice.pdf
37
- \`\`\`
38
-
39
- - Every header starts with the string \`- EMAIL #\` followed by the email sequence number
40
- - **Mandatory Field:** Every email will contain a unique Message-ID.
41
- - **Date Field:** Represents the timestamp when the email was sent.
42
- - **Attachments:** This field, when present, lists the names of attachments included with the email, separated by commas.
43
-
44
- **Output Guidelines:**
45
-
46
- 1. Answer the user's question using only the provided context information.
47
- 2. Your objective is to sift through the email context and pinpoint the answer that best addresses the given query.
48
- 3. If no email matches the query criteria, or if the match is ambiguous, refrain from providing an answer.
49
- 4. Limit your sources strictly to the provided email context. External references are not to be utilized.
50
- 5. Format your response as follows:
51
- - Start with \`Answer:\` followed by the relevant information.
52
- - On a new line, begin with \`Message-ID:\` and cite the unique Message-ID(s) of the emails you sourced your answer from.
53
- 6. Ensure that the Message-ID is never embedded within the main body of your response.
54
- 7. Avoid including any additional commentary or annotations.
55
-
56
- **Context**:
57
-
58
- - The current time is '${new Date().toUTCString()}'.
59
- `.trim();
60
-
61
- const QUESTION_PROMPT = `
62
- Instructions:
63
-
64
- You are analyzing user questions regarding email retrieval from a database. From the user's query, determine:
65
-
66
- 1. **Order Preference**:
67
- - Retrieve older emails first ('older_first').
68
- - Retrieve newer emails first ('newer_first').
69
- - If no specific order is discernible from the query, identify the most relevant email ('best_match'), based on keywords or subjects that closely align with the user's question.
70
-
71
- 2. **Time Constraints**:
72
- - Identify the starting point for the query ('start_time').
73
- - Identify when to stop the query ('end_time').
74
-
75
- 3. **Topic for the Hypothetical Answer**:
76
- - Try to answer the question without knowing the actual context and generate a topic for the answer.
77
- - For missing context assume any generic or likely value
78
-
79
- **Context**:
80
-
81
- - The current time is '${new Date().toUTCString()}'.
82
-
83
- **Output Guidelines**:
84
-
85
- - For terms implying a near-future context (e.g., "next", "newest", "upcoming"), opt for the 'newer_first' ordering.
86
- - For terms implying a distant past (e.g., "oldest"), use the 'older_first' ordering.
87
- - For terms implying ordering by time:
88
- - start of the list (e.g., "first"), use the 'older_first' ordering.
89
- - end of the list (e.g., "last", "latest"), opt for the 'newer_first' ordering.
90
- - If the user's query does not provide a clear time frame, or if the system's confidence in deducing a timeframe is below 70%, exclude 'start_time' and 'end_time' from the output.
91
- - If the deduced 'end_time' aligns with current time, omit the 'end_time'.
92
- - For unspecified time zones, timestamps should follow the 'YYYY-MM-DD hh:mm:ss' format.
93
- - If only the date is known, use the 'YYYY-MM-DD' format.
94
- - Assume the week starts on Monday.
95
- - Identify the topic for the question.
96
- - Your response should be structured in JSON, strictly adhering to the schema:
97
- \`\`\`
98
- {
99
- "ordering": "",
100
- "start_time": "",
101
- "end_time": "",
102
- "topic": ""
103
- }
104
- \`\`\`
105
- - Example Queries and Responses:
106
- - **Query**: "When is the next conference event?"
107
- **Response**: \`{"ordering":"newer_first", "topic": "Conference event happening next week"}\`
108
- - **Query**: "What did James write to me about last Friday?" (assuming that current time is "2023-10-02")
109
- **Response**: \`{"ordering":"best_match", "start_time": "2023-09-29", "end_time": "2023-09-30", "topic": "A message from James about an event in 2023-09-30"}\`
110
- - **Query**: "When did I receive my first Amazon invoice?"
111
- **Response**: \`{"ordering":"older_first", "topic": "Amazon invoice"}\`
112
-
113
- **User's Query**:
114
- Process the user question:
115
- `.trim();
116
-
117
- async function embeddingsQuery(apiToken, opts) {
118
- opts = opts || {};
119
-
120
- let baseApiUrl = opts.baseApiUrl || OPENAI_API_BASE_URL;
121
-
122
- let systemPrompt = (opts.systemPrompt || DEFAULT_SYSTEM_PROMPT).toString().trim();
123
- let question = (opts.question || '').toString().trim();
124
- let contextChunks = (opts.contextChunks || '').toString().trim();
125
-
126
- let maxAllowedTokens = opts.maxTokens || DEFAULT_MAX_ALLOWED_TOKENS;
127
- let gptModel = opts.gptModel || 'gpt-5-mini';
128
-
129
- const { prompt, charactersRemoved } = fitPrompt({
130
- text: contextChunks,
131
- maxTokens: maxAllowedTokens,
132
- build: contextText => `${SCHEMA_PROMPT}
133
-
134
- **Input**:
135
- ${JSON.stringify({ name: opts?.userData?.name, email: opts?.userData?.email, question })}
136
-
137
- **Context emails**:
138
-
139
- ${contextText}
140
- `
141
- });
142
-
143
- let payload = {
144
- model: gptModel
145
- };
146
-
147
- if (opts.user) {
148
- payload.user = opts.user;
149
- }
150
-
151
- if (opts.temperature && !isNaN(opts.temperature)) {
152
- payload.temperature = Number(opts.temperature);
153
- }
154
-
155
- if (opts.topP && !isNaN(opts.topP)) {
156
- payload.top_p = Number(opts.topP);
157
- }
158
-
159
- let openAiAPIURL;
160
- switch (gptModel) {
161
- case 'gpt-3.5-turbo-instruct':
162
- {
163
- openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_URL_INSTRUCT);
164
- payload.prompt = `${systemPrompt}\n${prompt}`;
165
- payload.max_tokens = 4000 - estimateTokens(payload.prompt);
166
- }
167
- break;
168
-
169
- case 'gpt-3.5-turbo':
170
- case 'gpt-4':
171
- default:
172
- openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_URL_CHAT);
173
- payload.messages = [
174
- {
175
- role: 'system',
176
- content: `${systemPrompt}`
177
- },
178
- {
179
- role: 'user',
180
- content: prompt
181
- }
182
- ];
183
- break;
184
- }
185
-
186
- const { data, time } = await apiRequest(openAiAPIURL, {
187
- apiToken,
188
- payload,
189
- dispatcher: opts.dispatcher,
190
- signal: opts.signal,
191
- verbose: opts.verbose
192
- });
193
-
194
- let output =
195
- data &&
196
- data.choices &&
197
- data.choices
198
- .filter(msg => msg && ((msg.message && msg.message.role === 'assistant' && msg.message.content) || msg.text))
199
- .sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0))
200
- .map(msg => (msg.message && msg.message.content) || msg.text)
201
- .join('')
202
- .trim();
203
-
204
- let responseValues = { answer: '', 'message-id': '' };
205
- let curKey;
206
- output
207
- .trim()
208
- .replace(/\r?\n/g, '\n')
209
- .split(/(^|\n)(?:[*`]*)(Answer:|Message-ID:)(?:[*`]*)/gi)
210
- .map(v => v.trim())
211
- .filter(v => v)
212
- .forEach(val => {
213
- if (/^(answer|message-id):$/i.test(val)) {
214
- curKey = val.replace(/:$/, '').trim().toLowerCase();
215
- return;
216
- }
217
-
218
- if (!curKey || !val) {
219
- return;
220
- }
221
-
222
- if (curKey === 'message-id') {
223
- val = val
224
- .split(/,/)
225
- .map(v => v.trim())
226
- .filter(v => v)
227
- .join('\n');
228
- }
229
-
230
- if (!responseValues[curKey]) {
231
- responseValues[curKey] = val;
232
- } else {
233
- responseValues[curKey] += '\n' + val;
234
- }
235
- });
236
-
237
- if (responseValues['message-id']) {
238
- responseValues.messageId = Array.from(new Set(responseValues['message-id'].split(/\n/)));
239
- }
240
- delete responseValues['message-id'];
241
-
242
- const response = Object.assign({ id: null, tokens: null, model: null }, responseValues, {
243
- id: data && data.id,
244
- tokens: data && data.usage && data.usage.total_tokens,
245
- model: gptModel
246
- });
247
-
248
- if (opts.verbose) {
249
- response._time = time;
250
- response._cr = charactersRemoved;
251
- }
252
-
253
- return response;
254
- }
255
-
256
- async function questionQuery(question, apiToken, opts) {
257
- opts = opts || {};
258
-
259
- let baseApiUrl = opts.baseApiUrl || OPENAI_API_BASE_URL;
260
-
261
- let systemPrompt = (opts.systemPrompt || DEFAULT_SYSTEM_PROMPT).toString().trim();
262
- question = (question || '').toString().trim();
263
- if (!question) {
264
- let error = new Error('Question not provided');
265
- error.code = 'EmptyInput';
266
- throw error;
267
- }
268
-
269
- let gptModel = opts.gptModel || 'gpt-3.5-turbo-instruct';
270
-
271
- let prompt = `${QUESTION_PROMPT}
272
- ${question}
273
- `;
274
-
275
- let payload = {
276
- model: gptModel
277
- };
278
-
279
- if (opts.user) {
280
- payload.user = opts.user;
281
- }
282
-
283
- if (opts.temperature && !isNaN(opts.temperature)) {
284
- payload.temperature = Number(opts.temperature);
285
- } else {
286
- payload.temperature = 0.2;
287
- }
288
-
289
- if (opts.topP && !isNaN(opts.topP)) {
290
- payload.top_p = Number(opts.topP);
291
- }
292
-
293
- let openAiAPIURL;
294
- switch (gptModel) {
295
- case 'gpt-3.5-turbo-instruct':
296
- {
297
- openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_URL_INSTRUCT);
298
- payload.prompt = `${systemPrompt}\n${prompt}`;
299
- payload.max_tokens = 4000 - estimateTokens(payload.prompt);
300
- }
301
- break;
302
-
303
- case 'gpt-3.5-turbo':
304
- case 'gpt-4':
305
- default:
306
- openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_URL_CHAT);
307
- payload.messages = [
308
- {
309
- role: 'system',
310
- content: `${systemPrompt}`
311
- },
312
- {
313
- role: 'user',
314
- content: prompt
315
- }
316
- ];
317
- break;
318
- }
319
-
320
- const { data, time } = await apiRequest(openAiAPIURL, {
321
- apiToken,
322
- payload,
323
- dispatcher: opts.dispatcher,
324
- signal: opts.signal,
325
- verbose: opts.verbose
326
- });
327
-
328
- let values;
329
- let output =
330
- data &&
331
- data.choices &&
332
- data.choices
333
- .filter(msg => msg && ((msg.message && msg.message.role === 'assistant' && msg.message.content) || msg.text))
334
- .sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0))
335
- .map(msg => (msg.message && msg.message.content) || msg.text)
336
- .join('')
337
- .trim();
338
-
339
- try {
340
- let objStart = output.indexOf('{');
341
- let objEnd = output.lastIndexOf('}');
342
-
343
- if (objStart < 0 || objEnd < 0 || objEnd <= objStart) {
344
- let error = new Error('Invalid JSON object');
345
- error.objStart = objStart;
346
- error.objEnd = objEnd;
347
- throw error;
348
- }
349
-
350
- // remove potential comments before and after the JSON output
351
- if (objEnd < output.length - 1) {
352
- output = output.substring(0, objEnd + 1);
353
- }
354
-
355
- if (objStart > 0) {
356
- output = output.substring(objStart);
357
- }
358
-
359
- values = JSON.parse(output);
360
-
361
- let walkAndRemoveNull = branch => {
362
- if (typeof branch !== 'object' || !branch) {
363
- return;
364
- }
365
- for (let key of Object.keys(branch)) {
366
- let subBranch = branch[key];
367
- if (Array.isArray(subBranch)) {
368
- for (let entry of subBranch) {
369
- walkAndRemoveNull(entry);
370
- }
371
- } else if (subBranch && typeof subBranch === 'object') {
372
- walkAndRemoveNull(subBranch);
373
- } else if (!['boolean', 'string', 'number'].includes(typeof subBranch) || subBranch === '') {
374
- delete branch[key];
375
- }
376
- }
377
- };
378
-
379
- walkAndRemoveNull(values);
380
- } catch (err) {
381
- let error = new Error('Failed to parse output from OpenAI API', { cause: err });
382
- error.textContent = output;
383
- error.code = 'OutputParseFailed';
384
- throw error;
385
- }
386
-
387
- const response = Object.assign({ id: null, tokens: null, model: null }, values || {}, {
388
- id: data && data.id,
389
- tokens: data && data.usage && data.usage.total_tokens,
390
- model: gptModel
391
- });
392
-
393
- if (opts.verbose) {
394
- response._time = time;
395
- }
396
-
397
- return response;
398
- }
399
-
400
- module.exports = { embeddingsQuery, questionQuery };