# Authentication Source: http://docs.siteassist.io/developer-api/authentication > Learn how to authenticate your API requests with SiteAssist ## Overview The SiteAssist API uses two authentication methods depending on the endpoint and use case: 1. **API Key Authentication** - For initializing sessions and public operations 2. **Bearer Token Authentication** - For authenticated requests after session initialization ## API Key Authentication API keys are used to identify your project and initialize visitor sessions. They are passed directly in the request body or as query parameters. ### Using Publishable Keys Publishable keys (`pk_*`) are used in client-side applications to initialize visitor sessions: ```js // Initialize a visitor session with your publishable key const response = await fetch('https://api.siteassist.io/v2/identity/init', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ apiKey: 'pk_your_publishable_key_here', saVid: 'unique-device-id-123', }), }); ``` ### Using Private Keys Private keys (`sk_*`) provide full access to the API and should only be used server-side. They are typically used as Bearer tokens: ```js // Using private key as Bearer token (server-side only) const response = await fetch('https://api.siteassist.io/v2/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer sk_your_private_key_here', 'Content-Type': 'application/json', }, body: JSON.stringify({ messages: [ { role: 'user', content: 'Hi' } ] }) }); ``` **Never expose private keys in client-side code!** Private keys should only be used in secure server environments. ## Bearer Token Authentication After initializing a visitor session, you receive a short-lived session token that must be used for subsequent authenticated requests. ### Session Token Lifecycle 1. **Initialize**: Call `/identity/init` with your publishable API key 2. **Receive**: Get a `sessionToken` in the response 3. **Use**: Include the token in the `Authorization` header for subsequent requests 4. **Expire**: Session tokens are short-lived and expire after a period of inactivity ### Example: Complete Authentication Flow ```js // Step 1: Initialize visitor session const initResponse = await fetch('https://api.siteassist.io/v2/identity/init', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ apiKey: 'pk_your_publishable_key_here', saVid: 'device-abc-123', }), }); const { sessionToken, visitor } = await initResponse.json(); // Step 2: Use session token for authenticated requests const conversationResponse = await fetch('https://api.siteassist.io/v2/conversations', { method: 'POST', headers: { 'Authorization': `Bearer ${sessionToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ context: { pageUrl: 'https://example.com/support', }, }), }); const conversation = await conversationResponse.json(); // Step 3: Continue using the same session token // for all requests in this session console.log('Visitor ID:', visitor.id); console.log('Conversation ID:', conversation.id); ``` ## Authentication by Endpoint Different endpoints use different authentication methods: | Endpoint | Authentication Method | Key Type | | ----------------------------------- | --------------------- | ------------- | | `POST /identity/init` | API Key (in body) | Publishable | | `GET /identity/me` | Bearer Token | Session Token | | `GET /projects/current` | API Key (query param) | Publishable | | `POST /conversations` | Bearer Token | Session Token | | `GET /conversations` | Bearer Token | Session Token | | `POST /conversations/{id}/messages` | Bearer Token | Session Token | | `GET /projects/{id}/qnas` | No auth required | - | | `GET /search` | API Key (query param) | Publishable | | `POST /chat/completions` | Bearer Token | Private | **Session Tokens vs Private Keys**: While both can be used as Bearer tokens, session tokens are for visitor-scoped operations (conversations, messages), while private keys provide full project access. ## Error Responses When authentication fails, the API returns appropriate error responses: ### 401 Unauthorized The authentication token is missing or invalid: ```json { "error": { "message": "Authentication required", "code": "UNAUTHORIZED" } } ``` **Common causes:** * Missing `Authorization` header * Expired session token * Invalid or revoked API key * Malformed Bearer token ### 403 Forbidden The authenticated user doesn't have permission to access the resource: ```json { "error": { "message": "Access denied to this conversation", "code": "FORBIDDEN" } } ``` **Common causes:** * Trying to access another visitor's conversation * Using a publishable key for admin operations * Domain restrictions on publishable key ## Best Practices ### Security 1. **Store Keys Securely**: Use environment variables, never hardcode keys 2. **Rotate Keys Regularly**: Create new keys and revoke old ones periodically 3. **Use HTTPS Only**: Never send API keys over unencrypted connections 4. **Implement Key Rotation**: Have a process to update keys without downtime ```bash # Good: Store in environment variables SITEASSIST_PUBLISHABLE_KEY=pk_abc123... SITEASSIST_SECRET_KEY=sk_xyz789... # Never commit these to version control! ``` ## Need Help? We're here to help you succeed! Whether you have questions, need assistance with setup, or want to discuss advanced use cases, our team is ready to provide personalized support. **Contact us:** [support@siteassist.io](mailto:support@siteassist.io) We'd love to hear about your use case and help you get the most out of SiteAssist! --- # Get Started Source: http://docs.siteassist.io/developer-api/get-started > Learn about the SiteAssist Developer API and how to create API keys ## Introduction The SiteAssist Developer API provides programmatic access to integrate AI-powered chat assistants into your applications. The API allows you to embed intelligent chatbots on your websites and services, enabling seamless customer interactions powered by AI. With the Developer API, you can: * Initialize visitor sessions for chat interactions * Create and manage conversations * Send and receive messages with AI assistants * Access conversation history * Perform semantic search on your knowledge base * Retrieve Q\&A entries from your project * Generate chat completions using configured assistants To use developer API, you need to create API keys in the project dashboard. ## Creating API Keys Follow these steps to create API keys for your project: ### Step 1: Navigate to API Keys Dashboard 1. Go to your project dashboard in SiteAssist 2. In the sidebar under **Advanced**, click on **API Keys** API Keys Dashboard ### Step 2: Click Create API Key In the top-right corner of the API Keys dashboard, click the **Create API Key** button. This will open a dropdown menu with two options: * **Publishable Key** - For client-side applications * **Private Key** - For server-side applications Create API Key Dropdown ### Step 3: Choose Your Key Type Select the appropriate key type based on where you'll use it: #### Publishable Key For client-side applications (websites, mobile apps): 1. Select **Publishable Key** from the dropdown 2. Fill in the modal fields: * **Name**: Give your key a descriptive name (e.g., "Production Website", "Mobile App") * **Assistant**: Select which AI assistant this key will interact with * **Allowed Websites**: Add the domains where this key will be used (e.g., "[https://example.com](https://example.com)") 3. Click **+ Add URL** to add multiple allowed domains 4. Click **Create Key** Create Publishable Key Modal **Domain Restrictions**: Adding allowed websites helps protect your API key from being used on unauthorized domains. The API will reject requests from domains not in your allowed list. #### Private Key For server-side integrations: 1. Select **Private Key** from the dropdown 2. Enter only: * **Name**: Give your key a descriptive name (e.g., "Backend API Integration", "Analytics Service") 3. Click **Create** Create Private Key Modal 4. Save **Your API Key** After creating your key, a modal will display your new API key. API Key Created Modal **Important Security Notice** This is the **only time** your API key will be shown in full. Make sure to: * Copy the key immediately and store it securely * Never commit it to version control * Use environment variables to store it in your applications * If you lose it, you'll need to create a new one For private keys, if the key is ever exposed, **revoke it immediately** and create a replacement. ### Revoking API Keys If an API key is compromised or no longer needed: 1. Locate the key in the API Keys dashboard 2. Click the actions menu (⋯) for that key 3. Select **Revoke Key** 4. Confirm the action Revoking a key will immediately stop all applications using that key from accessing the API. Make sure to update your applications with a new key before revoking if continuity is required. ## Need Help? We're here to help you succeed! Whether you have questions, need assistance with setup, or want to discuss advanced use cases, our team is ready to provide personalized support. **Contact us:** [support@siteassist.io](mailto:support@siteassist.io) We'd love to hear about your use case and help you get the most out of SiteAssist! --- # HTTP Status Codes Source: http://docs.siteassist.io/developer-api/status-codes > Understanding HTTP status codes returned by the SiteAssist API ## Overview The SiteAssist API uses standard HTTP status codes to indicate the success or failure of requests. Status codes in the 2xx range indicate success, 4xx indicate client errors, and 5xx indicate server errors. ## Status Codes | Status Code | Name | Description | | ----------- | --------------------- | ------------------------------------------------------------------------------------------ | | **200** | OK | The request was successful. The response body contains the requested data. | | **201** | Created | A new resource was successfully created (e.g., new conversation or visitor). | | **202** | Accepted | The request was accepted and queued for processing (e.g., message queued for human agent). | | **400** | Bad Request | The request was invalid or malformed. Check the request body and parameters. | | **401** | Unauthorized | Authentication is required or the provided credentials are invalid. | | **402** | Payment Required | A higher pricing plan is required to access this feature or resource. | | **403** | Forbidden | The authenticated user doesn't have permission to access the requested resource. | | **404** | Not Found | The requested resource doesn't exist or couldn't be found. | | **409** | Conflict | The request conflicts with the current state of the resource. | | **422** | Unprocessable Entity | The request was well-formed but contains semantic errors or validation failures. | | **429** | Too Many Requests | Rate limit exceeded or usage quota reached. Retry after the specified time. | | **500** | Internal Server Error | An unexpected error occurred on the server. Contact support if this persists. | | **502** | Bad Gateway | The server received an invalid response from an upstream service (e.g., AI provider). | | **503** | Service Unavailable | The server is temporarily unable to handle the request. Try again later. | ## Success Responses (2xx) ### 200 OK Standard success response. The request was processed successfully and the response contains the requested data. ```json { "object": "conversation", "id": "123e4567-e89b-12d3-a456-426614174000", "status": "open", "messages": [] } ``` ### 201 Created A new resource was successfully created. Common when creating conversations or initializing new visitors. ```json { "sessionToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "visitor": { "id": "9d1a7c9e-5b21-46f1-9c86-0a2b12345678", "type": "anonymous" } } ``` ### 202 Accepted The request was accepted but processing is asynchronous. Used when messages are queued for human agent handling. ```json "Message sent" ``` ## Client Error Responses (4xx) ### 400 Bad Request The request is malformed or contains invalid parameters. Check your request body, query parameters, and headers. ```json { "error": { "message": "Invalid request body. Content is required.", "code": "INVALID_REQUEST_BODY", "details": { "field": "content" } } } ``` **Common causes:** * Missing required fields * Invalid data types * Malformed JSON * Invalid parameter values ### 401 Unauthorized Authentication credentials are missing, invalid, or expired. ```json { "error": { "message": "Authentication required", "code": "UNAUTHORIZED" } } ``` **Common causes:** * Missing `Authorization` header * Expired session token * Invalid API key * Revoked credentials ### 402 Payment Required Your current plan doesn't include access to this feature or you've exceeded your plan limits. ```json { "error": { "message": "A higher pricing plan is required to access this feature", "code": "PAYMENT_REQUIRED", "details": { "currentPlan": "free", "requiredPlan": "pro", "feature": "advanced_ai_models" } } } ``` **Resolution:** * Upgrade your plan in the dashboard * Check your current usage and limits ### 403 Forbidden You don't have permission to access the requested resource, even with valid authentication. ```json { "error": { "message": "Access denied to this conversation", "code": "FORBIDDEN" } } ``` **Common causes:** * Attempting to access another visitor's conversation * Domain restrictions on publishable keys * Insufficient permissions for the operation ### 404 Not Found The requested resource doesn't exist or has been deleted. ```json { "error": { "message": "Conversation not found!", "code": "CONVERSATION_NOT_FOUND", "details": { "conversationId": "123e4567-e89b-12d3-a456-426614174000" } } } ``` **Common causes:** * Invalid resource ID * Resource was deleted * Typo in the URL path ### 409 Conflict The request conflicts with the current state of the resource. ```json { "error": { "message": "Resource already exists", "code": "CONFLICT", "details": { "resource": "conversation", "conflictingField": "id" } } } ``` **Common causes:** * Duplicate resource creation * Concurrent modification conflict ### 422 Unprocessable Entity The request is syntactically correct but contains semantic errors or fails validation. ```json { "error": { "message": "Validation failed", "code": "VALIDATION_ERROR", "details": { "field": "content", "reason": "Content exceeds maximum length of 10000 characters" } } } ``` **Common causes:** * Validation rule violations * Content too long or too short * Invalid format or pattern ### 429 Too Many Requests You've exceeded the rate limit or usage quota for your plan. ```json { "error": { "message": "Rate limit exceeded. Please try again later.", "code": "RATE_LIMIT_EXCEEDED", "details": { "retryAfter": 60 } } } ``` **Resolution:** * Wait for the time specified in `retryAfter` (in seconds) * Implement exponential backoff * Check the `Retry-After` response header * Upgrade your plan for higher limits ## Server Error Responses (5xx) ### 500 Internal Server Error An unexpected error occurred on the server. This is not your fault. ```json { "error": { "message": "An internal server error occurred", "code": "INTERNAL_SERVER_ERROR" } } ``` **What to do:** * Retry the request * If the error persists, contact support * Check the [status page](https://status.siteassist.io) for incidents ### 502 Bad Gateway The server received an invalid response from an upstream service (like an AI model provider). ```json { "error": { "message": "Service temporarily unavailable", "code": "BAD_GATEWAY", "details": { "service": "ai_model_service" } } } ``` **What to do:** * Retry the request after a short delay * The issue is usually temporary * Contact support if it persists ### 503 Service Unavailable The server is temporarily unable to handle requests, usually due to maintenance or high load. ```json { "error": { "message": "Service temporarily unavailable", "code": "SERVICE_UNAVAILABLE", "details": { "retryAfter": 30 } } } ``` **What to do:** * Wait and retry after the time specified in `retryAfter` * Check the [status page](https://status.siteassist.io) * Implement retry logic with exponential backoff ## Error Response Structure All error responses follow a consistent structure: ```json { "error": { "message": "Human-readable error message", "code": "MACHINE_READABLE_CODE", "details": { "additionalContext": "value" } } } ``` | Field | Description | | --------------- | ------------------------------------------------------- | | `error.message` | Human-readable description of what went wrong | | `error.code` | Machine-readable error code for programmatic handling | | `error.details` | Optional object with additional context about the error | ## Handling Errors ### Retry Logic Implement exponential backoff for temporary errors (429, 500, 502, 503): ```javascript async function fetchWithRetry(url, options, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { const response = await fetch(url, options); if (response.ok) { return response.json(); } // Retry on temporary errors if ([429, 500, 502, 503].includes(response.status)) { const waitTime = Math.pow(2, i) * 1000; // Exponential backoff await new Promise(resolve => setTimeout(resolve, waitTime)); continue; } // Don't retry on client errors if (response.status >= 400 && response.status < 500) { throw await response.json(); } } throw new Error('Max retries exceeded'); } ``` ### Error Handling Best Practices 1. **Check Status Codes**: Always check the HTTP status code before processing the response 2. **Parse Error Details**: Use the `error.code` field for programmatic error handling 3. **Log Errors**: Log error details for debugging and monitoring 4. **User-Friendly Messages**: Show appropriate messages to users based on error types 5. **Implement Retries**: Use exponential backoff for temporary failures 6. **Monitor Errors**: Track error rates to identify issues early ## Need Help? We're here to help you succeed! Whether you have questions, need assistance with setup, or want to discuss advanced use cases, our team is ready to provide personalized support. **Contact us:** [support@siteassist.io](mailto:support@siteassist.io) We'd love to hear about your use case and help you get the most out of SiteAssist! --- # Support Source: http://docs.siteassist.io/support > This page outlines SiteAssist's support offerings, available channels, and policies. To learn how to access support, please refer to the [Support channels](#support-channels) section. Identify the channels available to you based on your usage and follow the links to navigate to the relevant information. ## Support channels The support channels you can access differ according to your use of SiteAssist. | Support channels | Community support | Billing support | Standard support | | :------------------ | :---------------: | :-------------: | :--------------: | | [Discord](#discord) | ✓ | ✗ | ✓ | | [Email](#email) | - | ✓ | ✓ | ## Email You can reach us at [support@siteassist.io](mailto:support@siteassist.io). ## GitHub * [Found a bug?](https://github.com/siteassist/siteassist-js/issues) * [Have a feature request?](https://github.com/orgs/siteassist/discussions/categories/feature-requests) ## Discord [Join us on Discord](https://discord.gg/f2p8pvWgVw) to chat with us and fellow SiteAssist developers. ## Etiquette Regardless of the method or location through which SiteAssist provides Support, communication should be professional and respectful. Any communication that is deemed objectionable by SiteAssist staff is not tolerated. This includes but is not limited to any communication that is abusive or contains profane language. SiteAssist reserves the right to terminate Support Services in the event of any such objectionable communication. ## Customer responsibilities To ensure efficient resolution of issues, customers are expected to (1) provide detailed information about the issue, (2) cooperate with the Support team during troubleshooting, and (3) utilize available self-service resources for basic inquiries. ## Changes to the support policy We reserve the right to modify, amend, or update this Support Policy, including the types of support offered, support hours, response times, and support plans, at any time and at our sole discretion. Any changes to the Support Policy will be effective immediately upon posting a revised version of this Support Policy. Continued use of our services after such modifications will constitute acknowledgment and acceptance of the changes. --- # Introduction Source: http://docs.siteassist.io/user-guides/get-started/introduction > Get started creating chatbots with SiteAssist ## What is SiteAssist? SiteAssist is the future of website interaction, powered by cutting-edge AI technology. More than just a chatbot platform, SiteAssist transforms your website into an intelligent, interactive experience that understands your visitors' needs and delivers personalized assistance instantly. Our platform goes beyond traditional customer support tools. SiteAssist creates intelligent digital assistants that know your business inside and out, providing contextual help, guiding users through complex processes, and delivering the exact information they need — all while maintaining your brand voice and personality. Whether you're looking to revolutionize customer support, boost user engagement, increase conversions, or create seamless user experiences, SiteAssist empowers you to build the next generation of website interactions. With support for multiple AI models and advanced customization options, you can create truly unique digital experiences that set your business apart. Experience the future of website interaction with SiteAssist — where every visitor gets personalized, intelligent assistance that feels natural and human. --- # Quick Start Source: http://docs.siteassist.io/user-guides/get-started/quick-start > Create your first AI-powered assistant with SiteAssist This quickstart guide shows you how to set up your first AI-powered assistant with SiteAssist. After completing this guide, you will have an intelligent assistant live on your website, ready to provide personalized help and engage with your visitors. ## Get Started After you complete the authentication process and onboarding (which includes creating your first workspace and project), you're ready to set up your AI assistant. > **Haven't signed up yet?** [Create your free SiteAssist account](https://siteassist.io/register) to get started. ### Set Up Your Crawler A **crawler** is like a smart robot that reads your website to understand what it's about. This helps your AI assistant learn your content so it can answer visitors' questions accurately. > **Don't worry if this seems technical** - the screenshots below will guide you through each step! * Navigate to the `Web Crawlers` tab from the sidebar. * Click on **Add Crawler** to set up a new web crawler. * Configure your crawler: * **Name**: Give your crawler a descriptive name (e.g., "My Company Website") * **Start URL**: Enter your website's main URL (e.g., `yourwebsite.com`) * **Preset**: Choose the type that best matches your site: * **Website** - Perfect for most business websites * **Documentation** - For help docs or technical sites * **Blog** - For news, blog, or article-focused sites * **E-commerce** - For online stores (coming soon) * Click **Create & Start Indexing** to start the crawling process. > **This process usually takes 2-5 minutes** depending on your website size. You'll see a progress indicator and logs showing the crawler is working. Screenshot showing the Create Crawler modal with filled form fields (Name, Start URL, and Preset selection) > **Need more control?** For advanced crawler settings like URL exclusion rules, frequency scheduling, and URL limits, see our detailed [Crawler Configuration Guide](#). > The crawler will automatically discover and **index** your website content (think of this like creating a smart library catalog of all your pages). Once complete, your AI assistant will understand your website's content and be ready to help visitors. ### Embed Your Assistant Now it's time to add your AI assistant to your website! This is easier than it might sound. * Go to **Advanced** → **Embed** in the sidebar. Screenshot showing the Embed page with the "Embed Chat Widget" card visible * In the **Embed Chat Widget** card: * **API Key**: Select your publishable key from the dropdown (this is like a secure password that connects your website to SiteAssist) * **Widget Theme**: Choose your preferred appearance (auto/light/dark) * Click **Copy Snippet** to copy the HTML script tag #### Adding the Code to Your Website **For most users:** You'll need to add a small piece of code to your website. Here are the most common ways: **WordPress Users:** * Go to Appearance → Theme Editor → header.php * Paste the code before the `` tag **Shopify Users:** * Go to Online Store → Themes → Actions → Edit Code * Open theme.liquid and paste before `` **Squarespace Users:** * Go to Settings → Advanced → Code Injection * Paste the code in the "Header" section **Other Website Builders:** * Look for "Custom Code," "HTML/CSS," or "Header Code" sections * Contact your web developer if you need help Screenshot showing HTML code editor with the SiteAssist script tag pasted in the head section Save and publish your website. > **Need help?** If you're not sure how to add code to your website, email us at [support@siteassist.io](mailto:support@siteassist.io) - we're happy to walk you through it! **🎉 Congratulations!** Your AI-powered assistant is now live on your website! **You'll know it's working when you see:** * A small chat bubble in the bottom right corner of your website Screenshot showing chat bubble visible in the bottom right corner * Visitors can click it to start chatting with your AI assistant * The assistant will answer questions based on your website content Screenshot showing a website with the SiteAssist chat bubble visible in the bottom right corner > **Pro tip:** Test it yourself! Visit your website and try asking your assistant a question about your business. It should respond with helpful information from your site. ## What's Next? This quick start guide covered the basics to get your assistant up and running. SiteAssist offers much more: * **Advanced customization** - Personalize your assistant's behavior, appearance, and responses * **Multiple AI models** - Choose from OpenAI, Anthropic Claude, Google Gemini, and xAI Grok * **Analytics & insights** - Track conversations, user behavior, and performance metrics * **API integration** - Build custom integrations and workflows * **Team collaboration** - Manage multiple projects and team members * **Enterprise features** - Advanced security, SSO, and custom deployments Explore our comprehensive documentation to unlock the full potential of SiteAssist. ## Need Help? We're here to help you succeed! Whether you have questions, need assistance with setup, or want to discuss advanced use cases, our team is ready to provide personalized support. **Contact us:** [support@siteassist.io](mailto:support@siteassist.io) We'd love to hear about your use case and help you get the most out of SiteAssist! --- # Advanced Features Source: http://docs.siteassist.io/user-guides/widget-integration/advanced-features > Explore powerful advanced features of the SiteAssist widget ## Overview The SiteAssist widget includes several advanced features that enhance user experience and provide powerful capabilities beyond basic chat functionality. ## Text Selection & Context One of the most powerful features of the SiteAssist widget is intelligent text selection. Users can select any text on your page and instantly ask the AI about it. ### How It Works 1. User selects text on your page 2. An "Ask AI" popover appears near the selection 3. User clicks the popover 4. Widget opens with the selected text as context 5. AI provides answers based on both the selection and page content ### Automatic Context Sharing The widget automatically shares page context with the AI, including: * **Page URL**: Current page location * **Page Title**: Document title * **Page Content**: Cleaned, text-only version of page content * **Selected Text**: Any text the user has selected (if using text selection feature) **What gets filtered out:** * Scripts and styles * Navigation menus * Advertisements * SVG and canvas elements * Media elements (audio, video, images) * The widget itself ### Example Use Cases **Documentation Sites:** ``` User selects: "To install the package, run npm install..." User asks: "What does this command do?" AI responds with context-aware explanation ``` **E-commerce:** ``` User selects: "Free shipping on orders over $50" User asks: "How can I get free shipping?" AI explains the shipping policy ``` **Blog Posts:** ``` User selects: "The React useEffect hook..." User asks: "Can you explain this in simpler terms?" AI provides a simplified explanation ``` ### Controlling Text Selection Areas You can control where the text selection popover appears using the `contentSelector` option: ```javascript // Default - only show popover in .main-content elements SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: true, // or omit entirely }); // Show popover everywhere on the page SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: false, }); // Custom selector - only in specific areas SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: ".main-content", }); ``` **Use Cases:** * **Documentation sites**: Restrict to main content areas to avoid confusion * **Blogs**: Only allow selection in article content, not navigation * **E-commerce**: Enable everywhere for product help and support * **Admin panels**: Restrict to specific content sections **Example HTML Structure:** ```html

