CTM-ResearchAgent / script.js
privateuserh's picture
Update script.js
e892728 verified
raw
history blame
3.35 kB
document.addEventListener("DOMContentLoaded", () => {
const workerUrl = "https://ctmresearchagent.aiagents.workers.dev";
const submitButton = document.getElementById("submitButton");
const researchQueryInput = document.getElementById("researchQuery");
const resultDisplay = document.getElementById("resultDisplay");
const historyContainer = document.getElementById("historyContainer");
/**
* --- UPDATED: Submits query to the AI backend ---
*/
async function handleSubmit() {
const query = researchQueryInput.value.trim();
if (!query) {
alert("Please enter a research query.");
return;
}
// Show a loading state
submitButton.disabled = true;
submitButton.innerText = "Thinking...";
resultDisplay.innerHTML = "<p>Generating response...</p>";
try {
// Call the new AI endpoint
const response = await fetch(`${workerUrl}/api/query`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: query }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || "An unknown error occurred.");
}
// Display the real result from the AI
resultDisplay.innerText = data.result;
// Reload history to include the new entry
await loadResearchHistory();
} catch (error) {
console.error("Error fetching AI response:", error);
resultDisplay.innerText = `Error: ${error.message}`;
} finally {
// Restore the button
submitButton.disabled = false;
submitButton.innerText = "Submit";
}
}
/**
* Loads and displays the research history from the backend.
*/
async function loadResearchHistory() {
try {
// Use the correct endpoint for fetching history
const response = await fetch(`${workerUrl}/api/research`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const logs = await response.json();
historyContainer.innerHTML = ""; // Clear existing history
if (logs.length === 0) {
historyContainer.innerHTML = "<p>No research history found.</p>";
return;
}
logs.forEach(log => {
const entryDiv = document.createElement("div");
entryDiv.className = "history-entry";
entryDiv.innerHTML = `
<p><strong>Query:</strong> ${log.query}</p>
<p><strong>Result:</strong> ${log.result}</p>
<p><small><em>${new Date(log.timestamp).toLocaleString()}</em></small></p>
`;
historyContainer.appendChild(entryDiv);
});
} catch (error) {
console.error("Failed to load research history:", error);
historyContainer.innerHTML = "<p>Error loading research history.</p>";
}
}
// Event Listeners
submitButton.addEventListener("click", handleSubmit);
// Initial load of history
loadResearchHistory();
});