File size: 13,454 Bytes
d961e88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
from dataclasses import asdict, dataclass
from functools import partial
from math import ceil
from typing import Optional

import tiktoken
import yaml
from jinja2 import Environment, StrictUndefined, Template
from PIL import Image
from torch import Tensor, cosine_similarity

from pptagent.llms import LLM, AsyncLLM
from pptagent.utils import get_json_from_response, package_join

ENCODING = tiktoken.encoding_for_model("gpt-4o")


@dataclass
class Turn:
    """

    A class to represent a turn in a conversation.

    """

    id: int
    prompt: str
    response: str
    message: list
    retry: int = -1
    images: list[str] = None
    input_tokens: int = 0
    output_tokens: int = 0
    embedding: Tensor = None

    def to_dict(self):
        return {k: v for k, v in asdict(self).items() if k != "embedding"}

    def calc_token(self):
        """

        Calculate the number of tokens for the turn.

        """
        if self.images is not None:
            self.input_tokens += calc_image_tokens(self.images)
        self.input_tokens += len(ENCODING.encode(self.prompt))
        self.output_tokens = len(ENCODING.encode(self.response))

    def __eq__(self, other):
        return self is other


class Agent:
    """

    An agent, defined by its instruction template and model.

    """

    def __init__(

        self,

        name: str,

        llm_mapping: dict[str, LLM | AsyncLLM],

        text_model: Optional[LLM | AsyncLLM] = None,

        record_cost: bool = False,

        config: Optional[dict] = None,

        env: Optional[Environment] = None,

    ):
        """

        Initialize the Agent.



        Args:

            name (str): The name of the role.

            env (Environment): The Jinja2 environment.

            record_cost (bool): Whether to record the token cost.

            llm (LLM): The language model.

            config (dict): The configuration.

            text_model (LLM): The text embedding model.

        """
        self.name = name
        self.config = config
        if self.config is None:
            with open(package_join("roles", f"{name}.yaml"), encoding="utf-8") as f:
                self.config = yaml.safe_load(f)
                assert isinstance(self.config, dict), "Agent config must be a dict"
        self.llm_mapping = llm_mapping
        self.llm = self.llm_mapping[self.config["use_model"]]
        self.model = self.llm.model
        self.record_cost = record_cost
        self.text_model = text_model
        self.return_json = self.config.get("return_json", False)
        self.system_message = self.config["system_prompt"]
        self.prompt_args = set(self.config["jinja_args"])
        self.env = env
        if self.env is None:
            self.env = Environment(undefined=StrictUndefined)
        self.template = self.env.from_string(self.config["template"])
        self.retry_template = Template(
            """The previous output is invalid, please carefully analyze the traceback and feedback information, correct errors happened before.

            feedback:

            {{feedback}}

            traceback:

            {{traceback}}

            Give your corrected output in the same format without including the previous output:

            """
        )
        self.input_tokens = 0
        self.output_tokens = 0
        self._history: list[Turn] = []
        run_args = self.config.get("run_args", {})
        self.llm.__call__ = partial(self.llm.__call__, **run_args)
        self.system_tokens = len(ENCODING.encode(self.system_message))

    def calc_cost(self, turns: list[Turn]):
        """

        Calculate the cost of a list of turns.

        """
        for turn in turns[:-1]:
            self.input_tokens += turn.input_tokens
            self.input_tokens += turn.output_tokens
        self.input_tokens += turns[-1].input_tokens
        self.output_tokens += turns[-1].output_tokens
        self.input_tokens += self.system_tokens

    def get_history(self, similar: int, recent: int, prompt: str):
        """

        Get the conversation history.

        """
        history = self._history[-recent:] if recent > 0 else []
        if similar > 0:
            assert isinstance(self.text_model, LLM), "text_model must be a LLM"
            embedding = self.text_model.get_embedding(prompt)
            history.sort(key=lambda x: cosine_similarity(embedding, x.embedding))
            for turn in history:
                if len(history) > similar + recent:
                    break
                if turn not in history:
                    history.append(turn)
        history.sort(key=lambda x: x.id)
        return history

    def retry(self, feedback: str, traceback: str, turn_id: int, error_idx: int):
        """

        Retry a failed turn with feedback and traceback.

        """
        assert error_idx > 0, "error_idx must be greater than 0"
        prompt = self.retry_template.render(feedback=feedback, traceback=traceback)
        history = [t for t in self._history if t.id == turn_id]
        history_msg = []
        for turn in history:
            history_msg.extend(turn.message)
        response, message = self.llm(
            prompt,
            history=history_msg,
            return_message=True,
        )
        turn = Turn(
            id=turn_id,
            prompt=prompt,
            response=response,
            message=message,
            retry=error_idx,
        )
        return self.__post_process__(response, history, turn)

    def to_sync(self):
        """

        Convert the agent to a synchronous agent.

        """
        return Agent(
            self.name,
            self.llm_mapping,
            self.text_model,
            self.record_cost,
            self.config,
            self.env,
        )

    def to_async(self):
        """

        Convert the agent to an asynchronous agent.

        """
        return AsyncAgent(
            self.name,
            self.llm_mapping,
            self.text_model,
            self.record_cost,
            self.config,
            self.env,
        )

    @property
    def next_turn_id(self):
        if len(self._history) == 0:
            return 0
        return max(t.id for t in self._history) + 1

    @property
    def history(self):
        return sorted(self._history, key=lambda x: (x.id, x.retry))

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}(name={self.name}, model={self.model})"

    def __call__(

        self,

        images: list[str] = None,

        recent: int = 0,

        similar: int = 0,

        **jinja_args,

    ):
        """

        Call the agent with prompt arguments.



        Args:

            images (list[str]): A list of image file paths.

            recent (int): The number of recent turns to include.

            similar (int): The number of similar turns to include.

            **jinja_args: Additional arguments for the Jinja2 template.



        Returns:

            The response from the role.

        """
        if isinstance(images, str):
            images = [images]
        assert self.prompt_args == set(
            jinja_args.keys()
        ), f"Invalid arguments, expected: {self.prompt_args}, got: {jinja_args.keys()}"
        prompt = self.template.render(**jinja_args)
        history = self.get_history(similar, recent, prompt)
        history_msg = []
        for turn in history:
            history_msg.extend(turn.message)

        response, message = self.llm(
            prompt,
            system_message=self.system_message,
            history=history_msg,
            images=images,
            return_message=True,
        )
        turn = Turn(
            id=self.next_turn_id,
            prompt=prompt,
            response=response,
            message=message,
            images=images,
        )
        return turn.id, self.__post_process__(response, history, turn, similar)

    def __post_process__(

        self, response: str, history: list[Turn], turn: Turn, similar: int = 0

    ) -> str | dict:
        """

        Post-process the response from the agent.

        """
        self._history.append(turn)
        if similar > 0:
            turn.embedding = self.text_model.get_embedding(turn.prompt)
        if self.record_cost:
            turn.calc_token()
            self.calc_cost(history + [turn])
        if self.return_json:
            response = get_json_from_response(response)
        return response