Documentation

Select this text to ask AI questions!

``` *** ## Fullscreen Mode The widget supports fullscreen mode for immersive chat experiences. ### Automatic Fullscreen Fullscreen is automatically activated on: * Mobile devices (screens \< 768px wide) * When user clicks fullscreen button in widget ### Manual Fullscreen Control The widget can request fullscreen mode, which is handled automatically: ```javascript // Widget internally handles fullscreen requests // No manual API needed - users control via widget UI ``` ### Fullscreen Behavior **When fullscreen is active:** * Widget expands to fill entire viewport * Page scrolling is disabled (`overflow: hidden`) * Close button remains accessible * User can exit via close button or ESC key **When fullscreen exits:** * Widget returns to normal size * Page scrolling is restored * Content layout returns to normal ### Responsive Breakpoints The widget uses these breakpoints: * **Mobile** (`< 768px`): Always fullscreen when open * **Tablet** (`768px - 1024px`): Standard size, can go fullscreen * **Desktop** (`≥ 1024px`): Standard size with sidepanel support *** ## Page Context Integration The widget automatically integrates with your page content to provide intelligent, context-aware responses. ### Context Extraction When a user interacts with the widget, it automatically extracts: ```javascript { url: "https://yoursite.com/page", title: "Page Title", content: "Clean text content of the page...", textSelection: "Selected text (if any)" } ``` ### How Content is Cleaned The widget intelligently cleans page content: 1. **Clone** the document body 2. **Remove** unnecessary elements (scripts, styles, widgets, media) 3. **Extract** link text and URLs: `"Link Text (https://url)"` 4. **Normalize** whitespace and line breaks 5. **Send** to AI for context-aware responses ### Example Context Usage User visits: `https://example.com/pricing` ```javascript // Automatically shared context: { url: "https://example.com/pricing", title: "Pricing - Example SaaS", content: "Pricing Plans Starter $9/month Basic features... Pro $29/month Advanced features...", textSelection: null } ``` User asks: "What's included in the Pro plan?" AI receives context and can answer specifically about that page's Pro plan. ### Privacy Considerations **What is shared:** * Publicly visible text content * Page URL and title * User's selected text **What is NOT shared:** * Form inputs or user data * Hidden or password-protected content * Images or media files * Scripts or technical implementation *** ## Custom Events The widget dispatches custom events that you can listen to for advanced integrations. ### Event Format All custom events are prefixed with `sa:` and dispatched on the `window` object: ```javascript window.addEventListener("sa:event_name", (event) => { console.log("Event detail:", event.detail); }); ``` ### Common Events While specific events depend on your widget configuration, you can listen for custom events: ```javascript // Example: Listen for chat opened window.addEventListener("sa:opened", () => { console.log("Chat widget opened"); // Track in your analytics analytics.track("Chat Opened"); }); // Example: Listen for chat closed window.addEventListener("sa:closed", () => { console.log("Chat widget closed"); }); // Example: Custom event from widget window.addEventListener("sa:custom_action", (event) => { console.log("Custom action:", event.detail); }); ``` ### Event-Driven Integrations **Example - Track widget usage:** ```javascript let chatOpenedAt = null; window.addEventListener("sa:opened", () => { chatOpenedAt = Date.now(); console.log("Chat opened"); }); window.addEventListener("sa:closed", () => { if (chatOpenedAt) { const duration = Date.now() - chatOpenedAt; console.log(`Chat was open for ${duration}ms`); chatOpenedAt = null; } }); ``` **Example - Trigger other UI elements:** ```javascript window.addEventListener("sa:opened", () => { // Hide other overlays when chat opens document.getElementById("promo-banner").style.display = "none"; }); window.addEventListener("sa:closed", () => { // Show promo banner again document.getElementById("promo-banner").style.display = "block"; }); ``` *** ## Responsive Behavior The widget automatically adapts to different screen sizes and orientations. ### Mobile Optimization **On mobile devices (\< 768px):** * Widget opens in fullscreen * "Ask AI" text selection popover is optimized for touch * Page scrolling disabled when widget is open * Swipe gestures for closing (native behavior) ### Tablet Behavior **On tablets (768px - 1024px):** * Standard widget size * Sidepanel floats over content (doesn't push) * Touch-optimized interactions * Responsive text selection ### Desktop Experience **On desktop (≥ 1024px):** * Full-featured experience * Sidepanel can push content * Keyboard shortcuts work * Precise text selection ### Orientation Changes The widget automatically handles orientation changes: ```javascript // Automatically handled - no code needed // Widget adjusts when device rotates ``` *** ## Sidepanel Integration The sidepanel widget type offers advanced integration with your application layout. ### Content Push Behavior When sidepanel opens on desktop screens: ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY", type: "sidepanel", appContainerSelector: ".main-content", }); ``` **Desktop (≥ 1024px):** * Container margin-right: `400px` * Smooth transition animation * Content visible alongside widget **Tablet (\< 1024px):** * Sidepanel floats over content * No content push * Overlay-style interaction **Mobile (\< 768px):** * Full-screen mode * Content hidden while widget open ### Multiple Containers You can have multiple containers that respond to the sidepanel: ```html
Header content
Main content
``` All containers with the class will be pushed when the sidepanel opens. ### Custom Transition The widget applies default transitions, but you can customize: ```css .siteassist-container { transition-property: margin-right; transition-duration: 200ms; transition-timing-function: ease-in-out; } ``` *** ## Performance Optimization The widget is designed for optimal performance: ### Async Loading The widget loads asynchronously and doesn't block page rendering: ```javascript // Non-blocking async load o.async = !0; o.src = "https://...widget.js"; e.head.appendChild(o); ``` ### Lazy Initialization The iframe content only loads when: * Widget is initialized * User first interacts with the widget ### Resource Optimization * **Small bundle size**: \~10KB gzipped * **No external dependencies**: Self-contained * **Efficient event handlers**: Debounced and throttled * **Smart content extraction**: Only when needed *** ## Security Best Practices ### Publishable Key Protection ```javascript // ✅ Good - use environment variables SiteAssist("init", { apiKey: process.env.NEXT_PUBLIC_SITEASSIST_PUBLISHABLE_KEY, }); // ❌ Avoid - hardcoded keys in public repos SiteAssist("init", { apiKey: "pk_live_hardcoded_key_123", // Don't commit this! }); ``` ### Content Security Policy (CSP) If you use CSP headers, whitelist these domains: ``` script-src 'self' https://cnrib24ur3hk4b49.public.blob.vercel-storage.com; frame-src https://widgets.siteassist.io; connect-src https://api.siteassist.io; ``` ### Cross-Origin Communication The widget uses secure `postMessage` communication: ```javascript // Widget validates message origin if (ev.origin !== options.widgetUrl) return; ``` *** ## Advanced Customization Examples ### Custom Trigger Button Replace default floating button with your own: ```html ``` ### Conditional Loading Load widget only for specific pages or users: ```javascript // Only load on product pages if (window.location.pathname.startsWith("/products/")) { SiteAssist("init", { apiKey: "YOUR_API_KEY", }); } // Only for logged-in users if (userIsLoggedIn) { SiteAssist("init", { apiKey: "YOUR_API_KEY", externalId: currentUser.id, }); } ``` ### Theme Synchronization Sync widget theme with your site: ```javascript // Watch for site theme changes const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.attributeName === "data-theme") { const theme = document.documentElement.getAttribute("data-theme"); SiteAssist("changeTheme", theme); } }); }); observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"], }); ``` *** ## Troubleshooting ### Text Selection Not Working **Check:** * Widget is properly initialized * No conflicting JavaScript on the page * Browser supports Selection API * Content selector is correctly configured **Debug:** ```javascript window.addEventListener("mouseup", () => { const selection = window.getSelection(); console.log("Selected text:", selection.toString()); // Check if selection is in the right area const range = selection.getRangeAt(0); const container = range.commonAncestorContainer; console.log("Selection container:", container); }); ``` **Common Issues:** * **Popover not appearing**: Check your `contentSelector` setting * **Popover appears in wrong areas**: Verify your CSS selector is correct * **Selection not working at all**: Ensure widget is properly initialized **Example debugging:** ```javascript // Test if contentSelector is working SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: ".test-area", // Test with a specific area }); // Check if the selector exists console.log("Content element found:", document.querySelector(".test-area")); ``` ### Fullscreen Issues **Common causes:** * Browser restrictions on fullscreen * Conflicting CSS `overflow` properties * Z-index conflicts **Solution:** ```css /* Ensure widget has high z-index */ .sa-frame.fullscreen { z-index: 999999 !important; } ``` ### Content Not Being Captured **Check:** * Page content isn't in an iframe * Content is rendered (not dynamically loaded after widget init) * No security restrictions *** ## Next Steps * **[Examples](/docs/user-guides/widget-integration/examples)** - See real-world implementation examples * **[API Reference](/docs/user-guides/widget-integration/api-reference)** - Complete API documentation * **[Configuration](/docs/user-guides/widget-integration/configuration)** - Customization options Need help with advanced features? Contact us at [support@siteassist.io](mailto:support@siteassist.io) --- # API Reference Source: http://docs.siteassist.io/user-guides/widget-integration/api-reference > Complete reference for the SiteAssist JavaScript API ## API Overview The SiteAssist widget exposes a simple JavaScript API that allows you to control the widget programmatically. All API methods are called through the global `SiteAssist` function. ```javascript window.SiteAssist(command, ...arguments); ``` ## Available Methods ### `init` Initializes the SiteAssist widget with your configuration. **Signature:** ```typescript SiteAssist("init", options: InitOptions): void ``` **Parameters:** * `options` (object) - Configuration options **Example:** ```javascript SiteAssist("init", { apiKey: "pk_live_abc123", // Your publishable key from dashboard type: "floating-bubble", theme: "auto", }); ``` **See also:** [Configuration Guide](/docs/user-guides/widget-integration/configuration) for all available options. *** ### `open` Opens the chat widget. **Signature:** ```typescript SiteAssist("open"): void ``` **Example:** ```javascript // Open the widget programmatically SiteAssist("open"); ``` **Use cases:** * Open widget when user clicks a custom button * Auto-open after a delay * Open based on user behavior or triggers **Example - Custom trigger button:** ```html ``` **Example - Auto-open after 5 seconds:** ```javascript setTimeout(() => { SiteAssist("open"); }, 5000); ``` *** ### `close` Closes the chat widget. **Signature:** ```typescript SiteAssist("close"): void ``` **Example:** ```javascript // Close the widget programmatically SiteAssist("close"); ``` **Use cases:** * Close widget when user completes an action * Close on navigation to certain pages * Custom close triggers **Example - Close on page navigation:** ```javascript // Close widget when navigating away window.addEventListener("beforeunload", () => { SiteAssist("close"); }); ``` *** ### `toggle` Toggles the widget between open and closed states. **Signature:** ```typescript SiteAssist("toggle"): void ``` **Example:** ```javascript // Toggle widget state SiteAssist("toggle"); ``` **Use cases:** * Custom toggle buttons in your UI * Keyboard shortcuts * Menu items **Example - Keyboard shortcut:** ```javascript document.addEventListener("keydown", (e) => { // Ctrl/Cmd + K to toggle widget if ((e.ctrlKey || e.metaKey) && e.key === "k") { e.preventDefault(); SiteAssist("toggle"); } }); ``` *** ### `changeTheme` Changes the widget theme dynamically. **Signature:** ```typescript SiteAssist("changeTheme", theme: "light" | "dark" | "auto"): void ``` **Parameters:** * `theme` (string) - One of `"light"`, `"dark"`, or `"auto"` **Example:** ```javascript // Change to dark theme SiteAssist("changeTheme", "dark"); // Change to light theme SiteAssist("changeTheme", "light"); // Change to auto (system preference) SiteAssist("changeTheme", "auto"); ``` **Use cases:** * Sync with your site's theme switcher * Match user preferences * Time-based theme switching **Example - Sync with site theme:** ```javascript // When user changes site theme function onSiteThemeChange(newTheme) { // Update site theme document.documentElement.setAttribute("data-theme", newTheme); // Update SiteAssist theme SiteAssist("changeTheme", newTheme); } ``` **Example - Theme toggle button:** ```html ``` *** ### `track` (Coming Soon) Track custom events and analytics. **Signature:** ```typescript SiteAssist("track", eventName: string, data?: any): void ``` **Status:** This feature is currently in development and will be available soon. **Planned usage:** ```javascript // Once available, you'll be able to track events like this: // Track a simple event SiteAssist("track", "button_clicked"); // Track with additional data SiteAssist("track", "product_viewed", { productId: "12345", productName: "Premium Widget", price: 99.99, }); // E-commerce tracking SiteAssist("track", "add_to_cart", { productId: "123", quantity: 1, }); SiteAssist("track", "purchase_completed", { orderId: "ORD-123", total: 199.99, }); ``` *** ### `identify` (Coming Soon) Identify users with additional information. **Signature:** ```typescript SiteAssist("identify", user: { externalId?: string; email?: string; name?: string; attributes?: Record; }): void ``` **Status:** This feature is currently in development and will be available soon. **Planned usage:** ```javascript // Once available, you'll be able to identify users like this: SiteAssist("identify", { externalId: "user_123", email: "user@example.com", name: "John Doe", attributes: { plan: "premium", signupDate: "2024-01-15", }, }); ``` *** ## Queuing Commands The SiteAssist API supports command queuing, which means you can call API methods before the widget script has fully loaded. Commands will be executed in order once the script is ready. **Example:** ```javascript // These commands will be queued and executed when ready SiteAssist("init", { apiKey: "YOUR_API_KEY" }); SiteAssist("open"); ``` This is handled automatically by the loader script: ```javascript !(function (t, e, c, n, s) { if (t[s]) return; const i = (t[s] = function () { i._q.push(arguments); }); i._q = []; // ... loads actual script })(window, document, 0, 0, "SiteAssist"); ``` *** ## Custom Events The widget dispatches custom events that you can listen to: ```javascript // Listen for custom widget events window.addEventListener("sa:event_name", (event) => { console.log("Widget event:", event.detail); }); ``` **Available Events:** Events are prefixed with `sa:` and include any custom events dispatched from the widget. **Example - Listen for custom events:** ```javascript // Listen for all widget events window.addEventListener("sa:chat_opened", () => { console.log("User opened the chat"); }); window.addEventListener("sa:message_sent", (event) => { console.log("User sent a message:", event.detail); }); ``` *** ## TypeScript Support For TypeScript projects, you can add type definitions: ```typescript declare global { interface Window { SiteAssist: { ( cmd: "init", opts: { apiKey: string; type?: "floating-bubble" | "sidepanel"; theme?: "light" | "dark" | "auto"; contentSelector?: boolean | string; externalId?: string; appContainerSelector?: string; widgetUrl?: string; apiUrl?: string; }, ): void; (cmd: "open"): void; (cmd: "close"): void; (cmd: "toggle"): void; (cmd: "changeTheme", theme: "light" | "dark" | "auto"): void; }; } } ``` **Usage:** ```typescript // Now you get autocomplete and type checking window.SiteAssist("init", { apiKey: "pk_live_abc123", theme: "dark", // TypeScript will validate this }); // Open the widget window.SiteAssist("open"); // Change theme window.SiteAssist("changeTheme", "light"); ``` *** ## Complete API Example Here's a comprehensive example using multiple API methods: ```javascript // Initialize the widget SiteAssist("init", { apiKey: "pk_live_abc123", type: "floating-bubble", theme: "auto", }); // Auto-open after 10 seconds for first-time visitors if (!localStorage.getItem("siteassist_visited")) { setTimeout(() => { SiteAssist("open"); }, 10000); localStorage.setItem("siteassist_visited", "true"); } // Sync theme with site theme switcher document.getElementById("site-theme-toggle").addEventListener("click", (e) => { const newTheme = e.target.dataset.theme; SiteAssist("changeTheme", newTheme); }); // Add custom help button document.getElementById("help-button").addEventListener("click", () => { SiteAssist("open"); }); // Keyboard shortcut (Ctrl/Cmd + K) document.addEventListener("keydown", (e) => { if ((e.ctrlKey || e.metaKey) && e.key === "k") { e.preventDefault(); SiteAssist("toggle"); } }); ``` *** ## Best Practices ### 1. Initialize Once Only call `init` once per page load: ```javascript // ✅ Good SiteAssist("init", { apiKey: "YOUR_API_KEY" }); // ❌ Avoid SiteAssist("init", { apiKey: "YOUR_API_KEY" }); SiteAssist("init", { apiKey: "YOUR_API_KEY" }); // Don't initialize twice ``` ### 2. Handle Errors Gracefully Check if SiteAssist is loaded before calling: ```javascript if (window.SiteAssist) { SiteAssist("open"); } else { console.warn("SiteAssist not loaded yet"); } ``` ### 3. Respect User Intent Don't auto-open too aggressively: ```javascript // ✅ Good - give users time to browse setTimeout(() => { if (!userHasInteracted) { SiteAssist("open"); } }, 30000); // 30 seconds // ❌ Annoying - too soon setTimeout(() => { SiteAssist("open"); }, 1000); // 1 second - too fast! ``` *** ## Error Handling The SiteAssist API fails silently to avoid breaking your website. However, you can check the console for warnings: ```javascript // Check if API is available if (typeof window.SiteAssist === "undefined") { console.warn("SiteAssist is not loaded"); } // Wrap critical calls in try-catch if needed try { SiteAssist("open"); } catch (error) { console.error("Failed to open widget:", error); } ``` *** ## Next Steps * **[Advanced Features](/docs/user-guides/widget-integration/advanced-features)** - Explore text selection, fullscreen, and more * **[Examples](/docs/user-guides/widget-integration/examples)** - See real-world implementation examples * **[Configuration](/docs/user-guides/widget-integration/configuration)** - Learn about all configuration options Need help with the API? Contact us at [support@siteassist.io](mailto:support@siteassist.io) --- # Configuration Source: http://docs.siteassist.io/user-guides/widget-integration/configuration > Customize the SiteAssist widget to match your brand and requirements ## Configuration Overview The SiteAssist widget is highly customizable through configuration options passed to the `init` method. This guide covers all available options and how to use them. ## Basic Configuration The minimal configuration requires only an API key: ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY_HERE", }); ``` ## Configuration Options ### Required Options #### `apiKey` (string) Your SiteAssist project publishable key. Get this from your dashboard under **Advanced** → **API Keys** → **Publishable Keys**. ```javascript SiteAssist("init", { apiKey: "pk_live_abc123...", }); ``` *** ### Widget Type Options #### `type` (string) Defines the widget type. Default: `"floating-bubble"` **Options:** * `"floating-bubble"` - Floating chat button with expandable interface * `"sidepanel"` - Fixed side panel integration ```javascript // Floating bubble (default) SiteAssist("init", { apiKey: "YOUR_API_KEY", type: "floating-bubble", }); // Sidepanel SiteAssist("init", { apiKey: "YOUR_API_KEY", type: "sidepanel", }); ``` *** ### Theme Options #### `theme` (string) Controls the widget's color scheme. Default: `"auto"` **Options:** * `"auto"` - Automatically matches system preference * `"light"` - Always use light theme * `"dark"` - Always use dark theme ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY", theme: "dark", // Force dark theme }); ``` You can also change the theme dynamically: ```javascript // Change to light theme SiteAssist("changeTheme", "light"); // Change to dark theme SiteAssist("changeTheme", "dark"); // Change to auto (system preference) SiteAssist("changeTheme", "auto"); ``` *** ### Sidepanel Options #### `appContainerSelector` (string) CSS selector for the container that should be pushed when the sidepanel opens. Only applies when `type: "sidepanel"`. Default: `".siteassist-container"` ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY", type: "sidepanel", appContainerSelector: ".main-content", // Custom selector }); ``` **HTML Structure Example:** ```html
``` **Responsive Behavior:** * On screens **≥1024px**: Content is pushed by 400px * On screens **\<1024px**: Sidepanel floats over content (no push) * On screens **\<768px**: Full-screen mode automatically *** ### Content Selection Options #### `contentSelector` (boolean | string) Controls where the text selection popover appears when users select text on your page. **Options:** * `true` or `undefined` (default) - Only show popover when text is selected within `.main-content` elements * `false` - Show popover everywhere on the page (disable content filtering) * `string` - Custom CSS selector for where the popover should appear ```javascript // Default behavior - only in .main-content elements SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: true, // or omit entirely }); // Disable content filtering - show popover everywhere SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: false, }); // Custom selector - only in .main-content elements SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: ".main-content", }); // Only in article content SiteAssist("init", { apiKey: "YOUR_API_KEY", contentSelector: "article .content", }); ``` **HTML Structure Example:** ```html

