Skip to content

Instantly share code, notes, and snippets.

@jordymeow
Last active October 29, 2024 10:31
Show Gist options
  • Save jordymeow/c570826db8f72502f5f46a95cda30be5 to your computer and use it in GitHub Desktop.
Save jordymeow/c570826db8f72502f5f46a95cda30be5 to your computer and use it in GitHub Desktop.
Web Search (or similar) for AI Engine
<?php
add_filter( "mwai_context_search", 'my_web_search', 10, 3 );
function my_web_search( $context, $query, $options = [] ) {
// If the context is already provided, return it as is.
if ( ! empty( $context ) ) {
return $context;
}
// Get the latest question from the visitor.
$lastMessage = $query->get_message();
// Perform a search via the Google Custom Search API.
$apiKey = 'YOUR_API_KEY';
$engineId = 'YOUR_ENGINE_ID';
if ( empty( $apiKey ) || empty( $engineId ) ) {
return null;
}
$url = "https://www.googleapis.com/customsearch/v1?key=$apiKey&cx=$engineId&q=" . urlencode( $lastMessage );
$response = wp_remote_get( $url );
if ( is_wp_error( $response ) ) {
return null;
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
if ( empty( $data->items ) ) {
return null;
}
// AI Engine expects a type (for logging purposes) and the content (which will be used by AI).
$context["type"] = "websearch";
$context["content"] = "";
// Loop through the 5 first results.
$max = min( count( $data->items ), 5 );
for ( $i = 0; $i < $max; $i++ ) {
$result = $data->items[$i];
$title = $result->title;
$url = $result->link;
$snippet = $result->snippet;
$content = "Title: $title\nExcerpt: $snippet\nURL: $url\n\n";
$context["content"] .= $content;
}
return $context;
}
@christodeus
Copy link

@jordymeow Hi Jordy, getting to you back with my old message. This code is working great, I would like just that it first search in the embeddings DB, then if nothing is found, that it search on the internet.

@genai-consultant
Copy link

@jordymeow I am getting below error PHP Fatal error: Uncaught Error: Call to undefined method Meow_MWAI_Query_Text::getLastMessage() in /var/www/html/wp-content/plugins/code-snippets/php/snippet-ops.php(582) :

@maratinn2
Copy link

I get the same error somehow the getLastMessage() is causing trouble.

@jordymeow
Copy link
Author

I have fixed the code, instead of getLastMessage, get_message should be used.

@maratinn2
Copy link

@jordymeow Hi Jordy, getting to you back with my old message. This code is working great, I would like just that it first search in the embeddings DB, then if nothing is found, that it search on the internet.

How did you manage to do it? mine is not responding the results. I must have missing something. When I check the logs I see that it works fine.

@genai-consultant
Copy link

Thanks for solution

@wgnrai
Copy link

wgnrai commented Mar 8, 2024

I feel like a dummy. I can't get it to work. I'm using WPCode to add snippets such as this code. Is that incorrect or is there something else I am doing wrong? Am I using the wrong ChatGPT model?

What I get is"

_"As of my last update in April 2023, I can't provide real-time information or comments from the web, including trending comments about events such as the State of the Union address or any other current events. My capabilities are centered around providing information that was available up to that point, and I don't have access to live updates or the ability to browse the internet in real-time."

  • Wágner

@wgnrai
Copy link

wgnrai commented Mar 8, 2024

If I am not mistaken, this:

$content = "Title: $titlenExcerpt: $snippetnURL: $urlnn";

Was recently corrected to:

$content = "Title: $title\nExcerpt: $snippet\nURL: $url\n\n";

Is that true?

@pipilpower
Copy link

Why you doesn't keep working on this function? I want to my Chatbot connect to the web in search of data. The model GPT-4 has this function integrated but the costs are more expensive...10,000%

@kylehi2222
Copy link

kylehi2222 commented Aug 29, 2024

Hey @jordymeow ,

First all, thank you much for the great work you have put into the chatbot. We've just rolled the Pro version out on https://app.humandesign.ai and it's truly amazing. I'm currently trying to give our AI context or current astrological transits. If you have a moment, could you maybe show me where my code is going wrong:

add_filter("mwai_context_search", 'current_astrological_data', 10, 3);

function current_astrological_data($context, $query, $options = []) {

// Get the latest question from the visitor.
$lastMessage = $query->getLastMessage();

// Initialize cURL to call the RapidAPI endpoint.
$curl = curl_init();

curl_setopt_array($curl, [
CURLOPT_URL => "https://astrologer.p.rapidapi.com/api/v4/now",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"x-rapidapi-host: astrologer.p.rapidapi.com",
"x-rapidapi-key: 6de8f5ba45msh4c157dcb7752b21p1a88acjsn6d2e7cb39aec"
],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
$apiContent = "cURL Error #:" . $err;
} else {
$responseData = json_decode($response, true);

// Assuming the API returns a JSON object with astrological data
if (isset($responseData['data'])) {
  $apiContent = "Current Astrological Positions:\n";
  foreach ($responseData['data'] as $key => $value) {
    $apiContent .= ucfirst($key) . ": " . $value . "\n";
  }
} else {
  $apiContent = "Could not retrieve astrological data.";
}

}

// Incorporate the existing context (if any) and add the API data to it
if (!empty($context)) {
$context["content"] .= "\n" . $apiContent;
} else {
$context["content"] = $apiContent;
}

// Set the context type to "astrological_data"
$context["type"] = "astrological_data";
return $context;
}

Key is only valid for 10 searches btw.

@MaxineWoods
Copy link

MaxineWoods commented Oct 17, 2024

Thank you so much for sharing this code snippet! I was looking for a way to integrate web search functionality for my brother, and your solution using the Google Custom Search API is exactly what I needed. The clarity and structure of your code make it easy to understand and implement. I truly appreciate your help, this will make a big difference for him. I want to help my brother because he also always helps me whenever I need him. Last time he shared the https://www.topessaywriting.org/samples/search-engine website with me because he knows that I am not so good at writing essay assignments. Recently, I got an essay assignment on a search engine topic and I found it in on that website which he shared with me. On that website, I can easily found a lot of topics for your essay assignments and the good thing is, I can read all of them for free.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment