File size: 4,421 Bytes
6c50d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import random
from typing import Callable, Dict, List, Optional

import numpy as np

from .base_agent import BaseAgent

from autoresttest.graph import OperationGraph
from autoresttest.utils import construct_basic_token

# Progress callback type: (current_operation: str, completed_count: int) -> None
ProgressCallback = Callable[[str, int], None]


class HeaderAgent(BaseAgent):
    def __init__(
        self,
        operation_graph: OperationGraph,
        alpha: float = 0.1,
        gamma: float = 0.9,
        epsilon: float = 0.1,
    ):
        self.q_table: Dict[str, List[List]] = {}
        self.operation_graph = operation_graph
        self.alpha = alpha
        self.gamma = gamma
        self.epsilon = epsilon

    def initialize_q_table(
        self, progress_callback: Optional[ProgressCallback] = None
    ) -> None:
        request_generator = self.operation_graph.request_generator
        if request_generator is None:
            return
        token_list: List = []
        operation_nodes_list = list(self.operation_graph.operation_nodes.values())
        for idx, operation_node in enumerate(operation_nodes_list):
            if progress_callback:
                progress_callback(operation_node.operation_id, idx)
            token_info = request_generator.get_auth_info(operation_node, 5)
            for token in token_info:
                token_list.append(construct_basic_token(token))

        completed = 0
        for operation_id in self.operation_graph.operation_nodes.keys():
            if operation_id not in self.q_table:
                self.q_table[operation_id] = []
            random.shuffle(token_list)
            for i in range(min(9, len(token_list))):
                self.q_table[operation_id].append([token_list[i], 0])
            self.q_table[operation_id].append([None, 0])
            completed += 1
            if progress_callback:
                progress_callback(operation_id, completed)

    def get_action(self, operation_id: str) -> Optional[str]:
        if operation_id not in self.q_table:
            raise ValueError(f"Operation '{operation_id}' not found in the Q-table for HeaderAgent.")
        if random.random() < self.epsilon:
            return self.get_random_action(operation_id)
        return self.get_best_action(operation_id)

    def get_best_action(self, operation_id: str) -> Optional[str]:
        if not self.q_table.get(operation_id):
            return None
        return max(self.q_table[operation_id], key=lambda x: x[1])[0]

    def get_random_action(self, operation_id: str) -> Optional[str]:
        return random.choice(self.q_table.get(operation_id, [[None]]))[0]

    def update_q_table(
        self, operation_id: str, action: Optional[str], reward: float
    ) -> None:
        if operation_id not in self.q_table:
            return
        current_q = 0.0
        best_next_q = -np.inf
        for mapping in self.q_table[operation_id]:
            best_next_q = max(best_next_q, mapping[1])
            if mapping[0] == action:
                current_q = mapping[1]
        new_q = current_q + self.alpha * (reward + self.gamma * best_next_q - current_q)
        for mapping in self.q_table[operation_id]:
            if mapping[0] == action:
                mapping[1] = new_q

    def get_Q_next(self, operation_id: str) -> float:
        if operation_id not in self.q_table:
            return 0.0
        best_next_q = -np.inf
        for mapping in self.q_table[operation_id]:
            best_next_q = max(best_next_q, mapping[1])
        return best_next_q

    def get_Q_curr(self, operation_id: str, token: Optional[str]) -> float:
        if operation_id not in self.q_table:
            return 0.0
        current_q = 0.0
        for mapping in self.q_table[operation_id]:
            if mapping[0] == token:
                current_q = mapping[1]
        return current_q

    def update_Q_item(
        self, operation_id: str, token: Optional[str], td_error: float
    ) -> None:
        if operation_id not in self.q_table:
            return
        for mapping in self.q_table[operation_id]:
            if mapping[0] == token:
                mapping[1] += self.alpha * td_error

    def number_of_zeros(self, operation_id: str) -> int:
        zeros = 0
        for mapping in self.q_table.get(operation_id, []):
            if mapping[1] == 0:
                zeros += 1
        return zeros