This text WILL show the selection popover

This text will show the selection popover

``` **Use Cases:** * **Documentation sites**: Restrict to main content areas * **Blogs**: Only allow selection in article content * **E-commerce**: Enable everywhere for product help * **Admin panels**: Restrict to specific content sections *** ### Advanced Options #### `externalId` (string) Optional identifier for the user. Useful for tracking specific users or personalizing experiences. ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY", externalId: "user_12345", // Your internal user ID }); ``` > **Note**: Full user identification features (email, name, attributes) are **coming soon**. #### `widgetUrl` (string) Custom widget hosting URL. Only needed for self-hosted or custom deployments. Default: `"https://widgets.siteassist.io"` ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY", widgetUrl: "https://custom-widgets.yourdomain.com", }); ``` #### `apiUrl` (string) Custom API endpoint URL. Only needed for custom deployments. Default: `"https://api.siteassist.io"` ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY", apiUrl: "https://custom-api.yourdomain.com", }); ``` *** ## Dashboard Customization Many visual customization options are configured through the SiteAssist dashboard under **Project Settings** → **Widget Appearance**: ### Colors & Branding Configure these in your dashboard: * **Brand Color** - Primary accent color for the widget * **Brand Color (Dark Mode)** - Primary color for dark theme * **User Message Bubble Color** - Color for user messages * **User Message Bubble Color (Dark Mode)** - User message color in dark mode * **Chat Button Color** - Background color for the floating button ### Positioning & Layout * **Position** - Choose `bottom-left` or `bottom-right` * **Width** - Widget width in pixels (default: 400px) * **Max Height** - Maximum height in pixels (default: 700px) * **Offset** - X and Y offset from corner in pixels * **Base Font Size** - Base font size in pixels (default: 16px) ### Content & Messaging * **Welcome Message** - First message users see * **Input Placeholder** - Placeholder text in the input field * **Header Title** - Title shown in the widget header * **Assistant Avatar** - Custom avatar image URL * **Chat Button Icon** - Custom icon for the chat button ### Behavior * **Open Delay** - Auto-open delay in milliseconds (0 = disabled) *** ## Complete Configuration Example Here's a full example combining multiple options: ```javascript SiteAssist("init", { // Required apiKey: "pk_live_abc123def456", // Widget type type: "floating-bubble", // Theming theme: "auto", // Content selection contentSelector: ".main-content", // Only show popover in main content // User tracking externalId: "user_12345", // Advanced (usually not needed) widgetUrl: "https://widgets.siteassist.io", apiUrl: "https://api.siteassist.io", }); ``` *** ## Configuration Best Practices ### 1. Use Environment Variables Store your publishable key securely using environment variables: ```javascript // Next.js example SiteAssist("init", { apiKey: process.env.NEXT_PUBLIC_SITEASSIST_PUBLISHABLE_KEY, theme: "auto", }); ``` ### 2. Conditional Configuration Configure differently based on environment: ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY", theme: "auto", // Use development widget URL in dev environment ...(process.env.NODE_ENV === "development" && { widgetUrl: "http://localhost:3000", }), }); ``` ### 3. User-Based Theme Set theme based on user preference: ```javascript const userPreference = localStorage.getItem("theme") || "auto"; SiteAssist("init", { apiKey: "YOUR_API_KEY", theme: userPreference, }); ``` ### 4. Dynamic External ID Set external ID based on logged-in user: ```javascript const userId = getCurrentUser()?.id; SiteAssist("init", { apiKey: "YOUR_API_KEY", externalId: userId || null, }); ``` *** ## Testing Your Configuration After configuring the widget, verify it's working correctly: ### 1. Visual Inspection * Widget appears in the correct position * Colors match your configuration * Theme is applied correctly ### 2. Console Verification Open browser DevTools and check: ```javascript // Check if SiteAssist is loaded console.log(window.SiteAssist); // Should show a function if loaded correctly ``` ### 3. Interaction Testing * Click to open/close the widget * Test theme changes * Verify sidepanel behavior (if applicable) * Test text selection feature ### 4. Responsive Testing Test on different screen sizes: * Desktop (>1024px) * Tablet (768px - 1024px) * Mobile (\<768px) *** ## Troubleshooting ### Widget position is wrong Check your dashboard settings for position and offset values. ### Colors not applying Dashboard settings override any code-level color configurations. Update colors in your SiteAssist dashboard. ### Sidepanel not pushing content Ensure your container has the correct class or matches the `appContainerSelector`: ```html
``` ### Theme not changing Make sure you're calling `changeTheme` after initialization: ```javascript // Initialize first SiteAssist("init", { apiKey: "YOUR_API_KEY" }); // Then change theme SiteAssist("changeTheme", "dark"); ``` *** ## Next Steps * **[API Reference](/docs/user-guides/widget-integration/api-reference)** - Learn about available API methods * **[Advanced Features](/docs/user-guides/widget-integration/advanced-features)** - Explore powerful capabilities * **[Examples](/docs/user-guides/widget-integration/examples)** - See real-world implementation examples Need help with configuration? Contact us at [support@siteassist.io](mailto:support@siteassist.io) --- # Implementation Examples Source: http://docs.siteassist.io/user-guides/widget-integration/examples > Real-world examples of SiteAssist widget integration ## Overview This guide provides complete, real-world examples of integrating the SiteAssist widget in various scenarios and platforms. ## Basic Examples ### Simple Website The most straightforward integration for a basic website: ```html My Website

