Jump to content

User:Polygnotus/Scripts/Apertus.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// <nowiki>
const script = document.createElement('script');
script.type = 'module';
script.textContent = `
  import { InferenceClient } from "https://cdn.jsdelivr.net/npm/@huggingface/inference/+esm";
  
  const STORAGE_KEY = 'apertus_hf_token';
  
  function getStoredToken() {
    return localStorage.getItem(STORAGE_KEY);
  }
  
  function setStoredToken(token) {
    localStorage.setItem(STORAGE_KEY, token);
  }
  
  async function callApertus(message, token) {
    const client = new InferenceClient(token);
    const response = await client.chatCompletion({
      model: "swiss-ai/Apertus-8B-Instruct-2509",
      messages: [{ role: "user", content: message }],
      max_tokens: 500
    });
    const content = response.choices[0].message.content;
    console.log(content);
    return content;
  }
  
  async function handleAskApertus() {
    let token = getStoredToken();
    
    if (!token) {
      token = prompt("Enter your HuggingFace API token:");
      if (!token) return;
      setStoredToken(token);
    }
    
    const question = prompt("Ask Apertus:");
    if (!question) return;
    
    try {
      const response = await callApertus(question, token);
      alert(response);
    } catch (error) {
      console.error("Error calling Apertus:", error);
      alert("Error: " + error.message);
    }
  }
  
  // Add link to Tools menu
  function addToolsLink() {
    const toolsMenu = document.querySelector('#p-tb ul');
    if (toolsMenu) {
      const li = document.createElement('li');
      li.className = 'mw-list-item';
      const link = document.createElement('a');
      link.href = '#';
      link.textContent = 'Ask Apertus';
      link.addEventListener('click', (e) => {
        e.preventDefault();
        handleAskApertus();
      });
      li.appendChild(link);
      toolsMenu.appendChild(li);
      console.log("✅ Apertus Tools link added");
    }
  }
  
  // Wait for page load
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', addToolsLink);
  } else {
    addToolsLink();
  }
`;
document.head.appendChild(script);
// </nowiki>