// Define API settings
const cohereURL = "https://api.cohere.ai/v1/generate";
const openaiURL = "https://api.openai.com/v1/chat/completions";
var apikeyCohere = ""; // Add your Cohere API key
var apikeyOpenAI = ""; // Add your OpenAI API key
// Cohere API call for evaluation
function analyzeWithCohere(text) {
const prompt = `
Analyze the following IELTS writing response:
"${text}"
Provide a detailed evaluation based on:
1. Task Achievement
2. Coherence and Cohesion
3. Lexical Resource
4. Grammatical Range and Accuracy
Provide scores out of 9 for each criterion and suggest improvements.
`;
const requestData = {
model: "command-xlarge-nightly",
prompt: prompt,
max_tokens: 500,
temperature: 0.7,
stop_sequences: ["--"],
};
$.ajax({
type: "POST",
url: cohereURL,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apikeyCohere}`,
},
data: JSON.stringify(requestData),
success: function (response) {
console.log("Cohere API Response:", response); // Log response
const result = response.generations[0]?.text;
if (result) {
displayCohereResults(result); // Pass result to the display function
} else {
$("#cohereOutput").html("<font color=red><b>Invalid response structure from Cohere.</b></font>");
}
},
error: function (xhr) {
console.error("API Error:", xhr.responseText);
$("#cohereOutput").html("<font color=red><b>Error occurred while fetching results from Cohere.</b></font>");
},
});
}
// OpenAI API call for generating a band 9 essay
function generateBand9Essay(question) {
const requestData = {
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: "You are an expert IELTS tutor. Provide responses suitable for Band 9 IELTS essays.",
},
{
role: "user",
content: `Write a band 9 IELTS essay on the following topic:\n"${question}"`,
},
],
max_tokens: 1500,
temperature: 0.7,
};
$.ajax({
type: "POST",
url: openaiURL,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apikeyOpenAI}`,
},
data: JSON.stringify(requestData),
success: function (response) {
if (response && response.choices && response.choices[0] && response.choices[0].message) {
const result = response.choices[0].message.content;
displayOpenAIResults(result);
} else {
$("#openaiOutput").html(
"<font color=red><b>Invalid response structure from OpenAI.</b></font>"
);
}
},
error: function (xhr) {
const errorMsg = xhr.responseJSON ? xhr.responseJSON.error.message : "Unknown error.";
$("#openaiOutput").html(
`<font color=red><b>Error: ${errorMsg}</b></font>`
);
},
});
}
function formatResponse(response) {
// Split the response into sections based on numbers followed by a period
const sections = response.split(/\n(?=\d+\.\s)/).filter((section) => section.trim() !== "");
let formattedHTML = "<div class='results-container'>";
sections.forEach((section) => {
// Match the header (e.g., "1. Task Achievement: 7.5/9") and the rest
const match = section.match(/^(\d+\.\s[A-Za-z\s]+):\s*([\d.]+\/9)(.*)$/s);
if (match) {
const title = match[1].trim(); // Section title
const score = match[2].trim(); // Score
const description = match[3].trim(); // Description (including bullet points)
formattedHTML += `
<div class='result-section'>
<h3 class="section-header">${title}</h3>
<div class="score">Score: <span>${score}</span></div>
<p class="description">${description.replace(/\n/g, "<br>")}</p>
</div>
`;
}
});
formattedHTML += "</div>";
return formattedHTML;
}
function displayCohereResults(result) {
const formattedResult = formatResponse(result);
$("#cohereOutput").html(formattedResult);
}
function displayOpenAIResults(essay) {
const formattedEssay = `<h2>Generated Band 9 Essay:</h2><p>${essay}</p>`;
$("#openaiOutput").html(formattedEssay);
}
// Updated HTML
document.write(`
<div class="container">
<h1>IELTS Writing Evaluator</h1>
<div class="input-container">
<label>Enter your API Keys:</label>
<input type="text" id="apikeyCohere" placeholder="Cohere API Key">
<input type="text" id="apikeyOpenAI" placeholder="OpenAI API Key">
<button id="setApiKeyBtn">Set API Keys</button>
<div id="apiKeyStatus" class="status"></div>
</div>
<div class="input-container">
<label>Enter your IELTS Writing Question:</label>
<textarea id="question" rows="4" placeholder="Type your question here..."></textarea>
<button id="generateEssay">Generate Band 9 Essay</button>
</div>
<div id="openaiOutput" class="output-container"></div>
<div class="input-container">
<label>Enter your IELTS Writing Response:</label>
<textarea id="answer" rows="8" placeholder="Type your response here..."></textarea>
<button id="analyze">Analyze with Cohere</button>
</div>
<div id="cohereOutput" class="output-container"></div>
</div>
`);
// Button behavior
window.onload = function () {
document.getElementById("generateEssay").onclick = function () {
const question = document.getElementById("question").value.trim();
if (!apikeyOpenAI) {
alert("Please set the OpenAI API key before proceeding.");
return;
}
if (!question) {
alert("Please enter a question.");
return;
}
generateBand9Essay(question);
};
document.getElementById("analyze").onclick = function () {
const answer = document.getElementById("answer").value.trim();
if (!apikeyCohere) {
alert("Please set the Cohere API key before proceeding.");
return;
}
if (!answer) {
alert("Please enter an answer.");
return;
}
analyzeWithCohere(answer);
};
document.getElementById("setApiKeyBtn").onclick = function () {
apikeyCohere = document.getElementById("apikeyCohere").value.trim();
apikeyOpenAI = document.getElementById("apikeyOpenAI").value.trim();
if (apikeyCohere && apikeyOpenAI) {
document.getElementById("apiKeyStatus").innerHTML =
"<span class='success'>API Keys have been successfully set.</span>";
} else {
alert("Please enter valid API keys.");
}
};
};
// CSS for Dark Mode and Enhanced Styling
const style = document.createElement("style");
style.textContent =
` body {
background-color: #121212;
color: #ffffff;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
width: 80%;
max-width: 800px;
text-align: center;
background-color: #1e1e1e;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.7);
}
h1 {
color: #ff5722;
margin-bottom: 20px;
}
.input-container {
margin: 20px 0;
text-align: left;
}
label {
font-size: 1.2em;
margin-bottom: 10px;
display: block;
}
input, textarea {
width: 100%;
padding: 10px;
background-color: #2c2c2c;
color: #ffffff;
border: 2px solid #ff5722;
border-radius: 5px;
margin-bottom: 10px;
}
textarea {
resize: vertical;
}
button {
background-color: #ff5722;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 1em;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #ff3d00;
}
.status {
margin-top: 10px;
font-size: 1em;
}
.success {
color: #76ff03;
}
.output-container {
margin-top: 20px;
padding: 20px;
background-color: #2c2c2c;
border: 2px solid #ff5722;
border-radius: 5px;
}
.results-container {
display: flex;
flex-direction: column;
gap: 15px;
}
.result-section {
background-color: #2c2c2c;
padding: 15px;
border: 1px solid #ff5722;
border-radius: 8px;
margin-bottom: 15px;
}
.section-header {
color: #ff5722;
text-shadow: 0 0 10px #ff5722;
font-size: 1.5em;
margin-bottom: 5px;
}
.score {
color: #76ff03;
font-weight: bold;
font-size: 1.2em;
margin-bottom: 10px;
}
.description {
color: #ffffff;
font-size: 1em;
line-height: 1.5;
}
h3 {
color: #ffab91;
margin-bottom: 5px;
text-shadow: none;
}
;`
document.head.appendChild(style);