### Docker Compose for AI Assistant Setup Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android This YAML configuration defines the services for the AI Assistant and its PostgreSQL database. It includes environment variables for API keys, database credentials, and other settings. Ensure you replace `` with your actual OpenAI API key. The `pgvector` extension is required for the database. ```yaml version: "3.8" services: ai-assistant: image: pspdfkit/ai-assistant:nightly environment: OPENAI_API_KEY: PGUSER: db-user PGPASSWORD: password PGDATABASE: ai_assistant PGHOST: db PGPORT: 5432 API_AUTH_TOKEN: secret JWT_PUBLIC_KEY: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2gzhmJ9TDanEzWdP1WG+ 0Ecwbe7f3bv6e5UUpvcT5q68IQJKP47AQdBAnSlFVi4X9SaurbWoXdS6jpmPpk24 QvitzLNFphHdwjFBelTAOa6taZrSusoFvrtK9x5xsW4zzt/bkpUraNx82Z8MwLwr t6HlY7dgO9+xBAabj4t1d2t+0HS8O/ed3CB6T2lj6S8AbLDSEFc9ScO6Uc1XJlSo rgyJJSPCpNhSq3AubEZ1wMS1iEtgAzTPRDsQv50qWIbn634HLWxTP/UH6YNJBwzt 3O6q29kTtjXlMGXCvin37PyX4Jy1IiPFwJm45aWJGKSfVGMDojTJbuUtM+8P9Rrn AwIDAQAB -----END PUBLIC KEY----- JWT_ALGORITHM: RS256 DASHBOARD_USERNAME: dashboard DASHBOARD_PASSWORD: secret SECRET_KEY_BASE: secret-key-base ports: - 4000:4000 depends_on: db: condition: service_healthy db: image: pgvector/pgvector:pg16 healthcheck: test: [ "CMD-SHELL", "pg_isready -U db-user -d ai_assistant" ] interval: 3s timeout: 3s retries: 10 environment: POSTGRES_USER: db-user POSTGRES_PASSWORD: password POSTGRES_DB: ai_assistant POSTGRES_INITDB_ARGS: --data-checksums PGDATA: /var/lib/postgresql/data/pgdata volumes: - pgdata:/var/lib/postgresql/data volumes: pgdata: ``` -------------------------------- ### Run AI Assistant with Docker Compose Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/ios This command starts the AI Assistant service using Docker Compose. Ensure Docker is installed and configured. The process may take time depending on your internet connection. Look for the 'AI Assistant started' message to confirm successful execution. ```bash docker-compose up ``` -------------------------------- ### Implement AiAssistantProvider Interface in Android Activity Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android This Kotlin code demonstrates how to implement the `AiAssistantProvider` interface in an Android `AppCompatActivity`. This is required to provide an `AiAssistant` instance to the system. The example includes an optional implementation for `navigateTo` to handle multi-document navigation, allowing the AI Assistant to guide users to specific content across documents. ```kotlin class YourActivity : AppCompatActivity(), AiAssistantProvider { override fun getAiAssistant(): AiAssistant { return assistant } // Optional: Implement navigation callback for multi-document support. override fun navigateTo( documentRect: List, pageIndex: Int, documentIndex: Int ) { // Handle navigation to specific document, page, and highlight rectangles. // Example: Switch to the document at `documentIndex` and highlight the specified area. } } ``` -------------------------------- ### Open ChatGPT Prompt - JavaScript Source: https://www.nutrient.io/guides/ai-assistant/deployment/product-activation Opens ChatGPT in a new tab with a pre-filled prompt. The prompt includes a link to the current documentation page and asks the AI to be ready to explain concepts, give examples, or help debug based on it. ```javascript function v(i){const t="https://www.nutrient.io",o=window.location.pathname,r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`,s=`https://chatgpt.com/?q=${encodeURIComponent(r)}`;window.open(s,"_blank")} ``` -------------------------------- ### Open Grok AI with Context (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Opens Grok AI in a new tab with a context-specific prompt. The prompt guides the AI to assist with understanding the current Nutrient documentation page. This function enhances the user's ability to get quick help from various AI platforms. ```javascript function C(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://grok.com/c?q=${encodeURIComponent(r)}`; window.open(s, "_blank") } ``` -------------------------------- ### Verify Node.js Installation (Bash) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/web This command checks if Node.js is installed and displays its version. It's a standard way to confirm the installation after following Node.js setup instructions. The output format typically starts with 'v' followed by the version number. ```bash node --version ``` -------------------------------- ### Open Claude with Query (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/example-projects Opens Claude.ai in a new tab with a pre-filled query that includes the current documentation URL and a request for assistance. This facilitates users getting help from Claude based on the specific documentation page. ```javascript function x(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; const s=`https://claude.ai/new?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Open ChatGPT with Query (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/example-projects Opens ChatGPT in a new tab with a pre-filled query that includes the current documentation URL and a request for assistance. This allows users to quickly get help from ChatGPT based on the specific page they are viewing. ```javascript function v(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; const s=`https://chatgpt.com/?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Show AI Assistant Dialog Programmatically Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Demonstrates how to display the AI Assistant dialog using the `showAiAssistant` function. This method requires a `Context` object. ```kotlin import com.pspdfkit.ai.showAiAssistant // Show AI Assistant dialog. showAiAssistant(context) ``` -------------------------------- ### Initialize AI Assistant with Session History Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Explains how to initialize the AI Assistant, with an option to include session history for a more contextual experience. This involves calling the `initialize` method with a boolean parameter. ```kotlin // Initialize with session history (default). aiAssistant.initialize(withSessionHistory = true) // Initialize without session history for faster startup. aiAssistant.initialize(withSessionHistory = false) ``` -------------------------------- ### Open ChatGPT with Context (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Opens ChatGPT in a new tab with a pre-filled prompt. The prompt includes a link to the current documentation page and asks the AI to help understand and explain the content. This leverages the `encodeURIComponent` function to properly format the URL and query parameters. ```javascript function v(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://chatgpt.com/?q=${encodeURIComponent(r)}`; window.open(s, "_blank") } ``` -------------------------------- ### Open Grok AI Prompt - JavaScript Source: https://www.nutrient.io/guides/ai-assistant/deployment/product-activation Opens Grok AI in a new tab with a pre-filled prompt. The prompt is designed to help the user understand the current Nutrient documentation page by asking the AI for explanations, examples, or debugging assistance. ```javascript function C(i){const t="https://www.nutrient.io",o=window.location.pathname,r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`,s=`https://grok.com/c?q=${encodeURIComponent(r)}`;window.open(s,"_blank")} ``` -------------------------------- ### Android Dependencies for AI Assistant Integration Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android These are the Gradle dependencies required to integrate the AI Assistant into an Android application. They include libraries for markdown rendering, HTML parsing, linkification, table extensions, strikethrough formatting, and a socket.io client for real-time communication. ```gradle implementation("io.noties.markwon:core:4.6.2") implementation("io.noties.markwon:html:4.6.2") implementation("io.noties.markwon:linkify:4.6.2") implementation("io.noties.markwon:ext-tables:4.6.2") implementation("io.noties.markwon:ext-strikethrough:4.6.2") implementation("io.socket:socket.io-client:2.1.1") ``` -------------------------------- ### Create AI Assistant Instance on Android (Kotlin) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android This Kotlin code demonstrates how to create an instance of the AI Assistant on Android. It involves preparing a list of `DocumentDescriptor` objects from asset files and then calling the `createAiAssistant` function with the necessary parameters: context, document descriptors, server IP address, session ID, and a JWT token generation function. ```kotlin val assetFiles = listOf("document1.pdf", "document2.pdf", "document3.pdf") val documentDescriptors = assetFiles.map { DocumentDescriptor.fromDataProviders(listOf(AssetDataProvider(it)), listOf(), listOf()) } val assistant = createAiAssistant( context = this, documentsDescriptors = documentDescriptors, ipAddress = "your-server-ip", sessionId = "your-session-id", jwtToken = { documentIds -> generateJwtToken( context = this, claims = mapOf( "document_ids" to documentIds, "session_ids" to listOf("your-session-id"), "request_limit" to mapOf( "requests" to 160, "time_period_s" to 600000 // 10 minutes ) ) ) }) ``` -------------------------------- ### Open Claude with Context (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Opens Claude AI in a new tab with a pre-filled prompt. Similar to the ChatGPT function, it includes the current documentation URL and a request for assistance with understanding the content. This function facilitates context-aware AI interactions. ```javascript function x(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://claude.ai/new?q=${encodeURIComponent(r)}`; window.open(s, "_blank") } ``` -------------------------------- ### Load VWO Experiment Management Tool (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Initializes the Visual Website Optimizer (VWO) script. It defines configuration variables such as account ID, version, and settings tolerance. The script attempts to load settings from local storage and dynamically adds the VWO script to the page's head element. It includes error handling for JSON parsing and checks for existing VWO configurations. ```javascript window._vwo_code || (function() { var account_id=892495, version=2.1, settings_tolerance=2000, hide_element='', // Don't hide body to prevent flash hide_element_style = '', /* DO NOT EDIT BELOW THIS LINE */ f=false,w=window,d=document,v=d.querySelector('#vwoCode'),cK='_vwo_'+account_id+'_settings',cc={}; try{ var c=JSON.parse(localStorage.getItem('_vwo_'+account_id+'_config')); cc=c&&typeof c==='object'?c:{} }catch(e){} var stT=cc.stT==='session'?w.sessionStorage:w.localStorage; code={ nonce:v&&v.nonce, library_tolerance:function(){ return typeof library_tolerance!=='undefined'?library_tolerance:undefined }, settings_tolerance:function(){ return cc.sT||settings_tolerance }, hide_element_style:function(){ return'{'+(cc.hES||hide_element_style)+'}' }, hide_element:function(){ // Always return empty to prevent hiding return ''; }, getVersion:function(){ return version }, finish:function(e){ if(!f){ f=true; var t=d.getElementById('_vis_opt_path_hides'); if(t)t.parentNode.removeChild(t); if(e)(new Image).src='https://dev.visualwebsiteoptimizer.com/ee.gif?a='+account_id+e } }, finished:function(){ return f }, addScript:function(e){ var t=d.createElement('script'); t.type='text/javascript'; if(e.src){ t.src=e.src; t.async=true; // Make async }else{ t.text=e.text } v&&t.setAttribute('nonce',v.nonce); d.getElementsByTagName('head')[0].appendChild(t) }, load:function(e,t){ var n=this.getSettings(),i=d.createElement('script'),r=this; t=t||{}; if(n){ i.textContent=n; d.getElementsByTagName('head')[0].appendChild(i); if(!w.VWO||VWO.caE){ stT.removeI ``` -------------------------------- ### Open Markdown File in New Tab (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Opens the current page's markdown file (`.md`) in a new browser tab. This is useful for users who want to view or download the raw markdown content directly. It constructs the URL based on the current page's path. ```javascript function k(i){ const t=window.location.pathname, e=`${t.endsWith("/")?t.slice(0,-1):t}.md`; window.open(e, "_blank") } ``` -------------------------------- ### Ingest Document with AI Assistant Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android This code snippet demonstrates how to ingest a document using the AI Assistant. It requires a data provider and a JWT token for authentication. The function returns an ingestion response, which may contain details about the ingestion process. This is a core step for adding new documents to the assistant. ```kotlin val ingestionResponse = aiAssistant.ingestDocument(dataProvider, jwtToken) ``` -------------------------------- ### Copy Page Content to Clipboard (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Orchestrates the process of copying the current page's markdown content to the clipboard. It uses the `y` function to fetch content and the `b` function to perform the copy operation. It also includes logic for updating button text and states to provide user feedback on success or failure. ```javascript async function w(i = {}) { const {buttonSelector: t = ".copy-page-btn", dropdownSelector: o = ".copy-dropdown-item", successText: e = "Copied", errorText: r = "Error", resetDelay: a = 2000} = i; try { if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent) && navigator.clipboard && window.isSecureContext) { const n = new ClipboardItem({"text/plain": fetch(`${window.location.pathname.replace(/\/$/, "")}.md`).then(c => { if (!c.ok) throw new Error("Failed to fetch"); return c.text(); }).then(c => new Blob([c], {type: "text/plain"}))}); await navigator.clipboard.write([n]); } else { const n = await y(); await b(n); } h(t, o, e, "btn-success", a); } catch (s) { console.error("Error copying content:", s); h(t, o, r, "btn-error", a); } } function h(i, t, o, e, r) { const a = document.querySelector(i), s = document.querySelector(t); if (a) { // ... (rest of the function to update button text and class) } if (s) { // ... (rest of the function to update dropdown item text) } } ``` -------------------------------- ### Open Grok with Query (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/example-projects Opens Grok.com in a new tab with a pre-filled query that includes the current documentation URL and a request for assistance. This enables users to seek help from Grok regarding the specific documentation page they are viewing. ```javascript function C(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; const s=`https://grok.com/c?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Initialize and Load Service Settings (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/deployment/backup-and-recovery This JavaScript code initializes a service, likely for A/B testing or personalization. It includes functions to load settings, make asynchronous requests, and handle initialization deferral based on DOM readiness or idle time. Dependencies include a global `_vwo_code` object and browser `window` and `document` objects. ```javascript var _vwo_code = function() { var stT = window.localStorage; var cK = "_vwo_data_"; var d = document; var w = window; var r = { load: function(e, t) { var r = this; if (t) { var o = d.createElement('script'); o.src = e; o.onload = function() { if (t.onloadCb) return t.onloadCb(o, e) }; o.onerror = function() { if (t.onerrorCb) return t.onerrorCb(e) }; d.body.appendChild(o); } else { var o = new XMLHttpRequest; o.open('GET', e, true); o.withCredentials = !t.dSC; o.responseType = t.responseType || 'text'; o.onload = function() { if (t.onloadCb) return t.onloadCb(o, e) if (o.status === 200 || o.status === 304) { _vwo_code.addScript({ text: o.responseText }) } else { _vwo_code.finish('&e=loading_failure:' + e) } }; o.onerror = function() { if (t.onerrorCb) return t.onerrorCb(e) _vwo_code.finish('&e=loading_failure:' + e) }; o.send() } }, getSettings: function() { try { var e = stT.getItem(cK); if (!e) return; e = JSON.parse(e); if (Date.now() > e.e) { stT.removeItem(cK); return } return e.s } catch (e) { return } }, init: function() { if (d.URL.indexOf('__vwo__disable__') > -1) return; var e = this.settings_tolerance(); w._vwo_settings_timer = setTimeout(function() { _vwo_code.finish(); stT.removeItem(cK) }, e); var o = window._vis_opt_url || d.URL, s = 'https://dev.visualwebsiteoptimizer.com/j.php?a=' + account_id + '&u=' + encodeURIComponent(o) + '&vn=' + version; if (w.location.search.indexOf('_vwo_xhr') !== -1) { this.addScript({ src: s }) } else { this.load(s + '&x=true') } } }; w._vwo_code = r; if (d.readyState === 'loading') { d.addEventListener('DOMContentLoaded', function() { r.init(); }); } else { if ('requestIdleCallback' in w) { requestIdleCallback(function() { r.init(); }, { timeout: 1000 }); } else { setTimeout(function() { r.init(); }, 0); } } }(); ``` -------------------------------- ### Navigate to Docker Compose Directory Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/ios This command changes the current directory in the terminal to the location where the `docker-compose.yml` file is saved. This is a prerequisite for starting the AI Assistant service. ```bash cd ``` -------------------------------- ### Pull AI Assistant using Docker Hub Source: https://www.nutrient.io/guides/ai-assistant/downloads This command pulls the AI Assistant image with version 1.5.0 from Docker Hub. Ensure Docker is installed and configured correctly. ```bash docker pull pspdfkit/ai-assistant:1.5.0 ``` -------------------------------- ### Standard Messaging with AI Assistant (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Emits a standard message to the AI Assistant for processing. This is the most basic form of interaction. It takes a single string argument representing the query. ```javascript aiAssistant.emitMessage("Your query here") ``` -------------------------------- ### Generate Express Application with EJS Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/web Uses npx to create a new Express.js application named 'pspdfkit_example' with EJS as the view engine. This command sets up the basic project structure for a Node.js web application. ```bash npx express-generator pspdfkit_example --view=ejs ``` -------------------------------- ### Context-Specific Messaging with AI Assistant (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Emits a message to the AI Assistant with specific context, such as selected text from a document. This allows for more targeted responses. It requires both a message and the context text as string arguments. ```javascript aiAssistant.emitContextSpecificMessage( message = "Explain this section", contextText = "Selected text from the document" ) ``` -------------------------------- ### Open Claude AI Prompt - JavaScript Source: https://www.nutrient.io/guides/ai-assistant/deployment/product-activation Opens Claude AI in a new tab with a pre-filled prompt. The prompt includes a link to the current documentation page and requests assistance with understanding and debugging the content. ```javascript function x(i){const t="https://www.nutrient.io",o=window.location.pathname,r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`,s=`https://claude.ai/new?q=${encodeURIComponent(r)}`;window.open(s,"_blank")} ``` -------------------------------- ### Open Claude AI Chat - JavaScript Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/web Opens a new tab with Claude AI, pre-filling the query with a contextual message about the current Nutrient documentation page. This allows users to quickly get assistance from Claude regarding the documentation. ```javascript function x(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://claude.ai/new?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Open Grok with Context (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/ios Opens Grok.com in a new tab with a pre-filled query. The query informs Grok that the user is viewing Nutrient documentation and needs help understanding it, providing the current page URL. ```javascript function C(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`,s=`https://grok.com/c?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Fetch Markdown Content (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/example-projects Asynchronously fetches markdown content from a file based on the current window's pathname. It handles relative paths and throws an error if the fetch request fails. This is a core utility for accessing documentation. ```javascript async function y(i){ const t=window.location.pathname, o=t.endsWith("/")?t.slice(0,-1):t, e=await fetch(`${o}.md`); if(!e.ok)throw new Error("Failed to fetch markdown content"); return await e.text() } ``` -------------------------------- ### Initialize PSPDFKit with AI Assistant in JavaScript Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/document-engine This snippet shows how to load the PSPDFKit library and initialize it with AI Assistant capabilities. It includes JWT authentication, document loading, and configuration for the AI Assistant toolbar item, including session ID, JWT, and backend URL. Dependencies include the PSPDFKit JavaScript library. ```javascript PSPDFKit.load({ serverUrl: "http://localhost:5000/", container: "#pspdfkit", documentId: "<%%= documentId %>", authPayload: { jwt: "<%%= jwt %>" }, instant: false, toolbarItems: [...PSPDFKit.defaultToolbarItems, { type: "ai-assistant" }], aiAssistant: { sessionId: "my-random-session-id", jwt: "<%%= aiJwt %>", backendUrl: 'http://localhost:4000/' } }) .then(function(instance) { console.log("PSPDFKit loaded", instance); }) .catch(function(error) { console.error(error.message); }); ``` -------------------------------- ### Observing AI Assistant Responses (Kotlin) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Observes responses from the AI Assistant using a `Flow`. This allows for real-time updates to the UI based on the assistant's output. The `responseState` flow emits `CompletionResponse` objects or null. ```kotlin val responseState: Flow = aiAssistant.responseState ``` -------------------------------- ### Share Page to Claude (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/intro Opens a new browser tab with a pre-filled Claude prompt, including the current page's URL and a request for assistance with the documentation. This allows users to easily get help from Claude regarding the documentation content. ```javascript function x(i){const t="https://www.nutrient.io",o=window.location.pathname,r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`,s=`https://claude.ai/new?q=${encodeURIComponent(r)}`;window.open(s,"_blank") } ``` -------------------------------- ### JavaScript: Load Script from URL Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android This JavaScript function loads a script from a given URL. It handles both synchronous and asynchronous loading using XMLHttpRequest. It includes error handling and callback options for success and failure, and it supports response type configuration. ```javascript load: function(e, t) { t = t || {}; if (e.indexOf('//') === 0) { e = location.protocol + e } var n = function() { var r = new XMLHttpRequest; r.open('GET', e, !t.sync); r.withCredentials = !t.dSC; r.responseType = t.responseType || 'text'; r.onload = function() { if (t.onloadCb) { return t.onloadCb(r, e) } if (r.status === 200 || r.status === 304) { _vwo_code.addScript({ text: r.responseText }) } else { _vwo_code.finish('&e=loading_failure:' + e) } }; r.onerror = function() { if (t.onerrorCb) { return t.onerrorCb(e) } _vwo_code.finish('&e=loading_failure:' + e) }; r.send() }; if (t.sync) { n() } else { setTimeout(n, 0) } }, getSettings: function() { try { var e = stT.getItem(cK); if (!e) { return } e = JSON.parse(e); if (Date.now() > e.e) { stT.removeItem(cK); return } return e.s } catch (e) { return } }, init: function() { if (d.URL.indexOf('__vwo__disable__') > -1) return; var e = this.settings_tolerance(); w._vwo_settings_timer = setTimeout(function() { _vwo_code.finish(); stT.removeItem(cK) }, e); var o = window._vis_opt_url || d.URL, s = 'https://dev.visualwebsiteoptimizer.com/j.php?a=' + account_id + '&u=' + encodeURIComponent(o) + '&vn=' + version; if (w.location.search.indexOf('_vwo_xhr') !== -1) { this.addScript({ src: s }) } else { this.load(s + '&x=true') } } }; w._vwo_code = code; if (d.readyState === 'loading') { d.addEventListener('DOMContentLoaded', function() { code.init(); }); } else { if ('requestIdleCallback' in w) { requestIdleCallback(function() { code.init(); }, { timeout: 1000 }); } else { setTimeout(function() { code.init(); }, 0); } } })(); ``` -------------------------------- ### Terminate AI Assistant JavaScript Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android This JavaScript snippet demonstrates how to terminate the AI Assistant by calling the `terminate` method on the `aiAssistant` object. This is a straightforward method call with no direct inputs or outputs shown, but it signifies the cessation of the assistant's operations. ```javascript aiAssistant.terminate() ``` -------------------------------- ### Configure AI Assistant with Docker Compose Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/ios This configuration file sets up the AI Assistant service and its PostgreSQL database dependencies using Docker. It requires an OpenAI API key and defines various environment variables for database connection, authentication, and security. ```yaml version: "3.8" services: ai-assistant: image: pspdfkit/ai-assistant:nightly environment: OPENAI_API_KEY: PGUSER: db-user PGPASSWORD: password PGDATABASE: ai_assistant PGHOST: db PGPORT: 5432 API_AUTH_TOKEN: secret JWT_PUBLIC_KEY: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2gzhmJ9TDanEzWdP1WG+ 0Ecwbe7f3bv6e5UUpvcT5q68IQJKP47AQdBAnSlFVi4X9SaurbWoXdS6jpmPpk24 QvitzLNFphHdwjFBelTAOa6taZrSusoFvrtK9x5xsW4zzt/bkpUraNx82Z8MwLwr t6HlY7dgO9+xBAabj4t1d2t+0HS8O/ed3CB6T2lj6S8AbLDSEFc9ScO6Uc1XJlSo rgyJJSPCpNhSq3AubEZ1wMS1iEtgAzTPRDsQv50qWIbn634HLWxTP/UH6YNJBwzt 3O6q29kTtjXlMGXCvin37PyX4Jy1IiPFwJm45aWJGKSfVGMDojTJbuUtM+8P9Rrn AwIDAQAB -----END PUBLIC KEY----- JWT_ALGORITHM: RS256 DASHBOARD_USERNAME: dashboard DASHBOARD_PASSWORD: secret SECRET_KEY_BASE: secret-key-base ports: - 4000:4000 depends_on: db: condition: service_healthy db: image: pgvector/pgvector:pg16 healthcheck: test: [ "CMD-SHELL", "pg_isready -U db-user -d ai_assistant" ] interval: 3s timeout: 3s retries: 10 environment: POSTGRES_USER: db-user POSTGRES_PASSWORD: password POSTGRES_DB: ai_assistant POSTGRES_INITDB_ARGS: --data-checksums PGDATA: /var/lib/postgresql/data/pgdata volumes: - pgdata:/var/lib/postgresql/data/pgdata volumes: pgdata: ``` -------------------------------- ### Emit Selected Text with AI Assistant (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Emits selected text to the AI Assistant for processing. This is useful when the user has highlighted specific content they want the assistant to act upon. It takes a single string argument representing the selected text. ```javascript aiAssistant.emitSelectedText("Text selected by the user") ``` -------------------------------- ### Initialize PSPDFKit with AI Assistant - JavaScript Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/web This script initializes PSPDFKit, mounting it to a specified container and enabling the AI Document Assistant. It requires the document path, container selector, and AI-specific configurations like sessionId, jwt, and backendUrl. The script logs success or error messages to the console. ```javascript PSPDFKit.load({ document: "/samples/example.pdf", container: "#pspdfkit", instant: false, toolbarItems: [...PSPDFKit.defaultToolbarItems, { type: "ai-document-assistant" }], aiDocumentAssistant: { sessionId: "my-random-session-id", jwt: "<%%= aiJwt %>", backendUrl: 'http://localhost:4000/' }, }) .then(function(instance) { console.log("PSPDFKit loaded", instance); }) .catch(function(error) { console.error(error.message); }); ``` -------------------------------- ### Initialize and Load Script - JavaScript Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/web This JavaScript code initializes and loads a script, potentially for website optimization. It handles fetching settings, managing script loading with XMLHttpRequest, and uses techniques like requestIdleCallback or setTimeout to defer initialization, preventing render blocking. Dependencies include global variables like `window`, `document`, and `stT`, along with custom objects `_vwo_code` and `_vwo_settings_timer`. ```javascript var _vwo_code = { settings_tolerance: function() { var e = stT.getItem(cK); if (!e) { return; } e = JSON.parse(e); if (Date.now() > e.e) { stT.removeItem(cK); return; } return e.s; }, addScript: function(t) { var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; if (t.src) { e.src = t.src; } if (t.text) { e.text = t.text; } if (t.onload) { e.onload = t.onload; } document.head.appendChild(e); }, load: function(e, t) { if (t) { var r = _vwo_code.settings_tolerance(); if (r) { var n = JSON.parse(stT.getItem(cK)).s; var i = n.url + "?" + e + "&s=" + r; this.addScript({ src: i }); } stT.removeItem(cK); } else { var o = new XMLHttpRequest(); o.open('GET', e, true); o.withCredentials = !t.dSC; o.responseType = t.responseType || 'text'; o.onload = function() { if (t.onloadCb) { return t.onloadCb(o, e); } if (o.status === 200 || o.status === 304) { _vwo_code.addScript({ text: o.responseText }); } else { _vwo_code.finish('&e=loading_failure:' + e); } }; o.onerror = function() { if (t.onerrorCb) { return t.onerrorCb(e); } _vwo_code.finish('&e=loading_failure:' + e); }; o.send(); } }, getSettings: function() { try { var e = stT.getItem(cK); if (!e) { return; } e = JSON.parse(e); if (Date.now() > e.e) { stT.removeItem(cK); return; } return e.s; } catch (e) { return; } }, init: function() { if (d.URL.indexOf('__vwo__disable__') > -1) return; var e = this.settings_tolerance(); w._vwo_settings_timer = setTimeout(function() { _vwo_code.finish(); stT.removeItem(cK); }, e); var o = window._vis_opt_url || d.URL, s = 'https://dev.visualwebsiteoptimizer.com/j.php?a=' + account_id + '&u=' + encodeURIComponent(o) + '&vn=' + version; if (w.location.search.indexOf('_vwo_xhr') !== -1) { this.addScript({ src: s }); } else { this.load(s + '&x=true'); } } }; // Defer initialization to prevent render blocking if (d.readyState === 'loading') { d.addEventListener('DOMContentLoaded', function() { code.init(); }); } else { // If DOM is already loaded, use requestIdleCallback or setTimeout if ('requestIdleCallback' in w) { requestIdleCallback(function() { code.init(); }, { timeout: 1000 }); } else { setTimeout(function() { code.init(); }, 0); } } })(); ``` -------------------------------- ### Write to Clipboard (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Attempts to copy text to the clipboard using the modern `navigator.clipboard.writeText` or `navigator.clipboard.write` API, prioritizing security and context. It includes a fallback to the `g` function if the Clipboard API fails or is unavailable. This function is essential for user-friendly content sharing. ```javascript async function b(i){ const t=window.isSecureContext; if (navigator.clipboard && t) try { if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { const e = new ClipboardItem({"text/plain": new Blob([i], {type: "text/plain"})}); await navigator.clipboard.write([e]); } else await navigator.clipboard.writeText(i); return } catch (e) { console.warn("Clipboard API failed, trying fallback:", e); } if (!g(i)) throw new Error("Failed to copy to clipboard"); } ``` -------------------------------- ### VWO Initialization and Script Loading (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/deployment/product-activation This snippet initializes the VWO tracking code. It fetches settings from local storage, constructs the VWO script URL using the account ID and current URL, and then loads the script either via XHR for specific cases or directly via a script tag. Initialization is deferred using various methods like DOMContentLoaded, requestIdleCallback, or setTimeout to ensure it doesn't block page rendering. ```javascript var _vwo_code = (function() { var cK = 'vwo_settings'; var stT = window.localStorage; var d = document; var w = window; var account_id = 12345; // Replace with actual account ID var version = '1.0'; // Replace with actual version var code = { settings_tolerance: function() { var e = stT.getItem(cK); if (!e) { return 10000; } try { e = JSON.parse(e); if (Date.now() > e.e) { stT.removeItem(cK); return 10000; } return e.s; } catch (e) { return 10000; } }, addScript: function(t) { var e = d.createElement('script'); e.src = t.src; e.type = 'text/javascript'; e.async = true; d.body.appendChild(e); }, load: function(e, t) { t = t || {}; if (w.XMLHttpRequest) { var o = new XMLHttpRequest(); o.open('GET', e, true); o.withCredentials = !t.dSC; o.responseType = t.responseType || 'text'; o.onload = function() { if (t.onloadCb) { return t.onloadCb(o, e); } if (o.status === 200 || o.status === 304) { _vwo_code.addScript({ text: o.responseText }); } else { _vwo_code.finish('&e=loading_failure:' + e); } }; o.onerror = function() { if (t.onerrorCb) { return t.onerrorCb(e); } _vwo_code.finish('&e=loading_failure:' + e); }; o.send(); } else { var o = new XMLHttpRequest(); o.open('GET', e, true); o.withCredentials = !t.dSC; o.responseType = t.responseType || 'text'; o.onload = function() { if (t.onloadCb) { return t.onloadCb(o, e); } if (o.status === 200 || o.status === 304) { _vwo_code.addScript({ text: o.responseText }); } else { _vwo_code.finish('&e=loading_failure:' + e); } }; o.onerror = function() { if (t.onerrorCb) { return t.onerrorCb(e); } _vwo_code.finish('&e=loading_failure:' + e); }; o.send(); } }, getSettings: function() { try { var e = stT.getItem(cK); if (!e) { return; } e = JSON.parse(e); if (Date.now() > e.e) { stT.removeItem(cK); return; } return e.s; } catch (e) { return; } }, init: function() { if (d.URL.indexOf('__vwo__disable__') > -1) return; var e = this.settings_tolerance(); w._vwo_settings_timer = setTimeout(function() { _vwo_code.finish(); stT.removeItem(cK); }, e); var o = w._vis_opt_url || d.URL, s = 'https://dev.visualwebsiteoptimizer.com/j.php?a=' + account_id + '&u=' + encodeURIComponent(o) + '&vn=' + version; if (w.location.search.indexOf('_vwo_xhr') !== -1) { this.addScript({ src: s }); } else { this.load(s + '&x=true'); } } }; return code; })(); // Defer initialization to prevent render blocking if (d.readyState === 'loading') { d.addEventListener('DOMContentLoaded', function() { _vwo_code.init(); }); } else { // If DOM is already loaded, use requestIdleCallback or setTimeout if ('requestIdleCallback' in w) { requestIdleCallback(function() { _vwo_code.init(); }, { timeout: 1000 }); } else { setTimeout(function() { _vwo_code.init(); }, 0); } } // Assign to window for external access if needed // w._vwo_code = _vwo_code; ``` -------------------------------- ### Copy Text to Clipboard (JavaScript) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/android Provides a fallback mechanism for copying text to the clipboard by creating a temporary textarea element. This method is used when the modern Clipboard API is unavailable or fails. It ensures text is selected and copied, then removes the temporary element. ```javascript function g(i){ const t=document.createElement("textarea"); t.value=i, t.style.position="fixed", t.style.top="0", t.style.left="-999999px", t.style.width="2em", t.style.height="2em", t.style.padding="0", t.style.border="none", t.style.outline="none", t.style.boxShadow="none", t.style.background="transparent", document.body.appendChild(t), t.focus(), t.select(); let o=!1; try{ o=document.execCommand("copy")}catch(e){ console.error("Fallback copy failed:",e) } return document.body.removeChild(t), o } ``` -------------------------------- ### Configure AI Assistant in iOS App (SwiftUI/UIKit) Source: https://www.nutrient.io/sdk/ai-assistant/getting-started/ios This Swift code snippet illustrates how to configure the AI Assistant within an iOS application. It involves setting an AIAssistantConfiguration with server URL, JWT, and session details. The example references AIAssistantButton for SwiftUI and aiAssistantButtonItem for UIKit. ```swift // In your main PDFConfiguration: let configuration = PDFConfigurationBuilder() .aiAssistantConfiguration( AIAssistantConfiguration( serverUrl: URL(string: "your_server_url")!, jwt: "your_jwt_token", sessionIdentifier: "your_session_id", userId: "optional_user_id" ) ) .build() // For SwiftUI: // Add AIAssistantButton to your view // For UIKit: // Add aiAssistantButtonItem to your navigation bar or toolbar ``` -------------------------------- ### Open ChatGPT with Context (JavaScript) Source: https://www.nutrient.io/guides/ai-assistant/service-configuration/selecting-right-llm-hosting-strategy Opens ChatGPT in a new tab with a pre-filled query. The query includes a link to the current documentation page and a prompt asking for assistance with understanding and using it. ```javascript function v(i) { const t = "https://www.nutrient.io"; const o = window.location.pathname; const r = `I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; const s = `https://chatgpt.com/?q=${encodeURIComponent(r)}`; window.open(s, "_blank"); } ```