Agenten Prozessor

Der Prozessor ist eine Schlüsselkomponente des Agenten zur Verarbeitung der Kernlogik des Agenten, um die Anfrage des Benutzers zu bearbeiten. Der Prozessor wird als Klasse im Ordner ufo/agents/processors implementiert. Jeder Agent hat seine eigene Prozessor-Klasse innerhalb des Ordners.

Kernprozess

Nach dem Aufruf durchläuft ein Agent eine Reihe von Schritten, um die Anfrage des Benutzers zu bearbeiten, die in der Prozessor-Klasse definiert ist, indem die Methode process aufgerufen wird. Der Arbeitsablauf von process ist wie folgt:

Schritt Beschreibung Funktion
1 Drucken Sie die Schrittinformationen. print_step_info
2 Erfassen Sie den Screenshot der Anwendung. capture_screenshot
3 Holen Sie sich die Steuerungsinformationen der Anwendung. get_control_info
4 Holen Sie sich die Eingabeaufforderungsnachricht für die LLM. get_prompt_message
5 Generieren Sie die Antwort von der LLM. get_response
6 Aktualisieren Sie die Kosten des Schritts. update_cost
7 Analysieren Sie die Antwort von der LLM. parse_response
8 Führen Sie die Aktion basierend auf der Antwort aus. execute_action
9 Aktualisieren Sie den Speicher und das Blackboard. update_memory
10 Aktualisieren Sie den Status des Agenten. update_status

In jedem Schritt verarbeitet der Prozessor die Anfrage des Benutzers, indem er die entsprechenden Methoden sequenziell aufruft, um die notwendigen Aktionen auszuführen.

Der Prozess kann pausiert werden. Er kann basierend auf der Logik des Agenten und der Anfrage des Benutzers über die Methode resume fortgesetzt werden.

Referenz

Unten ist die grundlegende Struktur der Prozessor-Klasse aufgeführt.

Basen: ABC

Der Basisprozessor für die Sitzung. Eine Sitzung besteht aus mehreren Gesprächsrunden mit dem Benutzer, um eine Aufgabe abzuschließen. In jeder Runde interagieren der HostAgent und der AppAgent mit dem Benutzer und der Anwendung über den Prozessor. Jeder Prozessor ist dafür verantwortlich, die Benutzeranfrage zu verarbeiten und den HostAgent und AppAgent in einem einzigen Schritt einer Runde zu aktualisieren.

Initialisiert den Prozessor.

Parameter
  • context (Context) –

    Der Kontext der Sitzung.

  • agent (BasicAgent) –

    Der Agent, der den Prozessor ausführt.

Quellcode in agents/processors/basic.py
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
def __init__(self, agent: BasicAgent, context: Context) -> None:
    """
    Initialize the processor.
    :param context: The context of the session.
    :param agent: The agent who executes the processor.
    """

    self._context = context
    self._agent = agent

    self.photographer = PhotographerFacade()
    self.control_inspector = ControlInspectorFacade(BACKEND)

    self._prompt_message = None
    self._status = None
    self._response = None
    self._cost = 0
    self._control_label = None
    self._control_text = None
    self._response_json = {}
    self._memory_data = MemoryItem()
    self._question_list = []
    self._agent_status_manager = self.agent.status_manager
    self._is_resumed = False
    self._plan = None

    self._total_time_cost = 0
    self._time_cost = {}
    self._exeception_traceback = {}
    self._actions = ActionSequence()

actions Eigenschaft beschreibbar

Holen Sie sich die Aktionen.

Rückgabe
  • ActionSequence

    Die Aktionen.

agent Eigenschaft

Holen Sie sich den Agenten.

Rückgabe
  • BasicAgent

    Der Agent.

app_root Eigenschaft beschreibbar

Holen Sie sich die Anwendungs-Root.

Rückgabe
  • str

    Die Anwendungs-Root.

application_process_name Eigenschaft beschreibbar

Holen Sie sich den Namen des Anwendungsprozesses.

