An enhanced list, used for intermidate representation of a prompt.
| 77 | |
| 78 | |
| 79 | class PromptList(list): |
| 80 | """An enhanced list, used for intermidate representation of a prompt.""" |
| 81 | |
| 82 | def format(self, **kwargs) -> PromptList: |
| 83 | """Replaces all instances of 'src' in the PromptList with 'dst'. |
| 84 | |
| 85 | Args: |
| 86 | src (str): The string to be replaced. |
| 87 | dst (PromptType): The string or PromptList to replace with. |
| 88 | |
| 89 | Returns: |
| 90 | PromptList: A new PromptList with 'src' replaced by 'dst'. |
| 91 | |
| 92 | Raises: |
| 93 | TypeError: If 'dst' is a PromptList and 'src' is in a dictionary's |
| 94 | 'prompt' key. |
| 95 | """ |
| 96 | new_list = PromptList() |
| 97 | for item in self: |
| 98 | if isinstance(item, Dict): |
| 99 | new_item = deepcopy(item) |
| 100 | if 'prompt' in item: |
| 101 | new_item['prompt'] = safe_format(item['prompt'], **kwargs) |
| 102 | new_list.append(new_item) |
| 103 | else: |
| 104 | new_list.append(safe_format(item, **kwargs)) |
| 105 | return new_list |
| 106 | |
| 107 | def replace(self, src: str, dst: Union[str, PromptList]) -> PromptList: |
| 108 | """Replaces all instances of 'src' in the PromptList with 'dst'. |
| 109 | |
| 110 | Args: |
| 111 | src (str): The string to be replaced. |
| 112 | dst (PromptType): The string or PromptList to replace with. |
| 113 | |
| 114 | Returns: |
| 115 | PromptList: A new PromptList with 'src' replaced by 'dst'. |
| 116 | |
| 117 | Raises: |
| 118 | TypeError: If 'dst' is a PromptList and 'src' is in a dictionary's |
| 119 | 'prompt' key. |
| 120 | """ |
| 121 | new_list = PromptList() |
| 122 | for item in self: |
| 123 | if isinstance(item, str): |
| 124 | if isinstance(dst, str): |
| 125 | new_list.append(item.replace(src, dst)) |
| 126 | elif isinstance(dst, PromptList): |
| 127 | split_str = item.split(src) |
| 128 | for i, split_item in enumerate(split_str): |
| 129 | if split_item: |
| 130 | new_list.append(split_item) |
| 131 | if i < len(split_str) - 1: |
| 132 | new_list += dst |
| 133 | elif isinstance(item, Dict): |
| 134 | new_item = deepcopy(item) |
| 135 | if 'prompt' in item: |
| 136 | if src in item['prompt']: |
no outgoing calls