<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _get_history_id(self, connection, agent_id, instance_id):
 ''' Checks own cache for history_id for agent_id and instance_id. If information is missing fetch it from database. If it is not there create the new record. BEWARE: This method runs in a thread. ''' cache_key = (agent_id, instance_id, ) if cache_key in self._history_id_cache: history_id = self._history_id_cache[cache_key] return history_id else: command = text_helper.format_block(""" SELECT id FROM histories WHERE agent_id = ? AND instance_id = ? """
)
            cursor = connection.cursor()
            cursor.execute(command, (agent_id, instance_id, ))
            res = cursor.fetchall()
            if res:
                history_id = res[0][0]
                self._history_id_cache[cache_key] = history_id
                return history_id
            else:
                command = 'INSERT INTO histories VALUES (NULL, ?, ?)'
                cursor.execute(command, (agent_id, instance_id, ))
                history_id = cursor.lastrowid
                self._history_id_cache[cache_key] = history_id
                return history_id