|
| 1 | +# Copyright 2023-2025 AgentEra(Agently.Tech) |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +import asyncio |
| 17 | + |
| 18 | +from typing import Any, Callable, TYPE_CHECKING |
| 19 | +from agently.core import BaseAgent |
| 20 | +from agently.utils import FunctionShifter, GeneratorConsumer |
| 21 | + |
| 22 | +if TYPE_CHECKING: |
| 23 | + from agently.core.ModelRequest import ModelResponse |
| 24 | + from agently.types.data import AgentlyModelResponseEvent |
| 25 | + |
| 26 | + |
| 27 | +class KeyWaiterExtension(BaseAgent): |
| 28 | + def __init__(self, *args, **kwargs): |
| 29 | + super().__init__(*args, **kwargs) |
| 30 | + self.__when_handlers = {} |
| 31 | + |
| 32 | + self.get_key_result = FunctionShifter.syncify(self.async_get_key_result) |
| 33 | + |
| 34 | + def __check_keys_in_output( |
| 35 | + self, |
| 36 | + keys: list[str], |
| 37 | + must_in_prompt: bool = False, |
| 38 | + ): |
| 39 | + if "output" not in self.request.prompt or not self.request.prompt["output"]: |
| 40 | + raise NotImplementedError( |
| 41 | + f"Error: Cannot find keys without 'output' prompt definition.\nPrompt: { self.request.prompt }" |
| 42 | + ) |
| 43 | + if must_in_prompt: |
| 44 | + no_found_keys = [] |
| 45 | + for key in keys: |
| 46 | + if key not in self.request.prompt: |
| 47 | + no_found_keys.append(key) |
| 48 | + if no_found_keys: |
| 49 | + raise NotImplementedError( |
| 50 | + f"Error: Cannot wait key/keys { no_found_keys } because they were not in 'output' prompt\nPrompt: { self.request.prompt }" |
| 51 | + ) |
| 52 | + |
| 53 | + def __get_consumer(self): |
| 54 | + response = self.get_response() |
| 55 | + return GeneratorConsumer(response.get_async_generator(content="instant")) |
| 56 | + |
| 57 | + async def async_get_key_result( |
| 58 | + self, |
| 59 | + key: str, |
| 60 | + *, |
| 61 | + must_in_prompt: bool = False, |
| 62 | + ): |
| 63 | + self.__check_keys_in_output( |
| 64 | + [key], |
| 65 | + must_in_prompt=must_in_prompt, |
| 66 | + ) |
| 67 | + consumer = self.__get_consumer() |
| 68 | + |
| 69 | + async for data in consumer.get_async_generator(): |
| 70 | + if key == data.path and data.is_complete: |
| 71 | + return data.value |
| 72 | + |
| 73 | + async def async_wait_keys( |
| 74 | + self, |
| 75 | + keys: list[str], |
| 76 | + *, |
| 77 | + must_in_prompt: bool = False, |
| 78 | + ): |
| 79 | + self.__check_keys_in_output( |
| 80 | + keys, |
| 81 | + must_in_prompt=must_in_prompt, |
| 82 | + ) |
| 83 | + consumer = self.__get_consumer() |
| 84 | + |
| 85 | + async for data in consumer.get_async_generator(): |
| 86 | + if data.path in keys and data.is_complete: |
| 87 | + yield data.path, data.value |
| 88 | + |
| 89 | + def wait_keys( |
| 90 | + self, |
| 91 | + keys: list[str], |
| 92 | + *, |
| 93 | + must_in_prompt: bool = False, |
| 94 | + ): |
| 95 | + self.__check_keys_in_output( |
| 96 | + keys, |
| 97 | + must_in_prompt=must_in_prompt, |
| 98 | + ) |
| 99 | + consumer = self.__get_consumer() |
| 100 | + |
| 101 | + for data in consumer.get_generator(): |
| 102 | + if data.path in keys and data.is_complete: |
| 103 | + yield data.path, data.value |
| 104 | + |
| 105 | + def when_key(self, key: str, handler: Callable[[Any], Any]): |
| 106 | + if key not in self.__when_handlers: |
| 107 | + self.__when_handlers.update({key: []}) |
| 108 | + self.__when_handlers[key].append(handler) |
| 109 | + return self |
| 110 | + |
| 111 | + async def async_start_waiter(self, *, must_in_prompt: bool = False): |
| 112 | + if not self.__when_handlers: |
| 113 | + raise NotImplementedError( |
| 114 | + f"Use .when_key(<key>, <handler>) to provide at least one key handler before .start_waiter()." |
| 115 | + ) |
| 116 | + handler_keys = list(self.__when_handlers.keys()) |
| 117 | + self.__check_keys_in_output( |
| 118 | + handler_keys, |
| 119 | + must_in_prompt=must_in_prompt, |
| 120 | + ) |
| 121 | + consumer = self.__get_consumer() |
| 122 | + tasks = [] |
| 123 | + |
| 124 | + async def handler_wrapper(path: str, value: Any, handler: Callable[[Any], Any]) -> Any: |
| 125 | + return path, value, await FunctionShifter.asyncify(handler)(value) |
| 126 | + |
| 127 | + async for data in consumer.get_async_generator(): |
| 128 | + if data.path in handler_keys and data.is_complete: |
| 129 | + for handler in self.__when_handlers[data.path]: |
| 130 | + tasks.append(asyncio.create_task(handler_wrapper(data.path, data.value, handler))) |
| 131 | + |
| 132 | + self.request.prompt.clear() |
| 133 | + |
| 134 | + return await asyncio.gather(*tasks) |
| 135 | + |
| 136 | + def start_waiter(self, *, must_in_prompt: bool = False): |
| 137 | + if not self.__when_handlers: |
| 138 | + raise NotImplementedError( |
| 139 | + f"Use .when_key(<key>, <handler>) to provide at least one key handler before .start_waiter()." |
| 140 | + ) |
| 141 | + handler_keys = list(self.__when_handlers.keys()) |
| 142 | + self.__check_keys_in_output( |
| 143 | + handler_keys, |
| 144 | + must_in_prompt=must_in_prompt, |
| 145 | + ) |
| 146 | + consumer = self.__get_consumer() |
| 147 | + results = [] |
| 148 | + |
| 149 | + for data in consumer.get_generator(): |
| 150 | + if data.path in handler_keys and data.is_complete: |
| 151 | + for handler in self.__when_handlers[data.path]: |
| 152 | + results.append( |
| 153 | + ( |
| 154 | + data.path, |
| 155 | + data.value, |
| 156 | + FunctionShifter.syncify( |
| 157 | + handler, |
| 158 | + )(data.value), |
| 159 | + ) |
| 160 | + ) |
| 161 | + |
| 162 | + self.request.prompt.clear() |
| 163 | + |
| 164 | + return results |
0 commit comments