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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import google.generativeai as genai
|
3 |
+
import time
|
4 |
+
import yaml
|
5 |
+
from typing import Any, Generator, Tuple
|
6 |
+
|
7 |
+
# Wstaw swój klucz API Gemini tutaj
|
8 |
+
GEMINI_API_KEY = "TWÓJ_KLUCZ_API_GEMINI"
|
9 |
+
|
10 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
11 |
+
|
12 |
+
generation_config = {
|
13 |
+
"temperature": 1,
|
14 |
+
"top_p": 0.95,
|
15 |
+
"top_k": 64,
|
16 |
+
"max_output_tokens": 8192,
|
17 |
+
"response_mime_type": "text/plain",
|
18 |
+
}
|
19 |
+
|
20 |
+
system_message = """Jesteś "Nauczycielem Promptów", asystentem, który pomaga w pisaniu lepszych promptów. Twoim zadaniem jest ulepszanie promptów, aby były bardziej precyzyjne i dawały lepsze wyniki.
|
21 |
+
Kiedy otrzymasz prośbę o ulepszenie promptu, odpowiedz tylko ulepszoną wersją promptu.
|
22 |
+
Kiedy otrzymasz prośbę o wyjaśnienie zmian, opisz je w prosty i zrozumiały sposób."""
|
23 |
+
|
24 |
+
inital_usr_text = "Chcę nauczyć się pisać lepsze prompty! Pomożesz mi? 🤔📚"
|
25 |
+
|
26 |
+
initial_bot_text = """Witaj! 👋 Jestem Nauczycielem Promptów - pomogę Ci ulepszyć Twoje prompty! 🤖🎓
|
27 |
+
|
28 |
+
Zobacz, jak to działa:
|
29 |
+
|
30 |
+
1. Wybierz, co chcesz zmienić w swoim prompcie.
|
31 |
+
2. Wpisz prompt - co chcesz, żeby komputer zrobił?
|
32 |
+
3. Kliknij "✨Ulepsz prompt!", a ja postaram się go ulepszyć!
|
33 |
+
4. Kliknij "Wyjaśnij zmiany 💡", jeśli chcesz zrozumieć, co zmieniłem.
|
34 |
+
|
35 |
+
Możesz też zobaczyć przykłady na dole strony - kliknij na któryś, żeby go wybrać. 🖱️👇"""
|
36 |
+
|
37 |
+
|
38 |
+
class Metaprompt(BaseModel):
|
39 |
+
explanation: str
|
40 |
+
example_prompt: str
|
41 |
+
example_prompt_explanation: str
|
42 |
+
name: str
|
43 |
+
template: str
|
44 |
+
|
45 |
+
def __str__(self):
|
46 |
+
return f"✨**{self.name}**\n\n📝 *{self.explanation}*\n\n📚 **Przykładowy Prompt:** {self.example_prompt}\n\n📖 **Wyjaśnienie Przykładowego Promptu:** {self.example_prompt_explanation}"
|
47 |
+
|
48 |
+
|
49 |
+
class MetapromptLibrary(BaseModel):
|
50 |
+
Metaprompts: list[Metaprompt]
|
51 |
+
|
52 |
+
|
53 |
+
def read_and_validate(file_path: str = "metaprompts.yml"):
|
54 |
+
try:
|
55 |
+
with open(file_path, "r") as file:
|
56 |
+
data = yaml.safe_load(file)
|
57 |
+
validated_data = MetapromptLibrary(**data)
|
58 |
+
return validated_data
|
59 |
+
except FileNotFoundError:
|
60 |
+
return "Error: The file was not found."
|
61 |
+
except yaml.YAMLError as e:
|
62 |
+
return f"Error parsing YAML: {e}"
|
63 |
+
except ValidationError as e:
|
64 |
+
return f"Validation error: {e}"
|
65 |
+
|
66 |
+
|
67 |
+
metaprompts = read_and_validate().Metaprompts
|
68 |
+
metaprompts_dict = {mp.name: mp for mp in metaprompts}
|
69 |
+
|
70 |
+
|
71 |
+
def get_llm():
|
72 |
+
return genai.GenerativeModel(
|
73 |
+
model_name="gemini-1.5-pro-exp-0827",
|
74 |
+
generation_config=generation_config,
|
75 |
+
)
|
76 |
+
|
77 |
+
|
78 |
+
def explain_metaprompt(explanation_history, metaprompt):
|
79 |
+
explanation_history += [
|
80 |
+
[f"❓Jak **{metaprompt.capitalize()}** ulepsza mój prompt? 💡🚀", ""]
|
81 |
+
]
|
82 |
+
answer = f"""{metaprompts_dict[metaprompt]}"""
|
83 |
+
|
84 |
+
for character in answer:
|
85 |
+
explanation_history[-1][1] += character
|
86 |
+
time.sleep(0.001)
|
87 |
+
yield explanation_history
|
88 |
+
|
89 |
+
|
90 |
+
def update_widgets(metaprompt, feedback):
|
91 |
+
button_variant = "primary" if metaprompt else "secondary"
|
92 |
+
feedback_visibility = True if metaprompt == "Dodaj uwagi" else False
|
93 |
+
return [
|
94 |
+
gr.Button(variant=button_variant),
|
95 |
+
gr.Textbox(
|
96 |
+
visible=feedback_visibility, value=feedback if feedback_visibility else ""
|
97 |
+
),
|
98 |
+
]
|
99 |
+
|
100 |
+
|
101 |
+
def explain_improvement(
|
102 |
+
prompt, metaprompt, improved_prompt, prompt_teacher
|
103 |
+
):
|
104 |
+
llm = get_llm()
|
105 |
+
|
106 |
+
chat_session = llm.start_chat(
|
107 |
+
history=[
|
108 |
+
{"author": "user", "content": system_message},
|
109 |
+
{"author": "user", "content": f"""Następujący prompt:
|
110 |
+
---
|
111 |
+
{prompt}
|
112 |
+
---
|
113 |
+
został ulepszony za pomocą metapromptu:
|
114 |
+
---
|
115 |
+
{metaprompt}
|
116 |
+
---
|
117 |
+
W rezultacie powstała następująca ulepszona wersja:
|
118 |
+
---
|
119 |
+
{improved_prompt}
|
120 |
+
---
|
121 |
+
Zwięźle wyjaśnij ulepszenie."""},
|
122 |
+
]
|
123 |
+
)
|
124 |
+
response = chat_session.send_message("")
|
125 |
+
|
126 |
+
prompt_teacher += [
|
127 |
+
[
|
128 |
+
"❓Czy możesz proszę **wyjaśnić** **ulepszony prompt**? 📝✨",
|
129 |
+
"**Wyjaśnienie**:\n\n",
|
130 |
+
]
|
131 |
+
]
|
132 |
+
|
133 |
+
prompt_teacher[-1][1] += response.text
|
134 |
+
yield prompt_teacher
|
135 |
+
|
136 |
+
|
137 |
+
def improve_prompt(
|
138 |
+
prompt: str,
|
139 |
+
metaprompt: str,
|
140 |
+
feedback: str | None,
|
141 |
+
explanation_history,
|
142 |
+
) -> Generator[Tuple[str, str], Any, Any]:
|
143 |
+
metaprompt_template = metaprompts_dict[metaprompt].template
|
144 |
+
|
145 |
+
llm = get_llm()
|
146 |
+
chat_session = llm.start_chat(
|
147 |
+
history=[
|
148 |
+
{"author": "user", "content": system_message},
|
149 |
+
{"author": "user", "content": metaprompt_template},
|
150 |
+
]
|
151 |
+
)
|
152 |
+
|
153 |
+
explanation_history += [
|
154 |
+
[
|
155 |
+
f"""
|
156 |
+
**📝 Proszę ulepszyć następujący Prompt:**
|
157 |
+
```
|
158 |
+
{prompt}
|
159 |
+
```
|
160 |
+
""",
|
161 |
+
"**Ulepszony Prompt**:\n\n",
|
162 |
+
]
|
163 |
+
]
|
164 |
+
|
165 |
+
improved_prompt = ""
|
166 |
+
|
167 |
+
input_message = {"prompt": prompt, "feedback": feedback} if feedback else {"prompt": prompt}
|
168 |
+
input_str = ""
|
169 |
+
for key, value in input_message.items():
|
170 |
+
input_str += f"{key}: {value}\n"
|
171 |
+
|
172 |
+
response = chat_session.send_message(input_str)
|
173 |
+
|
174 |
+
explanation_history[-1][1] += response.text
|
175 |
+
improved_prompt += response.text
|
176 |
+
yield improved_prompt, explanation_history
|
177 |
+
|
178 |
+
|
179 |
+
def robustly_improve_prompt(*args, **kwargs):
|
180 |
+
history = args[3]
|
181 |
+
user_txt = "Ups, wystąpił błąd!💥 Co powinienem zrobić?"
|
182 |
+
try:
|
183 |
+
yield from improve_prompt(*args, **kwargs)
|
184 |
+
except Exception as e:
|
185 |
+
msg = "\n\nSpróbuj jeszcze raz! Upewnij się, że wszystko jest dobrze wpisane. 🤔"
|
186 |
+
try:
|
187 |
+
error_msg = e.body["message"]
|
188 |
+
error_msg += msg
|
189 |
+
history += [[user_txt, error_msg]]
|
190 |
+
gr.Warning(error_msg)
|
191 |
+
yield "", history
|
192 |
+
except Exception as ee:
|
193 |
+
error_msg = str(e) + msg
|
194 |
+
history += [[user_txt, error_msg]]
|
195 |
+
gr.Warning(error_msg)
|
196 |
+
yield "", history
|
197 |
+
|
198 |
+
|
199 |
+
with gr.Blocks(title="Nauczyciel Promptów", theme=gr.themes.Soft()) as gradio_app:
|
200 |
+
gr.Markdown("### 🤖 Nauczyciel Promptów - Pomocnik w pisaniu lepszych promptów! 📝✨")
|
201 |
+
with gr.Accordion("ℹ️ Co to są prompty?", open=True):
|
202 |
+
gr.Markdown(
|
203 |
+
"Prompty to instrukcje, które dajemy komputerowi, aby wykonał dla nas jakieś zadanie. Im lepszy prompt, tym lepszy wynik! 😊"
|
204 |
+
)
|
205 |
+
with gr.Row():
|
206 |
+
with gr.Column(scale=2):
|
207 |
+
prompt_teacher = gr.Chatbot(
|
208 |
+
height=580,
|
209 |
+
label="Nauczyciel Promptów",
|
210 |
+
show_copy_button=True,
|
211 |
+
value=[[inital_usr_text, initial_bot_text]],
|
212 |
+
avatar_images=("thinking.svg", "robot.svg"),
|
213 |
+
)
|
214 |
+
prompt = gr.Textbox(
|
215 |
+
label="Prompt",
|
216 |
+
interactive=True,
|
217 |
+
placeholder="Wpisz swój prompt - co chcesz, żeby komputer zrobił?",
|
218 |
+
value="Napisz krótkie streszczenie bitwy pod Grunwaldem.",
|
219 |
+
show_copy_button=True,
|
220 |
+
)
|
221 |
+
with gr.Row():
|
222 |
+
explain_btn = gr.Button(
|
223 |
+
"Wyjaśnij zmiany 💡",
|
224 |
+
variant="primary",
|
225 |
+
visible=False,
|
226 |
+
)
|
227 |
+
replace_btn = gr.Button(
|
228 |
+
"Zatwierdź zmiany 👍",
|
229 |
+
variant="primary",
|
230 |
+
visible=False,
|
231 |
+
)
|
232 |
+
with gr.Row():
|
233 |
+
improve_btn = gr.Button("✨Ulepsz prompt!", variant="primary")
|
234 |
+
with gr.Column(scale=1):
|
235 |
+
metaprompt = gr.Radio(
|
236 |
+
label="Ulepszenia",
|
237 |
+
info="Wybierz, jak chcesz ulepszyć swój prompt.",
|
238 |
+
value="Dodaj szczegóły",
|
239 |
+
choices=[mp.name.replace("_", " ").capitalize() for mp in metaprompts],
|
240 |
+
)
|
241 |
+
feedback = gr.Textbox(
|
242 |
+
label="Twoje uwagi",
|
243 |
+
info="Napisz, co chcesz zmienić w prompcie.",
|
244 |
+
visible=False,
|
245 |
+
)
|
246 |
+
|
247 |
+
improved_prompt = gr.Textbox(label="Ulepszony Prompt", visible=False)
|
248 |
+
examples = gr.Examples(
|
249 |
+
examples=[[mp.name, mp.example_prompt] for mp in metaprompts],
|
250 |
+
examples_per_page=100,
|
251 |
+
inputs=[metaprompt, prompt],
|
252 |
+
)
|
253 |
+
|
254 |
+
metaprompt.change(
|
255 |
+
fn=update_widgets,
|
256 |
+
inputs=[metaprompt, feedback],
|
257 |
+
outputs=[improve_btn, feedback],
|
258 |
+
).success(
|
259 |
+
lambda: [gr.Button(visible=False), gr.Button(visible=False)],
|
260 |
+
None,
|
261 |
+
[replace_btn, explain_btn],
|
262 |
+
).success(
|
263 |
+
fn=explain_metaprompt,
|
264 |
+
inputs=[prompt_teacher, metaprompt],
|
265 |
+
outputs=[prompt_teacher],
|
266 |
+
)
|
267 |
+
improve_btn.click(
|
268 |
+
fn=robustly_improve_prompt,
|
269 |
+
inputs=[
|
270 |
+
prompt,
|
271 |
+
metaprompt,
|
272 |
+
feedback,
|
273 |
+
prompt_teacher,
|
274 |
+
],
|
275 |
+
outputs=[improved_prompt, prompt_teacher],
|
276 |
+
).success(
|
277 |
+
lambda: [gr.Button(visible=True), gr.Button(visible=True)],
|
278 |
+
None,
|
279 |
+
[replace_btn, explain_btn],
|
280 |
+
)
|
281 |
+
|
282 |
+
explain_btn.click(lambda: gr.Button(visible=False), None, explain_btn).success(
|
283 |
+
explain_improvement,
|
284 |
+
[
|
285 |
+
prompt,
|
286 |
+
metaprompt,
|
287 |
+
improved_prompt,
|
288 |
+
prompt_teacher,
|
289 |
+
],
|
290 |
+
prompt_teacher,
|
291 |
+
)
|
292 |
+
|
293 |
+
replace_btn.click(lambda x: x, improved_prompt, prompt).success(
|
294 |
+
lambda: [gr.Button(visible=False), gr.Button(visible=False)],
|
295 |
+
None,
|
296 |
+
[replace_btn, explain_btn],
|
297 |
+
)
|
298 |
+
|
299 |
+
if __name__ == "__main__":
|
300 |
+
gradio_app.queue(default_concurrency_limit=10).launch(favicon_path="robot.svg")
|