Rückgabe
  • str

    Der Name des Anwendungsprozesses.

application_window Eigenschaft beschreibbar

Holen Sie sich das aktive Fenster.

Rückgabe
  • UIAWrapper

    Das aktive Fenster.

context Eigenschaft

Holen Sie sich den Kontext.

Rückgabe
  • Context

    Der Kontext.

control_label Eigenschaft beschreibbar

Holen Sie sich das Steuerungslabel.

Rückgabe
  • str

    Das Steuerungslabel.

control_reannotate Eigenschaft beschreibbar

Holen Sie sich die Steuerung neu anmuten.

Rückgabe
  • List[str]

    Die Steuerung neu anmuten.

control_text Eigenschaft beschreibbar

Holen Sie sich die aktive Anwendung.

Rückgabe
  • str

    Die aktive Anwendung.

cost Eigenschaft beschreibbar

Holen Sie sich die Kosten des Prozessors.

Rückgabe
  • float

    Die Kosten des Prozessors.

host_message Eigenschaft beschreibbar

Holen Sie sich die Host-Nachricht.

Rückgabe
  • List[str]

    Die Host-Nachricht.

log_path Eigenschaft

Holen Sie sich den Protokollpfad.

Rückgabe
  • str

    Der Protokollpfad.

logger Eigenschaft

Holen Sie sich den Logger.

Rückgabe
  • str

    Der Logger.

name Eigenschaft

Holen Sie sich den Namen des Prozessors.

Rückgabe
  • str

    Der Name des Prozessors.

plan Eigenschaft beschreibbar

Holen Sie sich den Plan des Agenten.

Rückgabe
  • str

    Der Plan.

prev_plan Eigenschaft

Holen Sie sich den vorherigen Plan.

Rückgabe
  • List[str]

    Der vorherige Plan des Agenten.

previous_subtasks Eigenschaft beschreibbar

Holen Sie sich die vorherigen Unteraufgaben.

Rückgabe
  • List[str]

    Die vorherigen Unteraufgaben.

question_list Eigenschaft beschreibbar

Holen Sie sich die Fragenliste.

Rückgabe
  • List[str]

    Die Fragenliste.

request Eigenschaft

Holen Sie sich die Anfrage.

Rückgabe
  • str

    Die Anfrage.

request_logger Eigenschaft

Holen Sie sich den Anfrage-Logger.

Rückgabe
  • str

    Der Anfrage-Logger.

round_cost Eigenschaft beschreibbar

Holen Sie sich die Rundengebühr.

Rückgabe
  • float

    Die Rundengebühr.

round_num Eigenschaft

Holen Sie sich die Rundennummer.

Rückgabe
  • int

    Die Rundennummer.

round_step Eigenschaft beschreibbar

Holen Sie sich den Rundenschritt.

Rückgabe
  • int

    Der Rundenschritt.

round_subtask_amount Eigenschaft

Holen Sie sich die Anzahl der Unteraufgaben pro Runde.

Rückgabe
  • int

    Die Anzahl der Unteraufgaben pro Runde.

session_cost Eigenschaft beschreibbar

Holen Sie sich die Sitzungsgebühr.

Rückgabe
  • float

    Die Sitzungsgebühr.

session_step Eigenschaft beschreibbar

Holen Sie sich den Sitzungsschritt.

Rückgabe
  • int

    Der Sitzungsschritt.

status Eigenschaft beschreibbar

Holen Sie sich den Status des Prozessors.

Rückgabe
  • str

    Der Status des Prozessors.

subtask Eigenschaft beschreibbar

Holen Sie sich die Unteraufgabe.

Rückgabe
  • str

    Die Unteraufgabe.

ui_tree_path Eigenschaft

Holen Sie sich den UI-Baum-Pfad.

Rückgabe
  • str

    Der UI-Baum-Pfad.

add_to_memory(data_dict)

Fügen Sie die Daten zum Speicher hinzu.

Parameter
  • data_dict (Dict[str, Any]) –

    Das Daten-Dictionary, das dem Speicher hinzugefügt werden soll.

