urlencode( $query ), 'count' => absint( $count ), 'text_decorations' => 0, // Disable HTML tags in descriptions 'spellcheck' => 1, ), $this->api_endpoint ); $response = wp_remote_get( $url, array( 'headers' => array( 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip', 'X-Subscription-Token' => $api_key, ), 'timeout' => 15, ) ); if ( is_wp_error( $response ) ) { return $response; } $http_code = wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( 200 !== $http_code ) { return new WP_Error( 'brave_api_error', sprintf( /* translators: %1$d is HTTP status code, %2$s is error message */ __( 'Brave Search API Error %1$d: %2$s', 'wp-agentic-writer' ), $http_code, $body['message'] ?? __( 'Unknown Error', 'wp-agentic-writer' ) ) ); } if ( empty( $body['web']['results'] ) ) { return array(); // No results found } $formatted_results = array(); foreach ( $body['web']['results'] as $result ) { $formatted_results[] = array( 'title' => $result['title'] ?? '', 'url' => $result['url'] ?? '', 'description' => $result['description'] ?? '', ); } // Cache results for 1 hour to prevent redundant API calls set_transient( $cache_key, $formatted_results, HOUR_IN_SECONDS ); return $formatted_results; } /** * Formats search results into a markdown context block for LLM System Prompt injection. * * @since 0.1.0 * @param array $results Search results array. * @param string $query Original query. * @return string Formatted markdown context string. */ public function format_results_for_llm( $results, $query ) { if ( empty( $results ) || is_wp_error( $results ) ) { return "No reliable web search results found for: {$query}"; } $markdown = "## LIVE WEB SEARCH CONTEXT\n"; $markdown .= "> You successfully searched the internet for: \"{$query}\"\n"; $markdown .= "> Please incorporate the following real-time data into your answer:\n\n"; $counter = 1; foreach ( $results as $item ) { $markdown .= "{$counter}. **{$item['title']}**\n"; $markdown .= " URL: {$item['url']}\n"; $markdown .= " Summary: {$item['description']}\n\n"; $counter++; } $markdown .= "---------------------------\n"; return $markdown; } }