Last active
October 29, 2024 10:31
-
-
Save jordymeow/c570826db8f72502f5f46a95cda30be5 to your computer and use it in GitHub Desktop.
Web Search (or similar) for AI Engine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.