class AsyncAgent(Agent):
    """

    An agent, defined by its instruction template and model.

    """

    def __init__(

        self,

        name: str,

        llm_mapping: dict[str, AsyncLLM],

        text_model: Optional[AsyncLLM] = None,

        record_cost: bool = False,

        config: Optional[dict] = None,

        env: Optional[Environment] = None,

    ):
        super().__init__(name, llm_mapping, text_model, record_cost, config, env)
        self.llm = self.llm.to_async()

    async def retry(self, feedback: str, traceback: str, turn_id: int, error_idx: int):
        """

        Retry a failed turn with feedback and traceback.

        """
        assert error_idx > 0, "error_idx must be greater than 0"
        prompt = self.retry_template.render(feedback=feedback, traceback=traceback)
        history = [t for t in self._history if t.id == turn_id]
        history_msg = []
        for turn in history:
            history_msg.extend(turn.message)
        response, message = await self.llm(
            prompt,
            history=history_msg,
            return_message=True,
        )
        turn = Turn(
            id=turn_id,
            prompt=prompt,
            response=response,
            message=message,
            retry=error_idx,
        )
        return await self.__post_process__(response, history, turn)

    async def __call__(

        self,

        images: list[str] = None,

        recent: int = 0,

        similar: int = 0,

        **jinja_args,

    ):
        """

        Call the agent with prompt arguments.



        Args:

            images (list[str]): A list of image file paths.

            recent (int): The number of recent turns to include.

            similar (int): The number of similar turns to include.

            **jinja_args: Additional arguments for the Jinja2 template.



        Returns:

            The response from the role.

        """
        if isinstance(images, str):
            images = [images]
        assert self.prompt_args == set(
            jinja_args.keys()
        ), f"Invalid arguments, expected: {self.prompt_args}, got: {jinja_args.keys()}"
        prompt = self.template.render(**jinja_args)
        history = await self.get_history(similar, recent, prompt)
        history_msg = []
        for turn in history:
            history_msg.extend(turn.message)

        response, message = await self.llm(
            prompt,
            system_message=self.system_message,
            history=history_msg,
            images=images,
            return_message=True,
        )
        turn = Turn(
            id=self.next_turn_id,
            prompt=prompt,
            response=response,
            message=message,
            images=images,
        )
        return turn.id, await self.__post_process__(response, history, turn, similar)

    async def get_history(self, similar: int, recent: int, prompt: str):
        """

        Get the conversation history.

        """
        history = self._history[-recent:] if recent > 0 else []
        if similar > 0:
            embedding = await self.text_model.get_embedding(prompt)
            history.sort(key=lambda x: cosine_similarity(embedding, x.embedding))
            for turn in history:
                if len(history) > similar + recent:
                    break
                if turn not in history:
                    history.append(turn)
        history.sort(key=lambda x: x.id)
        return history

    async def __post_process__(

        self, response: str, history: list[Turn], turn: Turn, similar: int = 0

    ):
        """

        Post-process the response from the agent.

        """
        self._history.append(turn)
        if similar > 0:
            turn.embedding = await self.text_model.get_embedding(turn.prompt)
        if self.record_cost:
            turn.calc_token()
            self.calc_cost(history + [turn])
        if self.return_json:
            response = get_json_from_response(response)
        return response


def calc_image_tokens(images: list[str]):
    """

    Calculate the number of tokens for a list of images.

    """
    tokens = 0
    for image in images:
        with open(image, "rb") as f:
            width, height = Image.open(f).size
        if width > 1024 or height > 1024:
            if width > height:
                height = int(height * 1024 / width)
                width = 1024
            else:
                width = int(width * 1024 / height)
                height = 1024
        h = ceil(height / 512)
        w = ceil(width / 512)
        tokens += 85 + 170 * h * w
    return tokens