Welcome to My Website

Your content here...

``` *** ## Framework Examples ### Next.js (App Router) **File: `app/layout.tsx`** ```tsx import Script from "next/script"; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( {children} {/* SiteAssist Widget Loader */} {/* Initialize SiteAssist */} ); } ``` **With environment variables:** ```bash # .env.local NEXT_PUBLIC_SITEASSIST_PUBLISHABLE_KEY=pk_live_abc123 ``` *** ### Next.js (Pages Router) **File: `pages/_app.tsx`** ```tsx import type { AppProps } from "next/app"; import Script from "next/script"; export default function App({ Component, pageProps }: AppProps) { return ( <> ); } ``` *** ### React **File: `App.tsx`** ```tsx import { useEffect } from "react"; function App() { useEffect(() => { // Load SiteAssist script if (!window.SiteAssist) { const loader = document.createElement("script"); loader.innerHTML = ` !function(t,e,c,n,s){if(t[s])return;const i=t[s]=function(){i._q.push(arguments)};i._q=[];const o=e.createElement("script");o.async=!0,o.src="https://cnrib24ur3hk4b49.public.blob.vercel-storage.com/widget/latest/widget.js",e.head.appendChild(o)}(window,document,0,0,"SiteAssist"); `; document.head.appendChild(loader); // Initialize const init = document.createElement("script"); init.innerHTML = ` SiteAssist("init", { apiKey: "${import.meta.env.VITE_SITEASSIST_API_KEY}", theme: "auto" }); `; document.head.appendChild(init); } }, []); return
{/* Your app content */}
; } export default App; ``` **Alternative: Using public/index.html** ```html React App
``` *** ### Vue.js **File: `index.html` or `app.html`** ```html Vue App
``` *** ### Angular **File: `src/index.html`** ```html Angular App ``` *** ## Platform-Specific Examples ### WordPress (Theme Integration) **File: `header.php`** ```php > ``` **Alternative: Using functions.php** ```php ``` *** ## Advanced Use Cases ### SaaS Dashboard with Sidepanel Perfect for web applications and admin panels: ```html SaaS Dashboard

