Skip to content

Forum in maintenance, we will back soon 🙂

create AI tool in W...
 
Notifications
Clear all

create AI tool in WP using Gemini API

34 Posts
4 Users
10 Reactions
70 Views
(@sonu-choudhary)
Posts: 26
Eminent Member Customer
Topic starter
 

how to create AI tool in WP using Gemini API

 
Posted : 01/31/2024 1:43 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@sonu-choudhary have you watched any of the training? Then you use the Gemini API documentation and replace the training documents with the API you want to use. If you have a project started on GitHub you can share a publicly accessible link here and we can help you.

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

 
Posted : 01/31/2024 2:10 pm
(@husein)
Posts: 550
Member Moderator
 

@sonu-choudhary It looks like you finished the prompt engineering course from your badge. Hasan mentioned how you can do it using OpenAI's API and mentioned how you can implement other LLM's APIs in your code. So all you have to do is just replace the code the calls OpenAI's API to call Gemini's API

 

 
Posted : 01/31/2024 3:05 pm
(@sonu-choudhary)
Posts: 26
Eminent Member Customer
Topic starter
 

@husein yes I have try this but its not working can you give me code

 
Posted : 02/01/2024 8:06 am
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@sonu-choudhary no, but share what you have and we can help you debug it. Preferably use a public link to a GitHub repository or use the code icon (<>) to paste your code or even share a screenshot of your code.

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

 
Posted : 02/01/2024 2:23 pm
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

@sonu-choudhary Hi friend, can you please show us what did you try?

 
Posted : 02/01/2024 2:51 pm
(@sonu-choudhary)
Posts: 26
Eminent Member Customer
Topic starter
 

function gemini_generate_text() {
// Get the prompt from the AJAX request
$prompt = $_POST['prompt'];
$temperature = isset($_POST['temperature']) ? $_POST['temperature'] : 0.7; // Optional temperature

// Placeholders for Gemini API details (replace with actual API information when available)
$api_url = 'curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pr o';
$api_key = 'AIzaSyBKFJF-nTDC-tHN8gqKukd';

// Prepare API request (adjust based on Gemini's requirements)
$headers = ['Authorization' => 'Bearer ' . $api_key]; // Adjust for actual authentication method
$body = [
'model' => 'gemini-pro',
'prompt' => $prompt,
'temperature' => $temperature
];

// Send request using appropriate library or method (adjust as needed)
$response = wp_remote_post($api_url, [
'headers' => $headers,
'body' => json_encode($body)
]);

// Handle response (adjust based on Gemini's API response structure)
if (is_wp_error($response)) {
wp_send_json_error("API request failed: " . $response->get_error_message());
} else {
$data = json_decode($response['body'], true);

// Assuming generated text is in a property named 'text' (adjust as needed)
if (isset($data['text'])) {
wp_send_json_success($data); // Send generated text back to JavaScript
} else {
wp_send_json_error("API response error: Invalid response structure");
}
}

wp_die();
}

add_action('wp_ajax_gemini_generate_text', 'gemini_generate_text');
add_action('wp_ajax_nopriv_gemini_generate_text', 'gemini_generate_text');

 

 

 

<div id="text-generation-tool">
<input type="text" id="topic" placeholder="Your Topic...">
<button id="generate-button">Generate Story!</button>
<div id="result-container" style="display: none;">
<div class="result-wrapper">
<div class="result-content">
<textarea id="result" readonly></textarea>
</div>
<div class="copy-button-container">
<button id="copy-button">Copy</button>
</div>
</div>
</div>
<div id="loading" class="loader" style="display: none;"></div>
</div>

<style>
/* Basic styles for the text generation tool */
#text-generation-tool {
width: 100%;
max-width: 600px;
margin: 0 auto;
font-family: Arial, sans-serif;
}

#topic {
width: 100%;
padding: 15px;
margin-bottom: 20px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ddd;
}

