Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 5 additions & 59 deletions chat-core.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,9 @@
// Global config for Pollinations API token
window._pollinationsAPIConfig = window._pollinationsAPIConfig || {
// Token can be provided via process.env or a global variable set in a separate script.
token:
(typeof process !== "undefined" && process.env?.POLLINATIONS_TOKEN) ||
window.POLLINATIONS_TOKEN ||
""
};

// Global helper to retry Pollinations text API requests with exponential backoff.
// Automatically appends `token` query parameter if not present.
window.pollinationsFetch = async function (url, options = {}, retries = 6, delay = 4000) {
const cfg = window._pollinationsAPIConfig || {};
try {
const urlObj = new URL(url);
if (urlObj.hostname.includes("pollinations.ai")) {
const token =
cfg.token ||
(typeof process !== "undefined" && process.env?.POLLINATIONS_TOKEN) ||
window.POLLINATIONS_TOKEN;
if (token && !urlObj.searchParams.has("token")) {
urlObj.searchParams.set("token", token);
}
if (!urlObj.searchParams.has("referrer")) {
urlObj.searchParams.set("referrer", "unityailab.com");
}
}
url = urlObj.toString();
} catch (err) {
console.warn("Invalid URL provided to pollinationsFetch:", url, err);
}

for (let attempt = 0; attempt <= retries; attempt++) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`Pollinations fetch failed with status ${response.status}`);
}
return response;
} catch (err) {
if (attempt === retries) throw err;
console.warn(
`Pollinations fetch attempt ${attempt + 1} failed, retrying in ${delay / 1000}s...`,
err
);
await new Promise((res) => setTimeout(res, delay));
delay *= 2;
}
}
// Minimal helper to call Pollinations APIs without modifying the request.
window.pollinationsFetch = function (url, options = {}) {
return fetch(url, options);
};

document.addEventListener("DOMContentLoaded", () => {
window._pollinationsAPIConfig.token =
window._pollinationsAPIConfig.token ||
(typeof process !== "undefined" && process.env?.POLLINATIONS_TOKEN) ||
window.POLLINATIONS_TOKEN ||
"";

const chatBox = document.getElementById("chat-box");
const chatInput = document.getElementById("chat-input");
Expand Down Expand Up @@ -541,10 +490,8 @@ document.addEventListener("DOMContentLoaded", () => {
messages.push({ role: "user", content: overrideContent });
}
const selectedModel = modelSelect.value || currentSession.model || "unity";
const seed = Date.now().toString() + Math.random().toString(36).substring(2);
const body = { messages, model: selectedModel, nonce: seed };
const apiUrl = `https://text.pollinations.ai/openai?model=${encodeURIComponent(selectedModel)}&seed=${seed}`;
console.log("Sending API request with payload:", JSON.stringify(body));
const body = { messages, model: selectedModel };
const apiUrl = `https://text.pollinations.ai/openai?model=${encodeURIComponent(selectedModel)}`;
window.pollinationsFetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
Expand All @@ -553,7 +500,6 @@ document.addEventListener("DOMContentLoaded", () => {
})
.then(res => res.json())
.then(data => {
console.log("API response received:", data);
loadingDiv.remove();
let aiContent = extractAIContent(data);
if (aiContent) {
Expand Down
48 changes: 22 additions & 26 deletions screensaver.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,46 +139,42 @@ document.addEventListener("DOMContentLoaded", () => {
});
}

async function fetchDynamicPromptWithRetry(maxRetries = 6, delayMs = 4000) {
const metaPrompt = "Generate an image prompt of something new and wild. Respond with text only.";
const messages = [
{ role: "system", content: "Generate unique, wild image prompts as text only, under 100 characters." },
{ role: "user", content: metaPrompt }
];
const seed = generateSeed();
async function fetchDynamicPrompt() {
const metaPrompt = "Generate an image prompt of something new and wild. Respond with text only.";
const messages = [
{ role: "system", content: "Generate unique, wild image prompts as text only, under 100 characters." },
{ role: "user", content: metaPrompt }
];
const body = {
messages,
model: "unity",
nonce: seed
model: "unity"
};
const apiUrl = `https://text.pollinations.ai/openai?model=unity&seed=${seed}`;
console.log("Sending API request for new prompt:", JSON.stringify(body));
const apiUrl = `https://text.pollinations.ai/openai?model=unity`;
try {
const response = await window.pollinationsFetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify(body),
cache: "no-store",
}, maxRetries, delayMs);

const data = await response.json();
let generatedPrompt = data.choices?.[0]?.message?.content || data.choices?.[0]?.text || data.response;
if (!generatedPrompt) throw new Error("No prompt returned from API");
if (generatedPrompt.length > 100) generatedPrompt = generatedPrompt.substring(0, 100);
console.log("Received new prompt from API:", generatedPrompt);
return generatedPrompt;
} catch (err) {
console.error("Failed to fetch dynamic prompt:", err);
throw err;
}
}
async function updatePrompt() {
});

const data = await response.json();
let generatedPrompt = data.choices?.[0]?.message?.content || data.choices?.[0]?.text || data.response;
if (!generatedPrompt) throw new Error("No prompt returned from API");
if (generatedPrompt.length > 100) generatedPrompt = generatedPrompt.substring(0, 100);
return generatedPrompt;
} catch (err) {
console.error("Failed to fetch dynamic prompt:", err);
throw err;
}
}
async function updatePrompt() {
if (!screensaverActive || paused || !autoPromptEnabled || isFetchingPrompt) {
return false;
}
isFetchingPrompt = true;
try {
const newPrompt = await fetchDynamicPromptWithRetry();
const newPrompt = await fetchDynamicPrompt();
promptInput.value = newPrompt;
settings.prompt = newPrompt;
saveScreensaverSettings();
Expand Down