Skip to content

Forum in maintenance, we will back soon 🙂

AI Tools With WordP...
 
Notifications
Clear all

AI Tools With WordPress doesn't work for me

35 Posts
9 Users
12 Reactions
950 Views
(@granny)
Posts: 3
Active Member
Topic starter
 

Hey Hasan and team,

I followed along with your video today and tried pasting the code onto a new page and it shows the code, not the tool working. What did I do wrong? how can I correct this?

 
Posted : 03/21/2024 10:16 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@granny that was a great video. You need to share your code. Use the icon (<>) for code sharing above. You might be interested in Hasan's courses as well. He has great style and teaching comes natural to him. Plus you get valuable resources that you don't get otherwise.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/22/2024 12:40 am
(@granny)
Posts: 3
Active Member
Topic starter
 
// Your Inputs
function setApiKey() {
    return "AIzaSyBoHhJHSkGVYsAbKRekL4MYBIaIG7...";
}

function setPrompt($input) {
    return "Generate 5 catchy blog titles for a blog post about " . $input;
}


// Define your "model" as an associative array
function createTitlesModel($titles) {
    return ["titles" => $titles];
}

// Helper JSON Functions
function modelToJson($modelInstance) {
    return json_encode($modelInstance);
}

function extractJson($textResponse) {
    $pattern = '/\{[^{}]*\}/';

    preg_match_all($pattern, $textResponse, $matches);
    $jsonObjects = [];

    foreach ($matches[0] as $jsonStr) {
        try {
            $jsonObj = json_decode($jsonStr, true, 512, JSON_THROW_ON_ERROR);
            array_push($jsonObjects, $jsonObj);
        } catch (JsonException $e) {
            // Extend the search for nested structures
            $extendedJsonStr = extendSearch($textResponse, $jsonStr);
            try {
                $jsonObj = json_decode($extendedJsonStr, true, 512, JSON_THROW_ON_ERROR);
                array_push($jsonObjects, $jsonObj);
            } catch (JsonException $e) {
                // Handle cases where the extraction is not valid JSON
                continue;
            }
        }
    }

    return !empty($jsonObjects) ? $jsonObjects : null;
}

function extendSearch($text, $jsonStr) {
    // Extend the search to try to capture nested structures
    $start = strpos($text, $jsonStr);
    $end = $start + strlen($jsonStr);
    $nestCount = 0;

    for ($i = $start; $i < strlen($text); $i++) {
        if ($text[$i] === '{') {
            $nestCount++;
        } elseif ($text[$i] === '}') {
            $nestCount--;
            if ($nestCount === 0) {
                return substr($text, $start, $i - $start + 1);
            }
        }
    }

    return substr($text, $start, $end - $start);
}

function jsonToModel($modelClass, $jsonData) {
    try {
        return $modelClass($jsonData);
    } catch (Exception $e) {
        echo "Validation error: " . $e->getMessage();
        return null;
    }
}

function validateJsonWithModel($modelClass, $jsonData) {
    $validatedData = [];
    $validationErrors = [];

    if (is_array($jsonData)) {
        foreach ($jsonData as $item) {
            try {
                $modelInstance = $modelClass($item);
                array_push($validatedData, $modelInstance);
            } catch (Exception $e) {
                array_push($validationErrors, ["error" => $e->getMessage(), "data" => $item]);
            }
        }
    } elseif (is_assoc($jsonData)) {
        try {
            $modelInstance = $modelClass($jsonData);
            array_push($validatedData, $modelInstance);
        } catch (Exception $e) {
            array_push($validationErrors, ["error" => $e->getMessage(), "data" => $jsonData]);
        }
    } else {
        throw new ValueError("Invalid JSON data type. Expected associative array or array.");
    }

    return [$validatedData, $validationErrors];
}

function is_assoc(array $arr) {
    if (array() === $arr) return false;
    return array_keys($arr) !== range(0, count($arr) - 1);
}

function generate_response_with_gemini($prompt) {
    
    $api_key = setApiKey();
    $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . $api_key ;


    // Headers for the Gemini API
    $headers = [
        'Content-Type' => 'application/json'
    ];

    // Body for the Gemini API
    $body = [
        'contents' => [
            [
                'parts' => [
                    ['text' => $prompt]
                ]
            ]
        ]
    ];

    // Args for the WordPress HTTP API
    $args = [
        'method' => 'POST',
        'headers' => $headers,
        'body' => json_encode($body),
        'timeout' => 120
    ];

    // Send the request
    $response = wp_remote_request($api_url, $args);
    
    // Extract the body from the response
    $responseBody = wp_remote_retrieve_body($response);

    // Decode the JSON response body
    $decoded = json_decode($responseBody, true);
    
    // Extract the text
    if (isset($decoded['candidates'][0]['content']['parts'][0]['text'])) {
        $extractedText = $decoded['candidates'][0]['content']['parts'][0]['text'];
        return $extractedText;
    } else {
        return 'Text not found in response';
    }


}

