The askLlamaWriteEssay
function uses LLM to generate an essay on a given topic by creating a chapter outline, selecting a random name, and writing long essay sections for each chapter.
The askLlamaWriteEssay
function uses LLM to generate an essay on a given topic by creating a chapter outline and writing long essay sections for each chapter. The function selects a random name for the essay and uses Markdown to format the chapter titles and descriptions.
npm run import -- "research paper llm"
const fs = require('fs')
const {Remarkable} = require('remarkable');
const md = new Remarkable({html: true, xhtmlOut: true, breaks: true});
const {safeurl} = importer.import("domain cache tools")
const selectModel = importer.import("select llm")
const askLlamaForAChapterSynopsis = importer.import("ask llm to write chapter titles and descriptions")
const PROJECT_PATH = path.join(__dirname, '..', 'Resources', 'Projects', 'reasonings')
// write an outline, then loop through outline and ask for entire essays on each subject
async function askLlamaWriteEssay(topic, name, promptModel = 'Qwen') {
if(typeof promptModel != 'function') {
promptModel = await selectModel(promptModel)
}
if(!topic) {
topic = 'metal bonding'
}
let paperName = name
if(!name) {
let q0 = 'Brainstorm 12 funny but creative names for a book involving:\n' + topic
+ '\nRespond with only the list of fun names and nothing else.'
console.log("User: " + q0);
const a0 = await promptModel(q0);
console.log("AI: " + a0);
let names = a0.trim().split(/(^|\s*\n)[0-9]+\.\s*/).filter(a => a && a.trim().length > 0)
paperName = names[Math.round(Math.random() * (names.length-1))]
}
let chapters = await askLlamaForAChapterSynopsis('a research paper named ' + paperName + ' on the topic ' + topic + ' including an introduction, background information, and new research information in the chapter outline.', 'sections')
let keys = Object.keys(chapters)
let bookChapters = []
for(let i = 0; i < keys.length; i++) {
let q1
if(i == 0) {
q1 = 'Write a long essay section introducing the topic, discard any synopsis or conclusions:' + topic + '\n' + keys[i] + '\n' + chapters[keys[i]]
} else {
q1 = 'Write a long essay section about ' + keys[i] + '\n' + chapters[keys[i]] + '\nOn the topic of ' + topic + '\nDiscard any synopsis or conclusions.'
}
console.log("User: " + q1);
const a1 = await promptModel(q1);
console.log("AI: " + a1);
bookChapters[i] = '## Chapter ' + (i + 1) + ' - ' + keys[i] + '\n' + a1
}
let q3 = 'Generate an abstract for this research paper:\n' + Object.values(chapters).join('\n')
console.log("User: " + q3);
const a3 = await promptModel(q3);
console.log("AI: " + a3);
const mdHtml = md.render('# ' + paperName
+ '\n## Abstract\n' + a3 +
+ '\n' + bookChapters.join('\n'))
const filename = path.join(PROJECT_PATH, safeurl((new Date).toISOString() + '-' + topic) + '.html')
fs.writeFileSync(filename, mdHtml)
return mdHtml
}
module.exports = askLlamaWriteEssay
```javascript
import { fileURLToPath, path } from 'node:url';
import { writeFileSync } from 'node:fs';
import Remarkable from'remarkable';
import importer from './importer.js';
const { safeurl } = importer.import('domain cache tools');
const selectModel = importer.import('select llm');
const askLlamaForAChapterSynopsis = importer.import('ask llm to write chapter titles and descriptions');
const PROJECT_PATH = fileURLToPath(new URL('../Resources/Projects/reasonings', import.meta.url));
/**
* Asks Llama to write an essay on a given topic.
* @param {string} topic - The topic to write about.
* @param {string} name - The name of the paper. If not provided, a name will be generated.
* @param {string} [promptModel='Qwen'] - The model to use for prompting Llama.
* @returns {string} The HTML content of the generated paper.
*/
async function askLlamaWriteEssay(topic, name, promptModel = 'Qwen') {
if (typeof promptModel!== 'function') {
// Use the selected model if not a function
promptModel = await selectModel(promptModel);
}
// Default topic if not provided
topic = topic ||'metal bonding';
/**
* Generates a name for the paper if none is provided.
* @returns {string} The generated name.
*/
function generatePaperName() {
const q0 = `Brainstorm 12 funny but creative names for a book involving:
${topic}
Respond with only the list of fun names and nothing else.`;
console.log(`User: ${q0}`);
const a0 = await promptModel(q0);
console.log(`AI: ${a0}`);
const names = a0.trim().split(/(^|\s*\n)[0-9]+\.\s*/).filter((a) => a && a.trim().length > 0);
return names[Math.round(Math.random() * (names.length - 1))];
}
// Generate a name for the paper if not provided
let paperName = name;
if (!name) {
paperName = generatePaperName();
}
// Get the chapters for the paper
const chapters = await askLlamaForAChapterSynopsis(
`a research paper named ${paperName} on the topic ${topic} including an introduction, background information, and new research information in the chapter outline.`,
'sections'
);
// Initialize the book chapters array
const bookChapters = [];
// Loop through the chapters and ask for an essay on each one
for (const key in chapters) {
const chapter = chapters[key];
const q1 = `Write a long essay section about ${key}
${chapter}
On the topic of ${topic}
Discard any synopsis or conclusions.`;
console.log(`User: ${q1}`);
const a1 = await promptModel(q1);
console.log(`AI: ${a1}`);
// Add the chapter to the book chapters array
bookChapters.push(`## Chapter ${bookChapters.length + 1} - ${key}
${a1}`);
}
// Generate an abstract for the paper
const q3 = `Generate an abstract for this research paper:
${Object.values(chapters).join('\n')}`;
console.log(`User: ${q3}`);
const a3 = await promptModel(q3);
console.log(`AI: ${a3}`);
// Render the Markdown content to HTML
const md = new Remarkable({ html: true, xhtmlOut: true, breaks: true });
const mdHtml = md.render(`
# ${paperName}
## Abstract
${a3}
${bookChapters.join('\n')}
`);
// Save the HTML content to a file
const filename = path.join(PROJECT_PATH, safeurl((new Date()).toISOString() + '-' + topic) + '.html');
writeFileSync(filename, mdHtml);
return mdHtml;
}
export default askLlamaWriteEssay;
```
Code Breakdown
The code starts by importing various modules:
fs
(File System) for interacting with the file systemRemarkable
from remarkable
for converting Markdown to HTMLsafeurl
from domain cache tools
selectModel
from select llm
askLlamaForAChapterSynopsis
from ask llm to write chapter titles and descriptions
path
for working with file pathsThe code defines several constants:
PROJECT_PATH
: the path to a project directorymd
: an instance of the Remarkable
class for converting Markdown to HTMLimporter
: a module for importing other modules (not shown)askLlamaWriteEssay
FunctionThe askLlamaWriteEssay
function takes three arguments:
topic
: the topic of the essay (defaults to 'metal bonding'
)name
: the name of the essay (optional)promptModel
: the model to use for generating prompts (defaults to 'Qwen'
)The function:
promptModel
is a function, and if not, selects a model using selectModel
.name
is not provided, prompts the user to come up with a list of funny but creative names for a book on the topic, and selects a random name from the list.askLlamaForAChapterSynopsis
.askLlamaForAChapterSynopsis
function is not shown, but it is likely responsible for generating a chapter outline based on the topic and topic keywords.selectModel
function is not shown, but it is likely responsible for selecting a suitable model for generating prompts.promptModel
function is not shown, but it is likely responsible for generating prompts based on the topic and chapter outline.