Quellcode in agents/processors/basic.py
293
294
295
296
297
298
def add_to_memory(self, data_dict: Dict[str, Any]) -> None:
    """
    Add the data to the memory.
    :param data_dict: The data dictionary to be added to the memory.
    """
    self._memory_data.add_values_from_dict(data_dict)

capture_screenshot() abstraktmethode

Erfassen Sie den Screenshot.

Quellcode in agents/processors/basic.py
231
232
233
234
235
236
@abstractmethod
def capture_screenshot(self) -> None:
    """
    Capture the screenshot.
    """
    pass

exception_capture(func) klassenmethode

Decorator zur Erfassung der Ausnahme der Methode.

Parameter
  • func

    Die zu dekorierende Methode.

Rückgabe
  • Die dekorierte Methode.

Quellcode in agents/processors/basic.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
@classmethod
def exception_capture(cls, func):
    """
    Decorator to capture the exception of the method.
    :param func: The method to be decorated.
    :return: The decorated method.
    """

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            func(self, *args, **kwargs)
        except Exception as e:
            self._exeception_traceback[func.__name__] = {
                "type": str(type(e).__name__),
                "message": str(e),
                "traceback": traceback.format_exc(),
            }

            utils.print_with_color(f"Error Occurs at {func.__name__}", "red")
            utils.print_with_color(
                self._exeception_traceback[func.__name__]["traceback"], "red"
            )
            if self._response is not None:
                utils.print_with_color("Response: ", "red")
                utils.print_with_color(self._response, "red")
            self._status = self._agent_status_manager.ERROR.value
            self.sync_memory()
            self.add_to_memory({"error": self._exeception_traceback})
            self.add_to_memory({"Status": self._status})
            self.log_save()

            raise StopIteration("Error occurred during step.")

    return wrapper

execute_action() abstraktmethode

Führt die Aktion aus.

Quellcode in agents/processors/basic.py
266
267
268
269
270
271
@abstractmethod
def execute_action(self) -> None:
    """
    Execute the action.
    """
    pass

get_control_info() abstraktmethode

Holen Sie sich die Steuerungsinformationen.

Quellcode in agents/processors/basic.py
238
239
240
241
242
243
@abstractmethod
def get_control_info(self) -> None:
    """
    Get the control information.
    """
    pass

get_prompt_message() abstraktmethode

Holen Sie sich die Eingabeaufforderungsnachricht.

Quellcode in agents/processors/basic.py
245
246
247
248
249
250
@abstractmethod
def get_prompt_message(self) -> None:
    """
    Get the prompt message.
    """
    pass

get_response() abstraktmethode

Holen Sie sich die Antwort von der LLM.

Quellcode in agents/processors/basic.py
252
253
254
255
256
257
@abstractmethod
def get_response(self) -> None:
    """
    Get the response from the LLM.
    """
    pass

is_application_closed()

Prüfen Sie, ob die Anwendung geschlossen ist.

Rückgabe
  • bool

    Der boolesche Wert, der angibt, ob die Anwendung geschlossen ist.

Quellcode in agents/processors/basic.py
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
def is_application_closed(self) -> bool:
    """
    Check if the application is closed.
    :return: The boolean value indicating if the application is closed.
    """

    if self.application_window is None:

        return True

    try:
        self.application_window.is_enabled()
        return False
    except:
        return True

is_confirm()

Prüfen Sie, ob der Prozess bestätigt wird.

Rückgabe
  • bool

    Der boolesche Wert, der angibt, ob der Prozess bestätigt wird.

Quellcode in agents/processors/basic.py
732
733
734
735
736
737
738
739
740
def is_confirm(self) -> bool:
    """
    Check if the process is confirm.
    :return: The boolean value indicating if the process is confirm.
    """

    self.agent.status = self.status

    return self.status == self._agent_status_manager.CONFIRM.value

is_error()

Prüfen Sie, ob der Prozess in einem Fehlerzustand ist.

