aboutsummaryrefslogtreecommitdiff
path: root/autogpts/autogpt/autogpt/models/context_item.py
blob: e3bdf24a5c633a2d5e2723df78d4b02ac686cbd6 (plain)
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
import logging
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Optional

from pydantic import BaseModel, Field

from autogpt.file_storage.base import FileStorage
from autogpt.utils.file_operations_utils import decode_textual_file

logger = logging.getLogger(__name__)


class ContextItem(ABC):
    @property
    @abstractmethod
    def description(self) -> str:
        """Description of the context item"""
        ...

    @property
    @abstractmethod
    def source(self) -> Optional[str]:
        """A string indicating the source location of the context item"""
        ...

    @abstractmethod
    def get_content(self, workspace: FileStorage) -> str:
        """The content represented by the context item"""
        ...

    def fmt(self, workspace: FileStorage) -> str:
        return (
            f"{self.description} (source: {self.source})\n"
            "```\n"
            f"{self.get_content(workspace)}\n"
            "```"
        )


class FileContextItem(BaseModel, ContextItem):
    path: Path

    @property
    def description(self) -> str:
        return f"The current content of the file '{self.path}'"

    @property
    def source(self) -> str:
        return str(self.path)

    def get_content(self, workspace: FileStorage) -> str:
        with workspace.open_file(self.path, "r", True) as file:
            return decode_textual_file(file, self.path.suffix, logger)


class FolderContextItem(BaseModel, ContextItem):
    path: Path

    @property
    def description(self) -> str:
        return f"The contents of the folder '{self.path}' in the workspace"

    @property
    def source(self) -> str:
        return str(self.path)

    def get_content(self, workspace: FileStorage) -> str:
        files = [str(p) for p in workspace.list_files(self.path)]
        folders = [f"{str(p)}/" for p in workspace.list_folders(self.path)]
        items = folders + files
        items.sort()
        return "\n".join(items)


class StaticContextItem(BaseModel, ContextItem):
    item_description: str = Field(alias="description")
    item_source: Optional[str] = Field(alias="source")
    item_content: str = Field(alias="content")