coolprompt 0.0.20__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. coolprompt-0.0.20/LICENSE +201 -0
  2. coolprompt-0.0.20/PKG-INFO +128 -0
  3. coolprompt-0.0.20/README.md +94 -0
  4. coolprompt-0.0.20/coolprompt/__init__.py +0 -0
  5. coolprompt-0.0.20/coolprompt/assistant.py +228 -0
  6. coolprompt-0.0.20/coolprompt/evaluator/__init__.py +13 -0
  7. coolprompt-0.0.20/coolprompt/evaluator/evaluator.py +106 -0
  8. coolprompt-0.0.20/coolprompt/evaluator/metrics.py +279 -0
  9. coolprompt-0.0.20/coolprompt/language_model/__init__.py +0 -0
  10. coolprompt-0.0.20/coolprompt/language_model/llm.py +57 -0
  11. coolprompt-0.0.20/coolprompt/optimizer/__init__.py +0 -0
  12. coolprompt-0.0.20/coolprompt/optimizer/distill_prompt/__init__.py +5 -0
  13. coolprompt-0.0.20/coolprompt/optimizer/distill_prompt/candidate.py +79 -0
  14. coolprompt-0.0.20/coolprompt/optimizer/distill_prompt/distiller.py +263 -0
  15. coolprompt-0.0.20/coolprompt/optimizer/distill_prompt/generate.py +232 -0
  16. coolprompt-0.0.20/coolprompt/optimizer/distill_prompt/run.py +68 -0
  17. coolprompt-0.0.20/coolprompt/optimizer/distill_prompt/utils.py +62 -0
  18. coolprompt-0.0.20/coolprompt/optimizer/hype.py +27 -0
  19. coolprompt-0.0.20/coolprompt/optimizer/reflective_prompt/__init__.py +5 -0
  20. coolprompt-0.0.20/coolprompt/optimizer/reflective_prompt/evoluter.py +571 -0
  21. coolprompt-0.0.20/coolprompt/optimizer/reflective_prompt/prompt.py +103 -0
  22. coolprompt-0.0.20/coolprompt/optimizer/reflective_prompt/run.py +66 -0
  23. coolprompt-0.0.20/coolprompt/utils/__init__.py +0 -0
  24. coolprompt-0.0.20/coolprompt/utils/default.py +7 -0
  25. coolprompt-0.0.20/coolprompt/utils/logging_config.py +71 -0
  26. coolprompt-0.0.20/coolprompt/utils/parsing.py +35 -0
  27. coolprompt-0.0.20/coolprompt/utils/prompt_templates/__init__.py +0 -0
  28. coolprompt-0.0.20/coolprompt/utils/prompt_templates/default_templates.py +21 -0
  29. coolprompt-0.0.20/coolprompt/utils/prompt_templates/distillprompt_templates.py +78 -0
  30. coolprompt-0.0.20/coolprompt/utils/prompt_templates/hype_templates.py +82 -0
  31. coolprompt-0.0.20/coolprompt/utils/prompt_templates/reflective_templates.py +76 -0
  32. coolprompt-0.0.20/coolprompt/utils/var_validation.py +314 -0
  33. coolprompt-0.0.20/coolprompt.egg-info/PKG-INFO +128 -0
  34. coolprompt-0.0.20/coolprompt.egg-info/SOURCES.txt +38 -0
  35. coolprompt-0.0.20/coolprompt.egg-info/dependency_links.txt +1 -0
  36. coolprompt-0.0.20/coolprompt.egg-info/requires.txt +10 -0
  37. coolprompt-0.0.20/coolprompt.egg-info/top_level.txt +2 -0
  38. coolprompt-0.0.20/data/__init__.py +0 -0
  39. coolprompt-0.0.20/pyproject.toml +56 -0
  40. coolprompt-0.0.20/setup.cfg +4 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: coolprompt