Rückgabe
  • bool

    Der boolesche Wert, der angibt, ob der Prozess in einem Fehlerzustand ist.

Quellcode in agents/processors/basic.py
700
701
702
703
704
705
706
707
def is_error(self) -> bool:
    """
    Check if the process is in error.
    :return: The boolean value indicating if the process is in error.
    """

    self.agent.status = self.status
    return self.status == self._agent_status_manager.ERROR.value

is_paused()

Prüfen Sie, ob der Prozess pausiert ist.

Rückgabe
  • bool

    Der boolesche Wert, der angibt, ob der Prozess pausiert ist.

Quellcode in agents/processors/basic.py
709
710
711
712
713
714
715
716
717
718
719
720
def is_paused(self) -> bool:
    """
    Check if the process is paused.
    :return: The boolean value indicating if the process is paused.
    """

    self.agent.status = self.status

    return (
        self.status == self._agent_status_manager.PENDING.value
        or self.status == self._agent_status_manager.CONFIRM.value
    )

is_pending()

Prüfen Sie, ob der Prozess ausstehend ist.

Rückgabe
  • bool

    Der boolesche Wert, der angibt, ob der Prozess ausstehend ist.

Quellcode in agents/processors/basic.py
722
723
724
725
726
727
728
729
730
def is_pending(self) -> bool:
    """
    Check if the process is pending.
    :return: The boolean value indicating if the process is pending.
    """

    self.agent.status = self.status

    return self.status == self._agent_status_manager.PENDING.value

log(response_json)

Setzt das Ergebnis der Sitzung und protokolliert das Ergebnis. Ergebnis: Das Ergebnis der Sitzung. response_json: Die Antwort als JSON. Rückgabe: Die Antwort als JSON.

Quellcode in agents/processors/basic.py
758
759
760
761
762
763
764
765
766
def log(self, response_json: Dict[str, Any]) -> None:
    """
    Set the result of the session, and log the result.
    result: The result of the session.
    response_json: The response json.
    return: The response json.
    """

    self.logger.info(json.dumps(response_json))

log_save()

Speichern Sie das Protokoll.

Quellcode in agents/processors/basic.py
300
301
302
303
304
305
306
307
308
def log_save(self) -> None:
    """
    Save the log.
    """

    self._memory_data.add_values_from_dict(
        {"total_time_cost": self._total_time_cost}
    )
    self.log(self._memory_data.to_dict())

method_timer(func) klassenmethode

Decorator zur Berechnung der Zeitkosten der Methode.

Parameter
  • func

    Die zu dekorierende Methode.

Rückgabe
  • Die dekorierte Methode.

Quellcode in agents/processors/basic.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@classmethod
def method_timer(cls, func):
    """
    Decorator to calculate the time cost of the method.
    :param func: The method to be decorated.
    :return: The decorated method.
    """

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        start_time = time.time()
        result = func(self, *args, **kwargs)
        end_time = time.time()
        self._time_cost[func.__name__] = end_time - start_time
        return result

    return wrapper

parse_response() abstraktmethode

Analysieren Sie die Antwort.

Quellcode in agents/processors/basic.py
259
260
261
262
263
264
@abstractmethod
def parse_response(self) -> None:
    """
    Parse the response.
    """
    pass

print_step_info() abstraktmethode

Drucken Sie die Schrittinformationen.

Quellcode in agents/processors/basic.py
224
225
226
227
228
229
@abstractmethod
def print_step_info(self) -> None:
    """
    Print the step information.
    """
    pass

process()

Verarbeitet einen einzelnen Schritt in einer Runde. Der Prozess umfasst die folgenden Schritte: 1. Drucken Sie die Schrittinformationen. 2. Erfassen Sie den Screenshot. 3. Holen Sie sich die Steuerungsinformationen. 4. Holen Sie sich die Eingabeaufforderungsnachricht. 5. Holen Sie sich die Antwort. 6. Aktualisieren Sie die Kosten. 7. Analysieren Sie die Antwort. 8. Führen Sie die Aktion aus. 9. Aktualisieren Sie den Speicher. 10. Aktualisieren Sie den Schritt und den Status. 11. Speichern Sie das Protokoll.

