Skip to content

Instantly share code, notes, and snippets.

@jordymeow
Last active March 8, 2024 14:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
}
@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?

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