function custom_tool_run() {
    
    
         // Add CORS headers
         header('Access-Control-Allow-Origin: *'); // Allows all origins
         header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); // Specifies the allowed methods
         header('Access-Control-Allow-Headers: Content-Type, Authorization'); // Specifies the allowed headers 
    
    
        // Variables
        $input = $_POST['input'];

        $basePrompt = setPrompt($input);
    
        
        // Creating an instance of your model
        $titlesModel = createTitlesModel(['title1', 'title2']);
    
        // Convert model instance to JSON
        $jsonModel = modelToJson($titlesModel);
    
        
        // Create optimized prompt
        $optimizedPrompt = $basePrompt . ". Please provide a response in a structured JSON format that matches the following model: " . $jsonModel;

    
        // Generate content using the modified prompt
        $gemeniResponse = generate_response_with_gemini($optimizedPrompt);
    
        // Extract and validate the JSON from the response
        $jsonObjects = extractJson($gemeniResponse);
    
        wp_send_json_success($jsonObjects);

        // Always die in functions echoing AJAX content
        wp_die();
}

add_action('wp_ajax_custom_tool_run', 'custom_tool_run');
add_action('wp_ajax_nopriv_custom_tool_run', 'custom_tool_run');
 
Posted : 03/22/2024 2:51 am
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@granny did you install and activate the recommended plugin? The code was supposed to go into the code snippet.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/22/2024 3:09 am
(@google-osamaraja)
Posts: 2
New Member
 

@ssadvisor i did post this code in the code snippet plug-in, but it is still not working. It shows a error, which says (Oops! Something went wrong. Please try again.)

 

 
Posted : 03/22/2024 5:15 am
(@google-osamaraja)
Posts: 2
New Member
 

@granny I found the solution of this error that we made in the HTML file. and it fixed my error, and I hope it fixes yours too. on html file, go to 