Quellcode in agents/processors/basic.py
 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def process(self) -> None:
    """
    Process a single step in a round.
    The process includes the following steps:
    1. Print the step information.
    2. Capture the screenshot.
    3. Get the control information.
    4. Get the prompt message.
    5. Get the response.
    6. Update the cost.
    7. Parse the response.
    8. Execute the action.
    9. Update the memory.
    10. Update the step and status.
    11. Save the log.
    """

    start_time = time.time()

    try:
        # Step 1: Print the step information.
        self.print_step_info()

        # Step 2: Capture the screenshot.
        self.capture_screenshot()

        # Step 3: Get the control information.
        self.get_control_info()

        # Step 4: Get the prompt message.
        self.get_prompt_message()

        # Step 5: Get the response.
        self.get_response()

        # Step 6: Update the context.
        self.update_cost()

        # Step 7: Parse the response, if there is no error.
        self.parse_response()

        if self.is_pending() or self.is_paused():
            # If the session is pending, update the step and memory, and return.
            if self.is_pending():
                self.update_status()
                self.update_memory()

            return

        # Step 8: Execute the action.
        self.execute_action()

        # Step 9: Update the memory.
        self.update_memory()

        # Step 10: Update the status.
        self.update_status()

        self._total_time_cost = time.time() - start_time

        # Step 11: Save the log.
        self.log_save()

    except StopIteration:
        # Error was handled and logged in the exception capture decorator.
        # Simply return here to stop the process early.

        return

resume()

Setzt die Ausführung von Aktionen nach der Pausierung der Sitzung fort.

Quellcode in agents/processors/basic.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def resume(self) -> None:
    """
    Resume the process of action execution after the session is paused.
    """

    self._is_resumed = True

    try:
        # Step 1: Execute the action.
        self.execute_action()

        # Step 2: Update the memory.
        self.update_memory()

        # Step 3: Update the status.
        self.update_status()

    except StopIteration:
        # Error was handled and logged in the exception capture decorator.
        # Simply return here to stop the process early.
        pass

    finally:
        self._is_resumed = False

string2list(string) statische methode

Konvertiert einen String in eine Liste von Strings, wenn die Eingabe ein String ist.

Parameter
  • string (Any) –

    Der String.

Rückgabe
  • List[str]

    Die Liste.

Quellcode in agents/processors/basic.py
776
777
778
779
780
781
782
783
784
785
786
@staticmethod
def string2list(string: Any) -> List[str]:
    """
    Convert a string to a list of string if the input is a string.
    :param string: The string.
    :return: The list.
    """
    if isinstance(string, str):
        return [string]
    else:
        return string

sync_memory() abstraktmethode

Synchronisiert den Speicher des Agenten.

Quellcode in agents/processors/basic.py
217
218
219
220
221
222
@abstractmethod
def sync_memory(self) -> None:
    """
    Sync the memory of the Agent.
    """
    pass

update_cost()

Aktualisieren Sie die Kosten.

Quellcode in agents/processors/basic.py
318
319
320
321
322
323
324
def update_cost(self) -> None:
    """
    Update the cost.
    """

    self.round_cost += self.cost
    self.session_cost += self.cost

update_memory() abstraktmethode

Aktualisiert den Speicher des Agenten.

Quellcode in agents/processors/basic.py
273
274
275
276
277
278
@abstractmethod
def update_memory(self) -> None:
    """
    Update the memory of the Agent.
    """
    pass

update_status()

Aktualisiert den Status der Sitzung.

Quellcode in agents/processors/basic.py
280
281
282
283
284
285
286
287
288
289
290
291
def update_status(self) -> None:
    """
    Update the status of the session.
    """
    self.agent.step += 1
    self.agent.status = self.status

    if self.status != self._agent_status_manager.FINISH.value:
        time.sleep(configs["SLEEP_TIME"])

    self.round_step += 1
    self.session_step += 1