#generate-button {
display: block;
width: 100%;
padding: 15px;
margin-bottom: 20px;
font-size: 16px;
border: none;
border-radius: 5px;
color: #fff;
background-color: #3498db;
cursor: pointer;
transition: background-color 0.3s ease;
}

#generate-button:hover {
background-color: #2980b9;
}

#result-container {
display: none;
margin-bottom: 20px;
}

.result-wrapper {
position: relative;
overflow: hidden;
}

.result-content {
display: flex;
}

#result {
flex: 1;
height: 400px;
padding: 15px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}

.copy-button-container {
margin-top: 10px;
text-align: right;
}

#copy-button {
padding: 8px 12px;
font-size: 14px;
border: none;
border-radius: 5px;
color: #fff;
background-color: #3498db;
cursor: pointer;
transition: background-color 0.3s ease;
}

#copy-button:hover {
background-color: #2980b9;
}

/* CSS for the loader */
.loader {
display: block;
margin: 50px auto;
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
}

@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>

<script>

document.getElementById("generate-button").addEventListener("click", function(e) {
e.preventDefault();

var generateButton = document.getElementById("generate-button");

if (generateButton.disabled) {
return; // Prevent multiple clicks while content is being generated
}

generateButton.disabled = true;

var topic = document.getElementById('topic').value;
var prompt = "Generate a 3 sentence story about " + topic;
var loading = document.getElementById('loading');
var result = document.getElementById('result');
var resultC = document.getElementById('result-container');

loading.style.display = 'block';
result.style.display = 'none'; // hide result textarea
resultC.style.display = 'none';

var formData = new FormData();
// Using placeholder for Gemini API integration (replace when available)
formData.append('action', 'gemini_generate_text');
formData.append('prompt', prompt);
// Optionally add temperature control (if supported by Gemini API)
formData.append('temperature', 0.7); // Adjust as needed

fetch('/wp-admin/admin-ajax.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
loading.style.display = 'none';
if (data.success) {
// Assuming generated text is in 'text' property (adjust based on Gemini's response)
result.value = data.text;
result.style.display = 'block'; // show result textarea
resultC.style.display = 'block';
generateButton.disabled = false;
} else {
result.value = 'An error occurred: ' + data.data;
result.style.display = 'block'; // show result textarea
resultC.style.display = 'block';
generateButton.disabled = false;
}
})
.catch(error => {
loading.style.display = 'none';
result.value = 'An error occurred: ' + error.message;
result.style.display = 'block'; // show result textarea
resultC.style.display = 'block';
generateButton.disabled = false;
});
});

// Copy button functionality remains unchanged
var copyButton = document.getElementById('copy-button');
copyButton.addEventListener('click', function() {
var result = document.getElementById('result');
result.select();
document.execCommand('copy');
alert('Copied to clipboard!');
});

</script>

 
Posted : 02/02/2024 12:55 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@sonu-choudhary I asked you to use the code icon (<>) above to share your code so that the formatting would show correctly.

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

 
Posted : 02/02/2024 3:26 pm
(@sonu-choudhary)
Posts: 26
Eminent Member Customer
Topic starter
 

@admin

function gemini_generate_text() {
// Get the prompt from the AJAX request
$prompt = $_POST['prompt'];
$temperature = isset($_POST['temperature']) ? $_POST['temperature'] : 0.7; // Optional temperature

// Placeholders for Gemini API details (replace with actual API information when available)
$api_url = 'curl  https://generativelanguage.googleapis.com/v1beta/models/gemini-pr  o';
$api_key = 'AIzaSyBKFJF-nTDC-tHN8gqKukd';

// Prepare API request (adjust based on Gemini's requirements)
$headers = ['Authorization' => 'Bearer ' . $api_key]; // Adjust for actual authentication method
$body = [
'model' => 'gemini-pro',
'prompt' => $prompt,
'temperature' => $temperature
];

// Send request using appropriate library or method (adjust as needed)
$response = wp_remote_post($api_url, [
'headers' => $headers,
'body' => json_encode($body)
]);

// Handle response (adjust based on Gemini's API response structure)
if (is_wp_error($response)) {
wp_send_json_error("API request failed: " . $response->get_error_message());
} else {
$data = json_decode($response['body'], true);

// Assuming generated text is in a property named 'text' (adjust as needed)
if (isset($data['text'])) {
wp_send_json_success($data); // Send generated text back to JavaScript
} else {
wp_send_json_error("API response error: Invalid response structure");
}
}

wp_die();
}

