Skip to content

Instantly share code, notes, and snippets.

@polyakovin
Created November 23, 2022 11:28
Show Gist options
  • Save polyakovin/113356786727130ebd4db69cdd002daf to your computer and use it in GitHub Desktop.
Save polyakovin/113356786727130ebd4db69cdd002daf to your computer and use it in GitHub Desktop.
const csvToJson = require('convert-csv-to-json');
const { Configuration, CreateCompletionResponse, OpenAIApi } = require('openai');
const Fuse = require('fuse.js');
const fileInputName = 'test.csv';
const json = csvToJson.getJsonFromCsv(fileInputName);
const data = json
.filter(({ AssociatedCompany }) => AssociatedCompany)
.map(
({ RecordID, FirstName, LastName, LifecycleStage, AssociatedCompany, AssociatedDeal }) =>
({ RecordID, FirstName, LastName, LifecycleStage, AssociatedCompany, AssociatedDeal })
)
const openai = new OpenAIApi(
new Configuration({
apiKey: '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',
})
)
const options = {
// isCaseSensitive: false,
// includeScore: false,
// shouldSort: true,
// includeMatches: false,
// findAllMatches: false,
// minMatchCharLength: 1,
// location: 0,
threshold: 0.6,
// distance: 100,
// useExtendedSearch: false,
// ignoreLocation: false,
// ignoreFieldNorm: false,
// fieldNormWeight: 1,
keys: [
'AssociatedCompany',
]
};
const fuse = new Fuse(data, options);
const actions = [
{
code: 'add_note_to_existing_deal',
examples: [
// 'Закинь в ноутс в сделку DEAL',
// 'Добавь EMAIL[] в сделку DEAL',
// 'Поставь задачку, чтобы я связался с COMPANY on DATE',
// 'Поставь напоминалку, чтобы я связался с COMPANY on DATE',
// 'Throw in the notes of DEAL deal',
// 'Add EMAIL[] to DEAL',
// 'Set task for me to contact COMPANY on DATE',
// 'Set reminder for me to contact COMPANY on DATE',
'Throw in the notes of DEAL deal: NOTES',
'Add EMAIL[] to DEAL',
'Set task for me to contact COMPANY on DATE',
'Set reminder for me to contact COMPANY on DATE',
],
},
{
code: 'add_new_deal',
examples: [
// 'Сделай сделку DEAL',
// 'Заведи сделки DEAL[] и вбей контакты EMAIL[]', // несколько сделок
// 'Создать новую оптю (opportunity) на клиента COMPANY на базовый контракт на период с DATE по DATE со стоимостью AMOUNT',
// 'Запиши клиента COMPANY на стандартный объём услуг', // Стандартный шаблон комм предложения, который генерит драфт на таких-то условиях
// 'Create deal DEAL',
// 'Make deals DEAL[] and add contacts EMAIL[]',
// 'Create new opportunity for COMPANY from DATE to DATE with a cost of AMOUNT',
// 'Note a client COMPANY for a standard scope of services',
'Create deal DEAL',
'Make deals DEAL[] and add contacts EMAIL[]',
'Create new opportunity for COMPANY from DATE to DATE with a cost of AMOUNT',
'Note a client COMPANY for a standard scope of services',
],
},
{
code: 'update_deal_status',
examples: [
// 'Повысить вероятность реализации контракта DEAL до 60%',
// 'Изменить ожидаемую дату реализации проекта DEAL на DATE',
// 'Increase probability of implementing DEAL contract to 60%',
// 'Change the expected implementation date of DEAL to DATE',
'Increase probability of implementing DEAL contract to 60%',
'Change the expected implementation date of DEAL to DATE',
],
},
];
// Контракт
async function getNumberedCompletion(prompt, options) {
const params = {
prompt,
model: 'text-davinci-002',
temperature: 0.1,
max_tokens: 128,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
stop: ['"""'],
};
const completionResponse = await openai.createCompletion({ ...params, ...(options ?? {}) });
const responseData = completionResponse.data;
const completion = responseData.choices?.[0]?.text?.trim();
// console.log(responseData.choices);
return (new NumberedCompletion(completion)).numberedCompletions;
}
class NumberedCompletion {
numberedCompletions;
constructor(rawCompletion) {
this.numberedCompletions = this.parseCompletion(rawCompletion);
}
get(number) {
return this.numberedCompletions.get(number - 1) ?? null;
}
parseCompletion(completion) {
return completion.trim();
// const lines = completion.trim().split('\n');
// const entries = lines.map((line, index) => {
// const str = line.trim().replace(/^\d+\.\s*/, '');
// if (str === '' || str.toLowerCase() === 'unknown' || str.toLowerCase() === 'none') {
// return [index, null];
// }
// return [index, str.trim()];
// })
// return new Map(entries);
}
}
// console.log(data.length, data[0]);
const getCompanyName = async (text) => {
return await getNumberedCompletion(`
Extract company name from the freeform text:
Company Name
"""
Set task for me to contact Coca-Cola on 12/01/23
"""
Coca-Cola
"""
Заключить контракт с ООО "Ромашка"
"""
ООО "Ромашка"
"""
Note a client mercedes for a standard scope of services
"""
Mercedes
"""
${text}
"""
`);
}
(async () => {
const phrase = process.argv[2];
const companyName = await getCompanyName(phrase);
console.log(companyName);
console.log(fuse.search(companyName).slice(0, 2));
// console.log(data.find(({ AssociatedCompany }) => companyName.toLowerCase() === AssociatedCompany?.toLowerCase()));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment