Real Time Data (From Google)
If you need help with this, you can check out our documentation on the matter here. Just use the mwai_context_search filter.
You can use this code to help you understand what is going on if you are experiencing issue with this.
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 ) ) {
error_log( "Context was found ! 💡 - Skipping web search." );
return $context;
}
// Get the latest question from the visitor.
$lastMessage = $query->get_message();
// Perform a search via the Google Custom Search API.
$apiKey = '';
$engineId = '';
if ( empty( $apiKey ) || empty( $engineId ) ) {
error_log( "🚨 Please set your Google Custom Search API key and engine ID in the file functions.php.");
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 ) ) {
error_log( "🚨 Error while calling the Google Custom Search API: " . $response->get_error_message() );
return null;
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
if ( empty( $data->items ) ) {
error_log( "🚨 No result found for the query: $lastMessage" );
return null;
}
// AI Engine expects a type (for logging purposes) and the content (which will be used by AI).
$context["type"] = "websearch";
$context["content"] = "If the user ask '$lastMessage', use the following information:\n\n";
// 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;
}
error_log( "🔍 Web search context: " . print_r( $context, true ) );
return $context;
}
OpenAI models are trained to respond that they can't receive new information, so if your query mentions "web search" or "internet," you might get such a response. You could try other models and see if that behavior changes.
The filters add data from the web into the chatbot context, but the AI itself doesn't have any knowledge of where this data comes from, and it shouldn't know this is from a web search.
Did this answer your question?
😞
😐
🤩