add_action('wp_ajax_gemini_generate_text', 'gemini_generate_text');
add_action('wp_ajax_nopriv_gemini_generate_text', 'gemini_generate_text');

 

 

 

<div id="text-generation-tool">
<input type="text" id="topic" placeholder="Your Topic...">
<button id="generate-button">Generate Story!</button>
<div id="result-container" style="display: none;">
<div class="result-wrapper">
<div class="result-content">
<textarea id="result" readonly></textarea>
</div>
<div class="copy-button-container">
<button id="copy-button">Copy</button>
</div>
</div>
</div>
<div id="loading" class="loader" style="display: none;"></div>
</div>

<style>
/* Basic styles for the text generation tool */
#text-generation-tool {
width: 100%;
max-width: 600px;
margin: 0 auto;
font-family: Arial, sans-serif;
}

#topic {
width: 100%;
padding: 15px;
margin-bottom: 20px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ddd;
}

#generate-button {
display: block;
width: 100%;
padding: 15px;
margin-bottom: 20px;
font-size: 16px;
border: none;
border-radius: 5px;
color: #fff;
background-color: #3498db;
cursor: pointer;
transition: background-color 0.3s ease;
}

#generate-button:hover {
background-color: #2980b9;
}

#result-container {
display: none;
margin-bottom: 20px;
}

.result-wrapper {
position: relative;
overflow: hidden;
}

.result-content {
display: flex;
}

#result {
flex: 1;
height: 400px;
padding: 15px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}

.copy-button-container {
margin-top: 10px;
text-align: right;
}

#copy-button {
padding: 8px 12px;
font-size: 14px;
border: none;
border-radius: 5px;
color: #fff;
background-color: #3498db;
cursor: pointer;
transition: background-color 0.3s ease;
}

#copy-button:hover {
background-color: #2980b9;
}

/* CSS for the loader */
.loader {
display: block;
margin: 50px auto;
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
}

@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

</style>



<script>

document.getElementById("generate-button").addEventListener("click", function(e) {
e.preventDefault();

var generateButton = document.getElementById("generate-button");

if (generateButton.disabled) {
return; // Prevent multiple clicks while content is being generated
}

generateButton.disabled = true;

var topic = document.getElementById('topic').value;
var prompt = "Generate a 3 sentence story about " + topic;
var loading = document.getElementById('loading');
var result = document.getElementById('result');
var resultC = document.getElementById('result-container');

loading.style.display = 'block';
result.style.display = 'none'; // hide result textarea
resultC.style.display = 'none';

var formData = new FormData();
// Using placeholder for Gemini API integration (replace when available)
formData.append('action', 'gemini_generate_text');
formData.append('prompt', prompt);
// Optionally add temperature control (if supported by Gemini API)
formData.append('temperature', 0.7); // Adjust as needed

fetch('/wp-admin/admin-ajax.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
loading.style.display = 'none';
if (data.success) {
// Assuming generated text is in 'text' property (adjust based on Gemini's response)
result.value = data.text;
result.style.display = 'block'; // show result textarea
resultC.style.display = 'block';
generateButton.disabled = false;
} else {
result.value = 'An error occurred: ' + data.data;
result.style.display = 'block'; // show result textarea
resultC.style.display = 'block';
generateButton.disabled = false;
}
})
.catch(error => {
loading.style.display = 'none';
result.value = 'An error occurred: ' + error.message;
result.style.display = 'block'; // show result textarea
resultC.style.display = 'block';
generateButton.disabled = false;
});
});

