<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def random_link(self, dataset, state, backward=False):
 """Get a random link. Parameters dataset : `object` Dataset from `self.get_dataset()`. state : `object` Link source. backward : `bool`, optional Link direction. Raises ------ ValueError If link count is invalid. Returns ------- (`str` or `None`, `object` or `None`) Link value and next state. """

        links = self.get_links(dataset, state, backward)
        if not links:
            return None, None
        x = randint(0, sum(link[0] for link in links) - 1)
        for link in links:
            count = link[0]
            if x < count:
                return link[1], self.follow_link(link, state, backward)
            x -= count
        raise RuntimeError('invalid link sum')