3
+ Version: 0.0.20
4
+ Summary: Framework for automative prompting creation and optimization
5
+ Author-email: Nikita Kulin <serito1998@gmail.com>, Artur Khairullin <anderbrine05@gmail.com>, Alena Sitkina <sitkina.alena2017@yandex.ru>, Ernest Dyagin <tsenred@yandex.com>, Viktor Zhuravlev <viktor.zhuravlev1919@gmail.com>
6
+ Maintainer-email: Nikita Kulin <serito1998@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/CTLab-ITMO/CoolPrompt
9
+ Project-URL: Issues, https://github.com/CTLab-ITMO/CoolPrompt/issues
10
+ Project-URL: Documentation, https://github.com/CTLab-ITMO/CoolPrompt
11
+ Project-URL: Repository, https://github.com/CTLab-ITMO/CoolPrompt
12
+ Project-URL: Changelog, https://github.com/CTLab-ITMO/CoolPrompt/blob/master/CHANGELOG.md
13
+ Keywords: prompting,autoprompting,llm,transformers,prompt
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Operating System :: OS Independent
20
+ Requires-Python: >=3.12
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: evaluate>=0.3.0
24
+ Requires-Dist: tqdm
25
+ Requires-Dist: vllm>=0.5.0
26
+ Requires-Dist: urllib3>=2.0.0
27
+ Requires-Dist: nltk>=3.0.0
28
+ Requires-Dist: rouge_score>=0.1.0
29
+ Requires-Dist: scikit-learn>=1.3.0
30
+ Requires-Dist: langchain>=0.3.0
31
+ Requires-Dist: langchain-community>=0.3.0
32
+ Requires-Dist: langchain-core>=0.3.0
33
+ Dynamic: license-file
34
+
35
+ <p align="center">
36
+ <picture>
37
+ <source media="(prefers-color-scheme: light)" srcset="docs/images/logo_light.png">
38
+ <source media="(prefers-color-scheme: dark)" srcset="docs/images/logo_dark.png">
39
+ <img alt="CoolPrompt Logo" width="40%" height="40%">
40
+ </picture>
41
+ </p>
42
+
43
+ [![Release Notes](https://img.shields.io/github/release/CTLab-ITMO/CoolPrompt?style=flat-square)](https://github.com/CTLab-ITMO/CoolPrompt/releases)
44
+ [![PyPI - License](https://img.shields.io/github/license/CTLab-ITMO/CoolPrompt?style=BadgeStyleOptions.DEFAULT&logo=opensourceinitiative&logoColor=white&color=blue)](https://opensource.org/license/apache-2-0)
45
+ [![PyPI - Downloads](https://img.shields.io/pypi/dm/coolprompt?style=flat-square)](https://pypistats.org/packages/coolprompt)
46
+ [![GitHub star chart](https://img.shields.io/github/stars/CTLab-ITMO/CoolPrompt?style=flat-square)](https://star-history.com/#CTLab-ITMO/CoolPrompt)
47
+ [![Open Issues](https://img.shields.io/github/issues-raw/CTLab-ITMO/CoolPrompt?style=flat-square)](https://github.com/CTLab-ITMO/CoolPrompt/issues)
48
+ [![ITMO](https://raw.githubusercontent.com/aimclub/open-source-ops/43bb283758b43d75ec1df0a6bb4ae3eb20066323/badges/ITMO_badge.svg)](https://itmo.ru/)
49
+
50
+
51
+ <p align="center">
52
+ English |
53
+ <a href="https://github.com/CTLab-ITMO/CoolPrompt/blob/master/README.ru.md">Русский</a>
54
+ </p>
55
+
56
+ CoolPrompt is a framework for automative prompting creation and optimization.
57
+
58
+ ## Quick install
59
+ - Install with pip:
60
+ ```
61
+ pip install coolprompt
62
+ ```
63
+
64
+ ## Quick start
65
+
66
+ Import and initialize PromptTuner
67
+ ```
68
+ from coolprompt.assistant import PromptTuner
69
+ ```
70
+
71
+ - with default LLM
72
+ ```
73
+ prompt_tuner = PromptTuner(model=my_model)
74
+ ```
75
+
76
+ - Or initialize your own LLM by Langchain and use it
77
+ ```
78
+ my_model = VLLM(
79
+ model="Qwen/Qwen2.5-Coder-32B-Instruct",
80
+ trust_remote_code=True,
81
+ dtype='bfloat16',
82
+ )
83
+
84
+ prompt_tuner = PromptTuner(model=my_model)
85
+ ```
86
+
87
+ - List of available LLMs: https://python.langchain.com/docs/integrations/llms/
88
+
89
+ ## Running PromptTuner
90
+ - Run PromptTuner instance with initial prompt
91
+ ```
92
+ # Define an initial prompt
93
+ prompt = "Make a summarization of 2+2"
94
+
95
+ # Run a prompt optimisation
96
+ new_prompt = tuner.run(start_prompt=prompt)
97
+
98
+ # Get your new prompt
99
+ print(new_prompt)
100
+ ```
101
+
102
+ - including a dataset for prompt optimization and evaluation.
103
+ A provided dataset will be split by trainset and testset.
104
+ ```
105
+ sst2 = load_dataset("sst2")
106
+ class_dataset = sst2['train']['sentence']
107
+ class_targets = sst2['train']['label']
108
+
109
+ tuner.run(
110
+ start_prompt=class_start_prompt,
111
+ task="classification",
112
+ dataset=class_dataset,
113
+ target=class_targets,
114
+ metric="accuracy"
115
+ )
116
+ ```
117
+
118
+ - to get a final prompt and prompt metrics
119
+ ```
120
+ print("Final prompt:", tuner.final_prompt)
121
+ print("Start prompt metric:", tuner.init_metric)
122
+ print("Final prompt metric:", tuner.final_metric)
123
+ ```
124
+ - This also works for generation tasks
125
+
126
+ ## More about project
127
+ - Explore the variety of autoprompting methods with PromptTuner: CoolPrompt currently support HyPE, DistillPrompt, ReflectivePrompt. You can choose method via corresponding argument `method` in `tuner.run`
128
+ - See more examples in <a href="https://github.com/CTLab-ITMO/CoolPrompt/blob/master/notebooks/examples">notebooks</a> to familiarize yourself with our framework
@@ -0,0 +1,94 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: light)" srcset="docs/images/logo_light.png">
4
+ <source media="(prefers-color-scheme: dark)" srcset="docs/images/logo_dark.png">
5
+ <img alt="CoolPrompt Logo" width="40%" height="40%">
6
+ </picture>
7
+ </p>
8
+
9
+ [![Release Notes](https://img.shields.io/github/release/CTLab-ITMO/CoolPrompt?style=flat-square)](https://github.com/CTLab-ITMO/CoolPrompt/releases)
10
+ [![PyPI - License](https://img.shields.io/github/license/CTLab-ITMO/CoolPrompt?style=BadgeStyleOptions.DEFAULT&logo=opensourceinitiative&logoColor=white&color=blue)](https://opensource.org/license/apache-2-0)
11
+ [![PyPI - Downloads](https://img.shields.io/pypi/dm/coolprompt?style=flat-square)](https://pypistats.org/packages/coolprompt)
12
+ [![GitHub star chart](https://img.shields.io/github/stars/CTLab-ITMO/CoolPrompt?style=flat-square)](https://star-history.com/#CTLab-ITMO/CoolPrompt)
13
+ [![Open Issues](https://img.shields.io/github/issues-raw/CTLab-ITMO/CoolPrompt?style=flat-square)](https://github.com/CTLab-ITMO/CoolPrompt/issues)
14
+ [![ITMO](https://raw.githubusercontent.com/aimclub/open-source-ops/43bb283758b43d75ec1df0a6bb4ae3eb20066323/badges/ITMO_badge.svg)](https://itmo.ru/)
15
+
16
+
17
+ <p align="center">
18
+ English |
19
+ <a href="https://github.com/CTLab-ITMO/CoolPrompt/blob/master/README.ru.md">Русский</a>
20
+ </p>
21
+
22
+ CoolPrompt is a framework for automative prompting creation and optimization.
23
+
24
+ ## Quick install
25
+ - Install with pip:
26
+ ```
27
+ pip install coolprompt
28
+ ```
29
+
30
+ ## Quick start
31
+
32
+ Import and initialize PromptTuner
33
+ ```
34
+ from coolprompt.assistant import PromptTuner
35
+ ```
36
+
37
+ - with default LLM
38
+ ```
39
+ prompt_tuner = PromptTuner(model=my_model)
40
+ ```
41
+
42
+ - Or initialize your own LLM by Langchain and use it
43
+ ```
44
+ my_model = VLLM(
45
+ model="Qwen/Qwen2.5-Coder-32B-Instruct",
46
+ trust_remote_code=True,
47
+ dtype='bfloat16',
48
+ )
49
+
50
+ prompt_tuner = PromptTuner(model=my_model)
51
+ ```
52
+
53
+ - List of available LLMs: https://python.langchain.com/docs/integrations/llms/
54
+
55
+ ## Running PromptTuner
56
+ - Run PromptTuner instance with initial prompt
57
+ ```
58
+ # Define an initial prompt
59
+ prompt = "Make a summarization of 2+2"
60
+
61
+ # Run a prompt optimisation
62
+ new_prompt = tuner.run(start_prompt=prompt)
63
+
64
+ # Get your new prompt
65
+ print(new_prompt)
66
+ ```
67
+
68
+ - including a dataset for prompt optimization and evaluation.
69
+ A provided dataset will be split by trainset and testset.
70
+ ```
71
+ sst2 = load_dataset("sst2")
72
+ class_dataset = sst2['train']['sentence']
73
+ class_targets = sst2['train']['label']
74
+
75
+ tuner.run(
76
+ start_prompt=class_start_prompt,
77
+ task="classification",
78
+ dataset=class_dataset,
79
+ target=class_targets,
80
+ metric="accuracy"
81
+ )
82
+ ```
83
+
84
+ - to get a final prompt and prompt metrics
85
+ ```
86
+ print("Final prompt:", tuner.final_prompt)
87
+ print("Start prompt metric:", tuner.init_metric)
88
+ print("Final prompt metric:", tuner.final_metric)
89
+ ```
90
+ - This also works for generation tasks
91
+
92
+ ## More about project
93
+ - Explore the variety of autoprompting methods with PromptTuner: CoolPrompt currently support HyPE, DistillPrompt, ReflectivePrompt. You can choose method via corresponding argument `method` in `tuner.run`
94
+ - See more examples in <a href="https://github.com/CTLab-ITMO/CoolPrompt/blob/master/notebooks/examples">notebooks</a> to familiarize yourself with our framework
File without changes
@@ -0,0 +1,228 @@
1
+ from pathlib import Path
2
+ from typing import Iterable
3
+ from langchain_core.language_models.base import BaseLanguageModel
4
+ from sklearn.model_selection import train_test_split
5
+
6
+ from coolprompt.evaluator import Evaluator, validate_metric
7
+ from coolprompt.language_model.llm import DefaultLLM
8
+ from coolprompt.optimizer.hype import hype_optimizer
9
+ from coolprompt.optimizer.reflective_prompt import reflectiveprompt
10
+ from coolprompt.optimizer.distill_prompt.run import distillprompt
11
+ from coolprompt.utils.logging_config import logger, set_verbose, setup_logging
12
+ from coolprompt.utils.var_validation import (
13
+ validate_model,
14
+ validate_task,
15
+ validate_method,
16
+ validate_run,
17
+ validate_verbose,
18
+ )
19
+ from coolprompt.utils.prompt_templates.default_templates import (
20
+ CLASSIFICATION_TASK_TEMPLATE,
21
+ GENERATION_TASK_TEMPLATE,
22
+ )
23
+ from coolprompt.utils.prompt_templates.hype_templates import (
24
+ CLASSIFICATION_TASK_TEMPLATE_HYPE,
25
+ GENERATION_TASK_TEMPLATE_HYPE,
26
+ )
27
+
28
+
29
+ class PromptTuner:
30
+ """Prompt optimization tool supporting multiple methods."""
31
+
32
+ TEMPLATE_MAP = {
33
+ ("classification", "hype"): CLASSIFICATION_TASK_TEMPLATE_HYPE,
34
+ ("classification", "reflective"): CLASSIFICATION_TASK_TEMPLATE,
35
+ ("classification", "distill"): CLASSIFICATION_TASK_TEMPLATE,
36
+ ("generation", "hype"): GENERATION_TASK_TEMPLATE_HYPE,
37
+ ("generation", "reflective"): GENERATION_TASK_TEMPLATE,
38
+ ("generation", "distill"): GENERATION_TASK_TEMPLATE,
39
+ }
40
+
41
+ def __init__(
42
+ self,
43
+ model: BaseLanguageModel = None,
44
+ logs_dir: str | Path = None,
45
+ ) -> None:
46
+ """Initializes the tuner with a LangChain-compatible language model.
47
+
48
+ Args:
49
+ model (BaseLanguageModel): Any LangChain BaseLanguageModel instance
50
+ which supports invoke(str) -> str.
51
+ Will use DefaultLLM if not provided.
52
+ logs_dir (str | Path, optional): logs saving directory.
53
+ Defaults to None.
54
+ """
55
+ setup_logging(logs_dir)
56
+ self._model = model or DefaultLLM.init()
57
+ self.init_metric = None
58
+ self.init_prompt = None
59
+ self.final_metric = None
60
+ self.final_prompt = None
61
+
62
+ logger.info(f"Validating the model: {self._model.__class__.__name__}")
63
+ validate_model(self._model)
64
+ logger.info(
65
+ "PromptTuner successfully initialized with "
66
+ f"model: {self._model.__class__.__name__}"
67
+ )
68
+
69
+ def get_task_prompt_template(self, task: str, method: str) -> str:
70
+ """Returns the prompt template for the given task.
71
+
72
+ Args:
73
+ task (str):
74
+ The type of task, either "classification" or "generation".
75
+ method (str):
76
+ Optimization method to use.
77
+ Available methods are: ['hype', 'reflective', 'distill']
78
+
79
+ Returns:
80
+ str: The prompt template for the given task.
81
+ """
82
+
83
+ logger.debug(
84
+ f"Getting prompt template for {task} task and {method} method"
85
+ )
86
+ validate_task(task)
87
+ validate_method(method)
88
+ return self.TEMPLATE_MAP[(task, method)]
89
+
90
+ def run(
91
+ self,
92
+ start_prompt: str,
93
+ task: str = "generation",
94
+ dataset: Iterable[str] = None,
95
+ target: Iterable[str] | Iterable[int] = None,
96
+ method: str = "hype",
97
+ metric: str = None,
98
+ problem_description: str = None,
99
+ validation_size: float = 0.25,
100
+ verbose: int = 1,
101
+ **kwargs,
102
+ ) -> str:
103
+ """Optimizes prompts using provided model.
104
+
105
+ Args:
106
+ start_prompt (str): Initial prompt text to optimize.
107
+ task (str):
108
+ Type of task to optimize for (classification or generation).
109
+ Defaults to generation.
110
+ dataset (Iterable):
111
+ Dataset iterable object for autoprompting optimization.
112
+ target (Iterable):
113
+ Target iterable object for autoprompting optimization.
114
+ method (str): Optimization method to use.
115
+ Available methods are: ['hype', 'reflective', 'distill']
116
+ Defaults to hype.
117
+ metric (str): Metric to use for optimization.
118
+ problem_description (str): a string that contains
119
+ short description of problem to optimize.
120
+ validation_size (float):
121
+ A float that must be between 0.0 and 1.0 and
122
+ represent the proportion of the dataset
123
+ to include in the validation split.
124
+ Defaults to 0.25.
125
+ verbose (int): Parameter for logging configuration:
126
+ 0 - no logging
127
+ 1 - steps logging
128
+ 2 - steps and prompts logging
129
+ **kwargs (dict[str, Any]): other key-word arguments.
130
+
131
+ Returns:
132
+ final_prompt: str - The resulting optimized prompt
133
+ after applying the selected method.
134
+
135
+ Raises:
136
+ ValueError: If an invalid task type is provided.
137
+ ValueError: If a problem description is not provided
138
+ for ReflectivePrompt.
139
+
140
+ Note:
141
+ Uses HyPE optimization
142
+ when dataset or method parameters are not provided.
143
+
144
+ Uses default metric for the task type
145
+ if metric parameter is not provided:
146
+ f1 for classisfication, meteor for generation.
147
+
148
+ if dataset is not None, you can find evaluation results
149
+ in self.init_metric and self.final_metric
150
+ """
151
+ if verbose is not None:
152
+ validate_verbose(verbose)
153
+ set_verbose(verbose)
154
+
155
+ logger.info("Validating args for PromptTuner running")
156
+ validate_run(
157
+ start_prompt,
158
+ task,
159
+ dataset,
160
+ target,
161
+ method,
162
+ problem_description,
163
+ validation_size,
164
+ )
165
+ metric = validate_metric(task, metric)
166
+ evaluator = Evaluator(self._model, metric)
167
+ final_prompt = ""
168
+
169
+ logger.info("=== Starting Prompt Optimization ===")
170
+ logger.info(f"Method: {method}, Task: {task}")
171
+ logger.info(f"Metric: {metric}, Validation size: {validation_size}")
172
+ if dataset:
173
+ logger.info(f"Dataset: {len(dataset)} samples")
174
+ else:
175
+ logger.info("No dataset provided")
176
+ if target:
177
+ logger.info(f"Target: {len(target)} samples")
178
+ else:
179
+ logger.info("No target provided")
180
+ if kwargs:
181
+ logger.debug(f"Additional kwargs: {kwargs}")
182
+
183
+ if method == "hype":
184
+ final_prompt = hype_optimizer(self._model, start_prompt)
185
+ elif method == "reflective":
186
+ dataset_split = train_test_split(
187
+ dataset, target, test_size=validation_size
188
+ )
189
+ final_prompt = reflectiveprompt(
190
+ model=self._model,
191
+ dataset_split=dataset_split,
192
+ evaluator=evaluator,
193
+ task=task,
194
+ problem_description=problem_description,
195
+ initial_prompt=start_prompt,
196
+ **kwargs,
197
+ )
198
+ elif method == "distill":
199
+ dataset_split = train_test_split(dataset, target, test_size=0.25)
200
+ final_prompt = distillprompt(
201
+ model=self._model,
202
+ dataset_split=dataset_split,
203
+ evaluator=evaluator,
204
+ task=task,
205
+ initial_prompt=start_prompt,
206
+ **kwargs,
207
+ )
208
+
209
+ logger.debug(f"Final prompt:\n{final_prompt}")
210
+ if dataset is not None:
211
+ template = self.get_task_prompt_template(task, method)
212
+ logger.info(f"Evaluating on given dataset for {task} task...")
213
+ self.init_metric = evaluator.evaluate(
214
+ start_prompt, dataset, target, task, template
215
+ )
216
+ self.final_metric = evaluator.evaluate(
217
+ final_prompt, dataset, target, task, template
218
+ )
219
+ logger.info(
220
+ f"Initial {metric} score: {self.init_metric}, "
221
+ f"final {metric} score: {self.final_metric}"
222
+ )
223
+
224
+ self.init_prompt = start_prompt
225
+ self.final_prompt = final_prompt
226
+
227
+ logger.info("=== Prompt Optimization Completed ===")
228
+ return final_prompt
@@ -0,0 +1,13 @@
1
+ from coolprompt.evaluator.evaluator import Evaluator
2
+ from coolprompt.evaluator.metrics import (
3
+ CLASSIFICATION_METRICS,
4
+ GENERATION_METRICS,
5
+ validate_metric
6
+ )
7
+
8
+ __all__ = [
9
+ 'Evaluator',
10
+ 'CLASSIFICATION_METRICS',
11
+ 'GENERATION_METRICS',
12
+ 'validate_metric'
13
+ ]