Dashboard

Your content here...

``` *** ### E-commerce with Custom Triggers Product pages with custom "Ask AI" buttons: ```html Product Page

Premium Widget

$99.99

This amazing product includes...

``` *** ### Documentation Site with Content Selection Perfect for documentation sites where you want to restrict text selection to main content areas: ```html Documentation

Getting Started

Welcome to our documentation. You can select any text in this area to ask questions about it.

For example, select the text "API Reference" above and ask "What's in the API reference?"

``` *** ### E-commerce with Global Text Selection Enable text selection everywhere for comprehensive product support: ```html ``` *** ### Blog with Article-Only Selection Restrict text selection to article content only: ```html ``` *** ### Documentation Site with Auto-Open Open widget automatically for users who seem stuck: ```html ``` *** ### Multi-Language Support Sync widget theme with site language: ```html ``` *** ### A/B Testing Integration Track which widget variant performs better: ```html ``` *** ### Conditional Loading by Page Load widget only on specific pages: ```html ``` *** ### Custom Event Integration Integrate with your analytics platform: ```html ``` *** ## Next Steps * **[API Reference](/docs/user-guides/widget-integration/api-reference)** - Complete API documentation * **[Advanced Features](/docs/user-guides/widget-integration/advanced-features)** - Explore powerful capabilities * **[Configuration](/docs/user-guides/widget-integration/configuration)** - Customization options Need help implementing? Contact us at [support@siteassist.io](mailto:support@siteassist.io) --- # Installation Source: http://docs.siteassist.io/user-guides/widget-integration/installation > Learn how to install the SiteAssist widget on your website ## Installation Methods SiteAssist offers three installation methods to fit your needs. Choose the one that works best for your website. ## Method 1: Floating Bubble Widget The floating bubble is the most popular integration method. It adds a chat button in the corner of your website that expands into a full chat interface. ### Step 1: Get Your Publishable Key 1. Log in to your [SiteAssist dashboard](https://app.siteassist.io) 2. Navigate to **Advanced** → **API Keys** 3. Go to the **Publishable Keys** tab 4. Copy your project's publishable key ### Step 2: Add the Script Add this code snippet to your website's HTML, preferably in the `` section or just before the closing `` tag: ```html ``` ### Step 3: Replace the Publishable Key Replace `YOUR_API_KEY_HERE` with your actual publishable key from the dashboard. ### Step 4: Test Visit your website and you should see the chat button appear in the bottom right corner! *** ## Method 2: Sidepanel Widget The sidepanel widget integrates as a fixed panel on the side of your website, perfect for web applications and dashboards. ### Installation ```html ``` ### Container Configuration The sidepanel can push your main content when opened. Add the `siteassist-container` class to your main content container: ```html
``` Or specify a custom selector: ```javascript SiteAssist("init", { apiKey: "YOUR_API_KEY_HERE", type: "sidepanel", appContainerSelector: "#app-content", // Custom selector }); ``` *** ## Method 3: Iframe Embed For full control over placement and styling, use the iframe embed method. ### Basic Iframe ```html ``` ### Responsive Iframe For a responsive iframe that adapts to different screen sizes: ```html
``` ### Iframe URL Parameters The iframe URL supports these query parameters: * `apiKey` (required) - Your SiteAssist API key * `theme` (optional) - `light`, `dark`, or `auto` (default: `auto`) * `externalId` (optional) - User identifier for personalization Example with all parameters: ```html ``` *** ## Platform-Specific Instructions ### WordPress 1. Go to **Appearance** → **Theme Editor** 2. Open **header.php** or use a plugin like "Insert Headers and Footers" 3. Paste the code before the `` tag 4. Save changes > **Tip**: Use a plugin like "Code Snippets" or "WPCode" for safer code injection. ### Shopify 1. Go to **Online Store** → **Themes** 2. Click **Actions** → **Edit Code** 3. Open **theme.liquid** 4. Paste the code before `` 5. Save and preview ### Squarespace 1. Go to **Settings** → **Advanced** → **Code Injection** 2. Paste the code in the **Header** section 3. Save changes ### Webflow 1. Go to **Project Settings** → **Custom Code** 2. Paste the code in the **Head Code** section 3. Publish your site ### React / Next.js For React applications, add the script in your main HTML file or use `next/script`: ```jsx import Script from "next/script"; export default function Layout({ children }) { return ( <> {children} ); } ``` ### Vue.js Add the script in your `index.html` or `app.html`: ```html
``` *** ## Verification After installation, verify the widget is working: 1. **Visual Check**: You should see the chat button (floating bubble) or panel (sidepanel) 2. **Console Check**: Open browser DevTools → Console. No errors should appear 3. **Interaction Test**: Click the chat button and try sending a message ### Common Issues **Widget not appearing?** * Check that your API key is correct * Verify the script is loading (check Network tab in DevTools) * Ensure no ad blockers are interfering * Check browser console for errors **Script loading but widget not initializing?** * Make sure you're calling `SiteAssist("init", {...})` after the loader script * Verify your API key is valid and active * Check that your domain is authorized in the dashboard **Need help?** Contact us at [support@siteassist.io](mailto:support@siteassist.io) *** ## Next Steps * **[Configure the widget](/docs/user-guides/widget-integration/configuration)** - Customize appearance and behavior * **[API Reference](/docs/user-guides/widget-integration/api-reference)** - Control the widget programmatically * **[Advanced Features](/docs/user-guides/widget-integration/advanced-features)** - Explore powerful capabilities --- # Widget Integration Overview Source: http://docs.siteassist.io/user-guides/widget-integration/overview > Learn how to integrate and customize the SiteAssist chat widget on your website ## What is the SiteAssist Widget? The SiteAssist widget is a powerful, customizable chat interface that brings AI-powered assistance directly to your website visitors. It's designed to be lightweight, fast, and easy to integrate while providing a rich, interactive experience. ## Key Features ### 🎨 **Fully Customizable** * Multiple widget types (floating bubble, sidepanel, iframe) * Theme support (light, dark, auto) * Customizable colors, positioning, and styling * Brand-aligned appearance ### 💬 **Intelligent Text Selection** * Users can select text on your page and instantly ask the AI about it * Context-aware responses based on selected content * Configurable selection areas (restrict to specific content sections) * Seamless integration with page content ### 📱 **Responsive Design** * Works perfectly on desktop, tablet, and mobile devices * Automatic fullscreen mode on mobile * Adaptive layout based on screen size ### ⚡ **Performance Optimized** * Lightweight script (\~10KB gzipped) * Async loading doesn't block page rendering * Minimal impact on site performance ### 🔒 **Privacy & Security** * Secure publishable key authentication * No tracking of user data without consent * GDPR compliant ## Widget Types SiteAssist offers three integration methods to fit different use cases: ### **Floating Bubble** The most popular option - a floating chat button that appears in the corner of your website. **Best for:** * Marketing websites * E-commerce stores * General business websites * Blogs and content sites **Features:** * Unobtrusive when closed * Expandable chat interface * "Ask AI" button with text selection support * Configurable text selection areas * Customizable position (bottom-left or bottom-right) ### **Sidepanel** A fixed side panel that integrates with your website's layout. **Best for:** * Web applications * Dashboards * Admin panels * SaaS products **Features:** * Always visible or toggleable * Pushes page content when opened * Seamless integration with app layout * Customizable container selector ### **Iframe Embed** A simple iframe for full control over placement and styling. **Best for:** * Custom implementations * Embedded in specific pages * Full-page chat experiences * Custom layouts **Features:** * Direct embedding anywhere on your page * Complete control over size and placement * No additional UI elements * Standalone chat interface ## How It Works The SiteAssist widget follows a simple lifecycle: 1. **Load**: Async script loads without blocking your page 2. **Initialize**: Widget initializes with your publishable key and configuration 3. **Ready**: Chat interface is ready for user interaction 4. **Context-Aware**: Automatically detects page content for better responses 5. **Interactive**: Users can chat, select text, and get instant AI assistance ## Getting Started Ready to add the SiteAssist widget to your website? 1. **[Install the widget](/docs/user-guides/widget-integration/installation)** - Choose your integration method 2. **[Configure options](/docs/user-guides/widget-integration/configuration)** - Customize appearance and behavior 3. **[Use the API](/docs/user-guides/widget-integration/api-reference)** - Control the widget programmatically 4. **[Explore advanced features](/docs/user-guides/widget-integration/advanced-features)** - Unlock powerful capabilities ## Browser Support The SiteAssist widget works on all modern browsers: * ✅ Chrome 90+ * ✅ Firefox 88+ * ✅ Safari 14+ * ✅ Edge 90+ * ✅ Mobile browsers (iOS Safari, Chrome Mobile, Samsung Internet) > **Note**: Internet Explorer is not supported. For legacy browser support, please contact our team. ## Need Help? Have questions about widget integration? We're here to help! * **Documentation**: Browse our comprehensive guides * **Support**: Email us at [support@siteassist.io](mailto:support@siteassist.io) * **Community**: Join our Discord community (coming soon) Let's get your AI assistant integrated! Continue to the [installation guide](/docs/user-guides/widget-integration/installation) to begin. --- # Create chat completion Source: http://docs.siteassist.io/developer-api/chat-completions/create-chat-completion > Create a chat completion using the configured assistant. Supports streaming (Server-Sent Events) and non-streaming JSON responses. Streaming returns incremental tokens, while non-streaming returns the full completion along with token usage. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Close a conversation Source: http://docs.siteassist.io/developer-api/conversations/close-conversation > Close an open conversation for the authenticated visitor in the current project. Optionally include a close reason. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Get a conversation Source: http://docs.siteassist.io/developer-api/conversations/get-conversation > Retrieve a single conversation by ID for the authenticated visitor in the current project, including its messages and human agent info if assigned. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # List conversations Source: http://docs.siteassist.io/developer-api/conversations/get-conversations > Retrieve a paginated list of conversations for the authenticated visitor within the current project. Supports filtering, ordering, and pagination. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Start a new conversation Source: http://docs.siteassist.io/developer-api/conversations/start-conversation > Create a new conversation for a customer to interact with an AI assistant. This endpoint initializes a conversation session and returns the conversation details including a unique conversation ID that can be used for subsequent message exchanges. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Get current visitor Source: http://docs.siteassist.io/developer-api/identity/get-me > Return the authenticated visitor associated with the provided bearer token. Useful for verifying session state and retrieving basic profile information. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Initialize visitor session Source: http://docs.siteassist.io/developer-api/identity/init > Create or fetch an anonymous visitor for the provided publishable API key and device identifier, then return a short-lived session token and visitor profile. Returns 201 on first-time creation and 200 on subsequent calls for the same device. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Retrieve messages from a conversation Source: http://docs.siteassist.io/developer-api/messages/get-messages > Retrieve messages from a conversation, ordered chronologically from oldest to newest. Supports pagination and filtering by role or status. Only the conversation owner can access their messages. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Submit feedback for a message Source: http://docs.siteassist.io/developer-api/messages/send-message-feedback > Submit feedback (like/dislike) for a specific message in a conversation. This endpoint allows users to rate the quality and helpfulness of AI assistant responses. **Use Cases:** - Rate the helpfulness of AI responses - Provide training data for model improvement - Track user satisfaction with AI interactions - Remove existing feedback by setting feedback to null - Update existing feedback by submitting a new value **Authentication Required:** This endpoint requires a valid Bearer token in the Authorization header. The user must have access to the conversation containing the message. **Feedback Types:** - `like`: Positive feedback indicating the response was helpful and accurate - `dislike`: Negative feedback indicating the response was unhelpful or incorrect - `null`: Remove existing feedback **Behavior:** - Feedback is stored with a timestamp (`feedbackAt`) - Submitting new feedback overwrites any existing feedback - Setting feedback to `null` removes the existing feedback - Feedback submissions are published as events for analytics - Only the message owner (visitor) can submit feedback **Event Publishing:** Feedback submissions are automatically published as events for analytics and monitoring purposes. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Send a message in a conversation Source: http://docs.siteassist.io/developer-api/messages/send-message > Send a message to an AI assistant in a conversation. Supports both streaming and non-streaming responses. Rate limiting and usage quotas are enforced per project. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Get current project Source: http://docs.siteassist.io/developer-api/projects/get-project > Return the current project identified by the provided publishable API key. Useful for initializing client SDKs with project configuration like chat widget settings. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Semantic search Source: http://docs.siteassist.io/developer-api/search/search > Perform a semantic search over the project's indexed knowledge base using vector similarity. Supports simple pagination via 'size'. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Get a Q&A Source: http://docs.siteassist.io/developer-api/qnas/get-qna > Retrieve a single Q&A entry by ID within the specified project. Returns author info when available. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # List Q&As Source: http://docs.siteassist.io/developer-api/qnas/get-qnas > Retrieve a paginated list of Q&A entries for a project. Supports full-text search using websearch_to_tsquery, along with pagination controls. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} --- # Crawler Configuration Source: http://docs.siteassist.io/user-guides/knowledge-base/web-crawlers/configuration > Advanced settings and configuration options for fine-tuning your web crawlers # Crawler Configuration While most users get excellent results with basic crawler setup, SiteAssist offers advanced configuration options for precise control over how your content is crawled and indexed. ## Accessing Configuration To configure your crawler: 1. Navigate to **Web Crawlers** in your project sidebar 2. Click on your existing crawler to open its management page 3. Switch to the **Configuration** tab {/* ![Screenshot showing the Configuration tab in crawler management](/images/docs/crawler-configuration-tab-screenshot.webp) */} ## Configuration Options ### **Start URL** **What it is:** The starting point where your crawler begins its discovery process. **How it works:** * Crawler starts at this URL and discovers linked pages * Acts as the entry point for content discovery * Must be publicly accessible **Configuration:** * Update anytime from the Configuration tab * Helpful when your site structure changes * Can point to specific sections (e.g., `/help`, `/docs`) **Examples:** ``` yourcompany.com → Crawls entire site yourcompany.com/help → Starts from help section docs.yourcompany.com → Crawls documentation subdomain ``` **Best Practices:** * Use your main domain for comprehensive coverage * Use specific sections for focused crawling * Ensure the URL contains links to important pages *** ### **Crawl Frequency** **What it is:** How often SiteAssist automatically re-crawls your website to keep the AI's knowledge up-to-date. **Why it matters:** * Keeps your AI assistant current with website changes * Ensures new content is automatically indexed * Removes outdated information #### **Frequency Options** **Every 6 Hours** * **Best for:** Frequently updated sites (news, blogs, e-commerce) * **Use case:** Sites with daily content changes * **Consideration:** Higher resource usage **Every 12 Hours** * **Best for:** Regular content updates * **Use case:** Business sites with weekly updates * **Consideration:** Balanced approach **Every Day** (Recommended) * **Best for:** Most business websites * **Use case:** Sites with occasional updates * **Consideration:** Optimal balance of freshness and efficiency **Every Week** * **Best for:** Stable websites with infrequent changes * **Use case:** Marketing sites, documentation sites * **Consideration:** Lower resource usage **Every Month** * **Best for:** Static websites or rarely updated content * **Use case:** Company info sites, established documentation * **Consideration:** Minimal resource usage *** ### **Exclusion Rules** **What it is:** A powerful system to prevent the crawler from indexing specific URLs or URL patterns. **Why use exclusion rules:** * Skip irrelevant pages (admin areas, login pages) * Avoid duplicate content * Exclude outdated or private sections * Improve crawling efficiency #### **Rule Types** **URL Starts With** * Matches URLs that begin with the specified text * Perfect for excluding entire sections ``` https://yourcompany.com/admin/ → Excludes all admin pages https://yourcompany.com/private/ → Excludes private sections https://yourcompany.com/temp/ → Excludes temporary pages ``` **URL Ends With** * Matches URLs that end with the specified text * Great for excluding file types or specific page patterns ``` .pdf → Excludes all PDF files /login → Excludes login pages .xml → Excludes XML files ``` **URL Contains** * Matches URLs that contain the specified text anywhere * Useful for excluding pages with specific keywords ``` /archive → Excludes pages with "archive" in URL ?print= → Excludes print versions /old → Excludes old content sections ``` **URL Exact Match** * Matches the exact URL only * Precise control for specific pages ``` https://yoursite.com/contact → Excludes only the contact page https://yoursite.com/privacy → Excludes only privacy policy https://yoursite.com/terms → Excludes only terms of service ``` #### **Adding Exclusion Rules** {/* ![Screenshot showing the exclusion rules interface](/images/docs/exclusion-rules-interface-screenshot.webp) */} 1. In the Configuration tab, find the **Exclusion Rules** section 2. Click **Add new Rule** 3. Choose your rule type (starts with, ends with, contains, exact match) 4. Enter the URL pattern to exclude 5. Click **Save** *** ### **Max URLs** **What it is:** A safety limit that stops crawling after reaching a specified number of pages. **Why it exists:** * **Cost Control:** Prevents unexpected crawling costs on large sites * **Resource Management:** Ensures efficient use of crawling resources * **Site Protection:** Avoids overwhelming your website server * **Quality Focus:** Encourages focusing on important content #### **Setting Max URLs** **Small Business Sites (1-100 pages):** * Set limit: 200-500 URLs * Provides buffer for growth **Medium Sites (100-1000 pages):** * Set limit: 1,500-2,000 URLs * Accommodates comprehensive crawling **Large Sites (1000+ pages):** * Set limit: 3,000-5,000+ URLs * Consider using exclusion rules to focus on important sections #### **What Happens at the Limit** When the crawler reaches your Max URLs setting: 1. Crawling stops immediately 2. Already discovered URLs are prioritized by importance 3. Status shows "Completed (Max URLs reached)" 4. You can increase the limit and re-run the crawler {/* ![Screenshot showing max URLs reached status](/images/docs/max-urls-reached-screenshot.webp) */} ## Configuration Best Practices ### **Start Small, Expand Gradually** 1. Begin with basic settings 2. Monitor initial crawl results 3. Add exclusion rules as needed 4. Adjust frequency based on content update patterns ### **Use Exclusion Rules Strategically** * Focus on excluding truly irrelevant content * Don't over-exclude - your AI might miss useful information * Test exclusions with small changes first ### **Monitor Performance** * Check crawl logs for errors * Verify important pages are being crawled * Adjust Max URLs if hitting limits frequently ### **Regular Review** * Review configuration monthly * Update exclusion rules as site structure changes * Adjust frequency based on actual content update patterns ## Advanced Configuration Examples ### **E-commerce Site Example** ``` Start URL: yourstore.com Exclusion Rules: - URL Contains: /cart - URL Contains: /checkout - URL Contains: /account - URL Starts With: /admin - URL Ends With: .jpg Max URLs: 2000 Frequency: Every day ``` ### **Documentation Site Example** ``` Start URL: docs.yourcompany.com Exclusion Rules: - URL Starts With: /api-v1 - URL Contains: /deprecated - URL Ends With: .pdf Max URLs: 1000 Frequency: Every week ``` ### **Business Website Example** ``` Start URL: yourcompany.com Exclusion Rules: - URL Exact Match: yourcompany.com/privacy - URL Starts With: /admin - URL Contains: ?print= Max URLs: 500 Frequency: Every day ``` ## Testing Your Configuration After updating your crawler configuration: 1. **Run a Test Crawl** to see immediate results 2. **Check the Logs** in the Overview tab for any issues 3. **Review Indexed Content** to ensure quality 4. **Test Your AI Assistant** with questions about your content ## Troubleshooting Configuration Issues **Crawler Missing Important Pages:** * Check if exclusion rules are too broad * Verify start URL includes links to important sections * Consider increasing Max URLs limit **Crawler Indexing Irrelevant Content:** * Add more specific exclusion rules * Use "URL Contains" rules for broad exclusions * Review and refine existing rules **Slow Crawling Performance:** * Reduce crawl frequency if not needed * Add exclusion rules for large file types * Lower Max URLs temporarily ## Need Help? Configuration can be complex for unique website structures. Our team is here to help: * **Email:** [support@siteassist.io](mailto:support@siteassist.io) * **We can help with:** Custom exclusion rules, optimal frequency settings, troubleshooting crawl issues > **Pro Tip:** Start with conservative settings and gradually optimize. It's easier to expand crawling than to clean up over-crawled content! --- # Creating Crawlers Source: http://docs.siteassist.io/user-guides/knowledge-base/web-crawlers/creating-crawlers > Step-by-step guide to setting up web crawlers for your website # Creating Web Crawlers Setting up a web crawler is the first step to building your AI assistant's knowledge base. This guide walks you through creating and configuring your first crawler. ## Before You Start **What You'll Need:** * Your website's main URL (e.g., `yourcompany.com` - no need for https\://) * Access to your SiteAssist project * Time for initial crawl (1 minute per \~300 pages) **Permissions Required:** * Your website must be publicly accessible * No password protection on pages you want crawled * Standard robots.txt compliance (SiteAssist respects crawling rules) ## Step-by-Step Guide ### 1. Access Web Crawlers Navigate to your project and click on **Web Crawlers** in the sidebar. {/* ![Screenshot showing the project sidebar with Web Crawlers highlighted](/images/docs/sidebar-web-crawlers-screenshot.webp) */} ### 2. Create New Crawler Click the **Add Crawler** button to open the crawler creation modal. {/* ![Screenshot showing the Web Crawlers page with Add Crawler button](/images/docs/add-crawler-button-screenshot.webp) */} ### 3. Basic Configuration Fill in the essential crawler settings: Screenshot showing the Create Crawler modal with all fields #### **Name** Give your crawler a descriptive name for easy identification. **Good examples:** * "Main Company Website" * "Help Documentation" * "Product Catalog" * "Marketing Site" **Avoid:** * Generic names like "Crawler 1" * Special characters or symbols #### **Start URL** Enter your website's main URL where crawling should begin. **Format Requirements:** * The input field has `https://` prefix automatically added * Just enter your domain without the protocol * Can be a specific section starting point **Examples:** * `yourcompany.com` * `docs.yourcompany.com` * `yourcompany.com/products` > **Smart Discovery**: The crawler automatically checks for sitemaps at `/sitemap.xml` and `/sitemap-index.xml` to discover pages more efficiently. #### **Preset Selection** Choose the preset that best matches your website type: **Website** * Best for: Business websites, marketing sites, general content * Optimized for: Customer support, general inquiries * *Recommended for most users* **Documentation** * Best for: Help centers, technical docs, API documentation * Optimized for: Detailed explanations, technical support * Maintains content hierarchy and structure **Blog** * Best for: News sites, blogs, content marketing sites * Optimized for: Article content, publication information * Handles date-based content organization **E-commerce** (Coming Soon) * Best for: Online stores, product catalogs * Will optimize for: Product information, pricing, descriptions > **Not sure which preset to choose?** Start with "Website" - it works well for most business sites and you can always create additional crawlers with different presets later. ### 4. Start Crawling Once you've configured the basic settings: 1. Review your configuration 2. Click **Create & Start Indexing** 3. The crawler will immediately start working {/* ![Screenshot showing crawler creation confirmation and initial status](/images/docs/crawler-created-confirmation-screenshot.webp) */} ## What Happens Next ### **Immediate Actions** * Crawler status changes to "Crawling" * Initial page discovery begins * Progress indicators show crawling activity * Crawler logs starts showing live logs. ### **During Crawling** (1-5+ minutes typically) * Pages are discovered and queued * Content is extracted and processed * Progress logs show real-time activity * You can monitor status in the crawler dashboard **Processing Times:** * \~300 pages: \~1 minute * \~600 pages: \~5 minutes * Larger sites: Time scales proportionally ### **After Completion** * Status changes to "Completed" * Indexed content count is displayed * Your AI assistant can now use this knowledge * Automatic scheduling begins (if configured) ## Managing Your Crawler Once created, each crawler has a dedicated page with three tabs for complete management: ### **Overview Tab** * Real-time crawling status and progress * Total pages discovered and indexed * Crawling logs and activity history * Performance metrics and statistics Live crawler logs when crawling ### **Configuration Tab** * Modify advanced crawler settings * Update start URL if needed * Adjust URL exclusion rules * Change crawling frequency and scheduling ### **Settings Tab** * View crawler ID and technical details * Access crawler management options * Delete crawler (permanent action) ## Monitoring Your New Crawler While your crawler runs, you can: **View Progress** * See pages being processed in real-time * Monitor crawling speed and efficiency * Check for any errors or issues in the logs Live crawler logs when crawling **Test Integration** * Try asking your AI assistant questions * Verify responses use your website content * Check accuracy and relevance ## Common First-Time Issues ### **Crawler Stuck or Slow** * **Cause**: Large website or slow server response * **Solution**: Be patient; crawling can take time for large sites * **When to worry**: If no progress after 30 minutes ### **Low Page Count** * **Cause**: Limited internal linking or restricted access * **Solution**: Check your website's internal link structure * **Alternative**: Use sitemap URL as start URL ### **Missing Important Pages** * **Cause**: Pages not linked from main navigation * **Solution**: Check [advanced configuration options](/docs/knowledge-base/web-crawlers/configuration) ### **Permission Errors** * **Cause**: Password-protected or restricted content * **Solution**: Ensure pages are publicly accessible ## Next Steps Once your crawler is running successfully: 1. **[Configure advanced settings](/docs/knowledge-base/web-crawlers/configuration)** for more control 2. **Test your AI assistant** with questions about your website content 3. **Consider additional crawlers** for different sections or content types ## Need Help? **Having trouble with crawler setup?** * Check our [troubleshooting guide](/docs/knowledge-base/web-crawlers/troubleshooting) * Email us: [support@siteassist.io](mailto:support@siteassist.io) * We can help analyze your website structure and recommend optimal settings **Want advanced features?** * See our [crawler configuration guide](/docs/knowledge-base/web-crawlers/configuration) * Learn about URL exclusion rules and custom scheduling --- # Web Crawlers Overview Source: http://docs.siteassist.io/user-guides/knowledge-base/web-crawlers/overview > Learn how SiteAssist crawlers work and why they're essential for your AI assistant ## What are Web Crawlers? Web crawlers are the foundation of your AI assistant's knowledge. Think of them as intelligent robots that systematically explore your website, reading and understanding your content so your AI can provide accurate, helpful responses to visitors. ## How Crawlers Work
Diagram showing crawler process flow Diagram showing crawler process flow
SiteAssist crawlers follow a systematic process: 1. **Sitemap Discovery**: First checks for sitemaps at `/sitemap.xml` and `/sitemap-index.xml` 2. **URL Discovery**: Starting from your provided URL, discovers all linked pages 3. **Content Extraction**: Each page's text content is extracted and cleaned 4. **Processing**: Content is processed and structured for optimal AI understanding 5. **Indexing**: Information is stored in your knowledge base for instant retrieval 6. **Updates**: Regular re-crawling keeps your AI's knowledge current ## Crawling Performance SiteAssist crawlers are optimized for speed and efficiency: * **\~300 pages**: Approximately 1 minute * **\~600 pages**: Approximately 5 minutes * **Larger sites**: Processing time scales proportionally The crawler intelligently prioritizes sitemaps when available for faster, more comprehensive discovery. ## Crawler Types & Presets Different websites have different structures and content types. SiteAssist offers optimized presets: ### **Website (General)** Perfect for most business websites, marketing sites, and general content. * Focuses on main content areas * Filters out navigation and promotional content * Optimized for customer support scenarios ### **Documentation** Specialized for technical documentation, help centers, and knowledge bases. * Prioritizes structured content and hierarchies * Extracts code examples and technical details * Maintains logical content relationships ### **Blog** Optimized for news sites, blogs, and article-heavy content. * Focuses on article content and metadata * Extracts publication dates and author information * Handles content archives effectively ### **E-commerce** (Coming Soon) Designed for online stores and product catalogs. * Will extract product information and descriptions * Handle dynamic pricing and inventory content * Support product categorization ## Benefits of Smart Crawling ### **Comprehensive Coverage** * Automatically discovers all publicly accessible pages * No manual URL management required * Finds content you might have forgotten about ### **Always Up-to-Date** * Scheduled re-crawling keeps information current * Detects new pages and content changes * Removes outdated information automatically ### **Intelligent Processing** * Filters out irrelevant content (ads, navigation, footers) * Focuses on valuable information for customer support * Optimizes content for AI understanding ### **Scalable Solution** * Handles websites of any size * Efficient crawling doesn't impact site performance * Works with all major CMS platforms ## What Gets Crawled **Included Content:** * Main page content and articles * Product descriptions and documentation * FAQ sections and help content * About pages and company information * Blog posts and news articles **Filtered Out:** * Navigation menus and headers * Advertisements and promotional banners * Cookie notices and legal disclaimers * Duplicate or boilerplate content * Private or password-protected areas ## Getting Started Ready to set up your first crawler? The process is simple: 1. **[Create a new crawler](/docs/knowledge-base/web-crawlers/creating-crawlers)** with your website URL 2. **[Configure settings](/docs/knowledge-base/web-crawlers/configuration)** for your specific needs 3. **[Monitor the crawling process](/docs/knowledge-base/web-crawlers/monitoring-crawls)** and results 4. **Test your AI assistant** with the newly indexed content > **Quick Start Tip**: Most users can get excellent results with just a website URL and the "Website" preset. Advanced configuration is available when you need more control. ## Need Help? Crawling not working as expected? Check our **[troubleshooting guide](/docs/knowledge-base/web-crawlers/troubleshooting)** or contact our support team at [support@siteassist.io](mailto:support@siteassist.io). --- # Troubleshooting Crawlers Source: http://docs.siteassist.io/user-guides/knowledge-base/web-crawlers/troubleshooting > Solutions to common web crawler issues and problems # Troubleshooting Web Crawlers Having trouble with your web crawler? This guide covers the most common issues and their solutions to get your crawler working smoothly. ## Common Setup Issues ### **🚫 Invalid URL Format Error** **Problem:** Users enter URLs with `https://` prefix, causing validation errors. **Why this happens:** * The Start URL field automatically adds `https://` prefix * Adding `https://` manually creates a double prefix (`https://https://yoursite.com`) * System rejects malformed URLs **Solution:** ``` ❌ Wrong: https://yourcompany.com ✅ Correct: yourcompany.com ❌ Wrong: http://yourcompany.com ✅ Correct: yourcompany.com ❌ Wrong: https://docs.yourcompany.com/help ✅ Correct: docs.yourcompany.com/help ``` **Quick Fix:** 1. Remove `https://` or `http://` from your URL 2. Enter only the domain and path 3. The system will automatically add the secure protocol *** ### **🔄 Single Page Application (SPA) Crawling Issues** **Problem:** Crawler finds very few pages on React, Vue, or Angular websites. **Why this happens:** * SPAs render content with JavaScript after page load * Crawlers see the initial HTML without JavaScript-rendered content * Most navigation happens client-side, not through traditional links **Symptoms:** * Only 1-2 pages discovered when you expect many more * Missing content from dynamic sections * Crawler stops quickly with low page count **Solutions:** **Option 1: Use Sitemap (Recommended)** * Ensure your SPA generates a sitemap.xml * Include all routes in your sitemap * SiteAssist will use the sitemap for comprehensive crawling **Option 2: Server-Side Rendering (SSR)** * Implement Next.js, Nuxt.js, or similar SSR framework * Ensures content is available when crawler visits * Best long-term solution for SEO and crawling **Option 3: Prerendering** * Use tools like Prerender.io or Netlify's prerendering * Generates static HTML for crawler visits * Good compromise for existing SPAs **Option 4: Manual URL Management** * Use exclusion rules strategically * Focus crawler on content-heavy sections * Consider multiple targeted crawlers *** ## Crawling Performance Issues ### **⏱️ Crawler Running Too Long** **Problem:** Crawler seems stuck or runs much longer than expected. **Possible Causes & Solutions:** **Large Website** * **Cause:** Site has thousands of pages * **Solution:** Set appropriate Max URLs limit (start with 1,000-2,000) * **Prevention:** Use exclusion rules to focus on important content **Slow Server Response** * **Cause:** Your website responds slowly to requests * **Solution:** Check your website's performance and hosting * **Workaround:** Increase timeout patience, crawl during off-peak hours **Infinite URL Loops** * **Cause:** Dynamic URLs creating endless variations * **Solution:** Add exclusion rules for URL parameters ``` URL Contains: ?page= URL Contains: ?filter= URL Contains: ?sort= ``` **Deep Link Structure** * **Cause:** Very deep navigation hierarchies * **Solution:** Start crawling from specific sections rather than root *** ### **📊 Very Low Page Discovery** **Problem:** Crawler finds far fewer pages than expected. **Common Causes & Fixes:** **Poor Internal Linking** * **Cause:** Pages aren't linked from main navigation * **Solution:** Improve site navigation or use sitemap crawling * **Check:** Ensure important pages are linked from your homepage **Broken Internal Links** * **Cause:** Links pointing to non-existent pages * **Solution:** Fix broken links in your website navigation * **Tool:** Use website crawling tools to identify broken links **JavaScript-Heavy Navigation** * **Cause:** Navigation menu built entirely with JavaScript * **Solution:** Add HTML fallback navigation or use sitemap * **Best Practice:** Ensure critical pages have HTML links **Robots.txt Restrictions** * **Cause:** Your robots.txt file blocks crawling * **Solution:** Check and adjust robots.txt permissions * **Test:** Use Google Search Console to test robot access *** ## Content Quality Issues ### **🗑️ Crawler Indexing Irrelevant Content** **Problem:** AI assistant knows about admin pages, shopping carts, or other irrelevant content. **Solution Strategy:** **Add Strategic Exclusion Rules** ``` Common exclusions for business sites: - URL Starts With: https://yourcompany.com/admin - URL Starts With: https://yourcompany.com/wp-admin - URL Contains: /cart - URL Contains: /checkout - URL Contains: /login - URL Contains: /register - URL Ends With: .pdf - URL Contains: ?print= ``` **E-commerce Specific Exclusions** ``` - URL Contains: /cart - URL Contains: /checkout - URL Contains: /account - URL Contains: /wishlist - URL Starts With: https://yourcompany.com/customer - URL Contains: ?variant= ``` **Review and Refine** 1. Run initial crawl to see what gets indexed 2. Identify unwanted content in the logs 3. Add specific exclusion rules 4. Re-run crawler to test improvements *** ### **❌ Missing Important Pages** **Problem:** Key pages aren't being crawled and indexed. **Diagnostic Steps:** **Check Start URL** * Ensure start URL links to or navigates to missing pages * Try starting from a section closer to the missing content **Review Exclusion Rules** * Check if exclusion rules are too broad * Temporarily disable rules to test * Refine overly aggressive exclusions **Verify Page Accessibility** * Ensure pages are publicly accessible (no login required) * Check that pages return 200 HTTP status * Verify pages aren't blocked by robots.txt **Check Max URLs Limit** * Increase limit if crawler stops before reaching important pages * Monitor crawl progress to see where it stops *** ## Technical Issues ### **🚨 Crawler Fails to Start** **Problem:** Crawler won't begin crawling at all. **Troubleshooting Checklist:** **URL Accessibility** ```bash Test your URL: 1. Open start URL in browser 2. Verify page loads completely 3. Check for password protection 4. Ensure SSL certificate is valid ``` **Domain Configuration** * Verify domain is spelled correctly * Check for typos in subdomain names * Ensure DNS is properly configured **Server Issues** * Check if your website is currently down * Verify hosting provider isn't blocking crawlers * Test during different times if server is overloaded *** ### **⚠️ Partial Crawl Results** **Problem:** Crawler stops unexpectedly with partial results. **Common Causes:** **Hit Max URLs Limit** * **Check:** Crawler status shows "Max URLs reached" * **Solution:** Increase Max URLs limit or add exclusion rules **Server Rate Limiting** * **Cause:** Your server blocks rapid requests * **Solution:** Contact support for crawler rate adjustment * **Prevention:** Ensure hosting can handle crawler traffic **Website Structure Changes** * **Cause:** Site navigation changed during crawl * **Solution:** Re-run crawler after changes settle * **Prevention:** Schedule crawls during maintenance windows *** ## Website-Specific Solutions ### **WordPress Sites** **Common Issues:** * WP admin pages getting crawled * Plugin pages creating noise * Duplicate content from categories/tags **Recommended Exclusions:** ``` URL Starts With: https://yourcompany.com/wp-admin URL Starts With: https://yourcompany.com/wp-login URL Contains: /author/ URL Contains: /tag/ URL Contains: /date/ URL Contains: ?p= ``` ### **Shopify Stores** **Common Issues:** * Product variants creating duplicate URLs * Customer account pages * Checkout process pages **Recommended Exclusions:** ``` URL Contains: /account URL Contains: /cart URL Contains: /checkout URL Contains: ?variant= URL Starts With: https://yourcompany.com/admin ``` ### **Documentation Sites** **Common Issues:** * Multiple versions creating confusion * API references in wrong format * Download files being indexed **Recommended Exclusions:** ``` URL Contains: /v1/ URL Contains: /deprecated URL Ends With: .pdf URL Ends With: .zip URL Contains: /download ``` ## Getting Help ### **When to Contact Support** Reach out to us at [support@siteassist.io](mailto:support@siteassist.io) if: * Crawler consistently fails after trying solutions above * Your website has unique architecture needs * You need help setting up complex exclusion rules * Crawling works but AI responses are poor quality * You're seeing unexpected behavior not covered here ### **Information to Include** When contacting support, please provide: 1. **Your website URL** 2. **Crawler configuration details** 3. **Description of the problem** 4. **Screenshots of crawler status/logs** 5. **Expected vs. actual results** ### **Quick Diagnostic Steps** Before contacting support, try: 1. **Test in Private Browser**: Rule out caching issues 2. **Check Crawler Logs**: Look for specific error messages 3. **Try Different Start URL**: Test with a simpler starting point 4. **Disable All Exclusions**: See if rules are causing issues 5. **Increase Max URLs**: Rule out limit-related problems ## Prevention Tips ### **Set Yourself Up for Success** **Website Preparation:** * Ensure clear navigation structure * Generate and maintain sitemap.xml * Use descriptive, crawlable URLs * Minimize JavaScript-dependent navigation **Crawler Configuration:** * Start with conservative settings * Test with small Max URLs first * Add exclusions gradually * Monitor results after changes **Regular Maintenance:** * Review crawler performance monthly * Update exclusions as site changes * Adjust frequency based on content updates * Test AI responses periodically > **Remember:** Most crawling issues have simple solutions. Start with the basics (URL format, exclusions, limits) before diving into complex configurations.