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;
}
@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