Topview Logo
  • Create viral videos with
    GPT-4o + Ads library
    Use GPT-4o to edit video empowered by Youtube & Tiktok & Facebook ads library. Turns your links or media assets into viral videos in one click.
    Try it free
    gpt video

    Injecting watsonx api generated js code to plot curves | Code Explanation

    blog thumbnail

    Introduction

    In this article, I'll be providing a detailed explanation of a recent change I added to a social media app, which leverages AI to plot graphs using JavaScript. This process involves generating JavaScript code and injecting it into HTML to render the graph.

    To integrate the graph-plotting functionality, I re-used an existing API endpoint initially designed for checking grammar. The limited space in the app's post area necessitated this approach. Therefore, I included logic to distinguish between grammar checks and graph plotting based on the input content.

    Here's a step-by-step breakdown of how I achieved this:

    1. Extending Grammar API:

      • I modified the API endpoint to recognize a prefix in the post content. If the input starts with "graph: " or "graph2: ", it understands that the request is for plotting a graph rather than checking grammar.
      • For instance, the prompt sent to the API would be: "Write a JavaScript code to plot this curve in the canvas: [User Input]. Provide just the code in the response with no explanation or additional info."
    2. API Response Processing:

      • On the backend, the AI model (watsonx API) generates the JavaScript code based on the user's input. The raw response needs some processing, which occurs on the frontend.
      • In the frontend's home component, it checks if the caption has a "graph: " prefix. If it does, it processes the response string by splitting it based on specific characters. The response string is then parsed to identify and extract the actual JavaScript code which starts with the "JavaScript" keyword.
    3. Injecting JavaScript Code:

      • A canvas element is added to the DOM, but it only becomes visible after setting the generated JS code as its non-null value.
      • To ensure the canvas is properly injected, I wrapped the code execution inside a setTimeout. This delay allows the DOM to fully load the canvas element before the JavaScript code runs.
    4. Error Handling and Debugging:

      • During testing, an issue was found where the code was not being executed due to the JavaScript token being in the first split itself.
      • To resolve this, I introduced a check to ensure the length of the split string is more than a specified number of tokens before proceeding.
      • After implementing this fix, the graph plotting functioned correctly, demonstrating both simple and more complex graph equations.

    Below is a sample walk-through of the implementation process:

    Example of Implementing and Testing Graph Plotting:

    Initial Setup

    • When a post starts with "graph: " or "graph2: ", it triggers the graph-plotting logic.
    • For example, "graph: y = sin(x)".

    Frontend Logic

    if (caption.startsWith('graph:') || caption.startsWith('graph2:')) (
        const rawResponse = callAPIWithCaption(caption);
        const jsCode = processRawResponse(rawResponse);
        setTimeout(() => injectJavaScriptCode(jsCode), 1000);
    )
    
    • Here, callAPIWithCaption sends the caption to the watsonx API and retrieves the raw response.
    • processRawResponse converts the raw response into executable JavaScript code.

    Error Fix

    function processRawResponse(response) (
        const splitResponse = response.split('some_character');
        const jsCodeSegment = splitResponse.find(segment => segment.startsWith('JavaScript') && segment.length > 5);
        return jsCodeSegment.replace('JavaScript', '');
    )
    
    • Ensures that the segment of the response that starts with "JavaScript" and has a length greater than 5 is processed.

    Final Output

    function injectJavaScriptCode(jsCode) (
        const canvas = document.getElementById('canvas_id');
        setTimeout(() => {
            new Function(jsCode)();
        ), 1000);
    }
    
    • Ensures that the canvas is available in the DOM before executing the JavaScript code.

    This brings us to the end of the explanation. The final code fixes are committed to the project repository.

    Keywords

    • AI-generated JavaScript
    • Graph plotting
    • API response processing
    • Canvas element
    • DOM manipulation
    • Timeout wrapper

    FAQ

    1. What triggered the need to reuse the grammar API for graph plotting?

    • The limited space in the post area didn't allow for an additional button. Hence, we reused the existing grammar API.

    2. How do you identify that the input request is for graph plotting?

    • The input request is identified for graph plotting if the post content starts with "graph:" or "graph2:".

    3. How do you handle the API response on the frontend?

    • The API response is processed by splitting the string and identifying the segment starting with "JavaScript". Additional checks ensure the segment has sufficient length.

    4. What issue was faced during the initial testing?

    • The JavaScript token appeared in the first split itself, resulting in no valid code. This was fixed by introducing a length check.

    5. What changes were made to fix the error in code processing?

    • A condition was added to check if the segment length is greater than a certain number of tokens, ensuring valid code.

    6. Why was a setTimeout required in the code?

    • The setTimeout ensures the canvas element is fully loaded in the DOM before executing the JavaScript code.

    One more thing

    In addition to the incredible tools mentioned above, for those looking to elevate their video creation process even further, Topview.ai stands out as a revolutionary online AI video editor.

    TopView.ai provides two powerful tools to help you make ads video in one click.

    Materials to Video: you can upload your raw footage or pictures, TopView.ai will edit video based on media you uploaded for you.

    Link to Video: you can paste an E-Commerce product link, TopView.ai will generate a video for you.

    You may also like