// Copy button functionality remains unchanged
var copyButton = document.getElementById('copy-button');
copyButton.addEventListener('click', function() {
var result = document.getElementById('result');
result.select();
document.execCommand('copy');
alert('Copied to clipboard!');
});

</script>

 
Posted : 02/02/2024 5:34 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@sonu-choudhary I asked ChatGPT what was wrong with the code, here is what it had to say:

 

There are a few issues and points of improvement in the provided WordPress code snippet that deals with integrating a hypothetical Gemini API for generating text. Here are the key points:

### PHP Part (WordPress Backend)

1. **API URL Syntax and Usage**: The API URL string contains spaces and a line break, which is incorrect. URLs must be correctly formatted without spaces or line breaks. This will cause the API call to fail.
```php
$api_url = 'curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pr o';
```
It should be corrected to something like:
```php
$api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro';
```
Also, `curl` should not be part of the URL; it seems like a confusion with how to make API requests in command-line examples.

2. **Authorization Header**: The example assumes a bearer token for authorization. Ensure that the Gemini API requires a bearer token and that `"Authorization" => 'Bearer ' . $api_key` is the correct way to authenticate. Sometimes APIs require API keys to be sent as query parameters or in different header formats.

3. **Error Handling**: The code correctly checks for WP_Error but assumes the response structure will contain a `'text'` key. Make sure the Gemini API response structure is as expected. Additionally, consider adding status code checks to handle HTTP errors more gracefully.

4. **Security**: Ensure that user input is sanitized and validated, especially since it is being sent to an external API. The code snippet does not show any validation or sanitization of the `$_POST['prompt']` variable.

### JavaScript Part (Frontend)

1. **Form Data Handling**: The script correctly collects input and sends it via `FormData`, which is good for this use case.

2. **Error Handling**: The JavaScript error handling is basic. It might be beneficial to inform the user more specifically about what went wrong, depending on the error messages returned by the WordPress backend and the API.

3. **User Experience**: Disabling the generate button to prevent multiple submissions is good practice. However, consider adding more feedback mechanisms (like progress indicators or more detailed error messages) to improve user experience.

### General Recommendations

- **API Key Exposure**: Ensure the API key is not hard-coded or exposed in places where it can be accessed by unauthorized users. Consider storing sensitive information like API keys in configuration files or the database, and access them securely within your PHP code.
- **Consistent Error Messages**: Maintain consistency in how error messages are presented to the end user, ensuring they are user-friendly and not exposing too much technical detail.
- **HTTPS Usage**: Always use HTTPS for making API requests to ensure the security of the data being transmitted.

By addressing these issues, the code should be more robust, secure, and functional.

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

 
Posted : 02/02/2024 8:30 pm
(@sonu-choudhary)
Posts: 26
Eminent Member Customer
Topic starter
 

@ssadvisor Anyone can ask ChatGPT to identify any issues in this code. If you implement this code in WordPress, please send me the revised version."

 
Posted : 02/03/2024 5:35 am
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

@sonu-choudhary Hi Friend, did you try the Gemini API first outside WordPress? did you try to generate with the API call first

 
Posted : 02/03/2024 10:16 am
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

anyway, I will do some tests on Gemeni AI within WordPress, and I will try to make a working function so anyone can use it

 
Posted : 02/03/2024 10:30 am
(@sonu-choudhary)
Posts: 26
Eminent Member Customer
Topic starter
 

@admin yes i have create lots of apps using gemini pro and vision api just im stuck at wordpress function

 
Posted : 02/03/2024 10:52 am
(@sonu-choudhary)
Posts: 26
Eminent Member Customer
Topic starter
 

@admin yes bro do it hurry as much as possible

 
Posted : 02/03/2024 10:53 am
Page 1 / 3
Share:
[the_ad_group id="312"]