fetch('http://wordpress-test.local/wp-admin/admin-ajax.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
 
There, you just need to replace this (wordpress-test) to your local-WordPress site name (in my case it was osamaai.local)
 
i hope this will fix your error too 🙂 
 
 
 
 
Posted : 03/22/2024 5:45 am
(@granny)
Posts: 3
Active Member
Topic starter
 

That's fantastic! Thank you, I'll try it. I'm moving today so I won't have internet until tomorrow.

 
Posted : 03/22/2024 4:05 pm
(@mohanv44)
Posts: 4
New Member
 

Even after replacing "wordpress-test" with my website address "altty.com", still I am getting the same error "Oops! Something went wrong. Please try again."

 
Posted : 03/22/2024 5:25 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@mohanv44 see lines 92, 113, 119, 141 and 146 of the file posted at  https://learnwithhasan.com/custom-code/ai-tool-on-wordpress-ui/  where you need to change the URL

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/22/2024 10:02 pm
(@mohanv44)
Posts: 4
New Member
 

@ssadvisor Thanks for your reply.
All the URLs related to wordpress-test are replaced with my website address, but still same issue.

 
Posted : 03/23/2024 5:20 am
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@mohanv44 share your modified code snippet using the code share icon (<>) above and share what your URL is.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/23/2024 1:21 pm
(@mohanv44)
Posts: 4
New Member
 
<style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f4f4;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }

        .container {
            max-width: 600px;
            margin: auto;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .input-group {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        input[type="text"] {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
        }

        button {
            background: #007bff;
            color: #fff;
            border: 0;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background: #0056b3;
        }

        .result-item {
            background-color: #f2f2f2;
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .copy-button {
            background: #007bff;
            color: #fff;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
        }

        .copy-button:hover {
            background: #0056b3;
        }

        .image-container {
            margin-bottom: 20px;
        }

        @media screen and (max-width: 768px) {
            body, .container, .input-group {
                padding: 10px;
            }
        }
    .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="input-group">
            <input type="text" id="inputInput" placeholder="Enter a Chat input (e.g., Birthday, Congratulations)">
            <button id="generateButton">Generate Chats</button>
        </div>
        <div id="imageContainer" class="image-container">
            <img src="https://altty.com/wp-content/uploads/2022/06/Altty-Round-Favicon.png" alt="Getting Started" style="max-width: 30%;">
        </div>

        <ul id="titleList"></ul>

        
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const generateButton = document.getElementById('generateButton');
            const titleList = document.getElementById('titleList');
            const inputInput = document.getElementById('inputInput');
            const imageContainer = document.getElementById('imageContainer');

            generateButton.addEventListener('click', function() {
                const input = inputInput.value;
                if (!input) {
                    alert('Please enter a input.');
                    return;
                }

                imageContainer.innerHTML = '<img src="https://altty.com/wp-content/uploads/2022/07/Preloader-Circle.gif" alt="Loading" style="max-width: 20%;">';

        // Clear existing titles and show the loading GIF
                titleList.innerHTML = '';
                imageContainer.classList.remove('hidden'); 

                fetch('https://altty.com/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: 'action=custom_tool_run&input=' + encodeURIComponent(input)
                })
                .then(response => response.json())
                .then(jsonResponse => {
                    titleList.innerHTML = '';
                    if (jsonResponse.success) {
                        const titles = jsonResponse.data[0].titles;

                        titles.forEach(title => {
                            let listItem = document.createElement('li');
                            listItem.className = 'result-item';
                            listItem.innerHTML = `<span>${title}</span> <button class="copy-button" onclick="copyToClipboard('${title}')">Copy</button>`;
                            titleList.appendChild(listItem);
                        });
                        imageContainer.classList.add('hidden'); // Hide the image container
                    } else {
                        console.error('Failed to fetch titles');
            imageContainer.innerHTML = '<img src="https://altty.com/wp-content/uploads/2022/11/8.Giving-Back-To-Society.pngs" alt="Error" style="max-width: 100%;">' +
                                               '<p>Oops! Something went wrong. Please try again.</p>';                   }
                })
                .catch(error => {
                    console.error('Error:', error);
                    imageContainer.innerHTML = '<img src="https://altty.com/wp-content/uploads/2019/08/gift.svg" alt="Error" style="max-width: 100%;">' +
                                               '<p>Oops! Something went wrong. Please try again.</p>'; 

                });
            });

            window.copyToClipboard = function(text) {
            var textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.top = "0";
            textArea.style.left = "0";
            textArea.style.position = "fixed";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                var successful = document.execCommand('copy');
                var msg = successful ? 'successful' : 'unsuccessful';
                alert('Copying text was ' + msg);
            } catch (err) {
                alert('Unable to copy text');
                console.error('Unable to copy', err);
            }

            document.body.removeChild(textArea);
        };

        });
    </script>
 
Posted : 03/23/2024 2:23 pm
(@ishan45)
Posts: 2
New Member
 

Its not working!

 
Posted : 03/23/2024 7:02 pm
(@google-technicalsir)
Posts: 9
Active Member
 

I am also facing the same problem and don't know where to change the links

 
Posted : 03/24/2024 6:27 am
(@husein)
Posts: 550
Member Moderator
 

@google-technicalsir @ishan45 Did you try changing the URL to your own URL in lines 92, 113, 119, 141 and 146?

 
Posted : 03/24/2024 9:03 am
(@google-technicalsir)
Posts: 9
Active Member
 

@husein I know that I need to replace the url but from which url I should replace these urls? Like there would be different url based on my domain but can you put an example on which part of url is actually the problem

 
Posted : 03/24/2024 9:37 am
(@bappadigital)
Posts: 5
Active Member
 

I changed the url in lines 92,113,119,141, and 146 but the Error unsolved "Oops! Something went wrong. Please try again."

 
Posted : 03/24/2024 10:13 am
(@bappadigital)
Posts: 5
Active Member
 

@mohanv44 we are facing the same Error, please let me know if you fix it. Please!

 
Posted : 03/24/2024 10:32 am
(@husein)
Posts: 550
Member Moderator
 

@google-technicalsir you should replace the URLs with your own, for example, let's say your website is abc.com then, the URL will be:

https://abc.com/wp-admin/admin-ajax.php

 
Posted : 03/24/2024 10:49 am
(@husein)
Posts: 550
Member Moderator
 

@bappadigital Did you generate your own Gemini API Key? I just tried implementing it again using a local wp, i just had to generate a gemini key and change the URLs and it worked.

 
Posted : 03/24/2024 10:50 am
Page 1 / 2
Share:
[the_ad_group id="312"]