1"""
208. ํ๋กฌํํธ ์์ง๋์ด๋ง ์์
3
4๋ค์ํ ํ๋กฌํํ
๊ธฐ๋ฒ๊ณผ ์ต์ ํ ์ ๋ต
5"""
6
7print("=" * 60)
8print("ํ๋กฌํํธ ์์ง๋์ด๋ง")
9print("=" * 60)
10
11
12# ============================================
13# 1. ํ๋กฌํํธ ํ
ํ๋ฆฟ ํด๋์ค
14# ============================================
15print("\n[1] ํ๋กฌํํธ ํ
ํ๋ฆฟ")
16print("-" * 40)
17
18class PromptTemplate:
19 """์ฌ์ฌ์ฉ ๊ฐ๋ฅํ ํ๋กฌํํธ ํ
ํ๋ฆฟ"""
20
21 def __init__(self, template: str, input_variables: list = None):
22 self.template = template
23 self.input_variables = input_variables or []
24
25 def format(self, **kwargs) -> str:
26 """๋ณ์๋ฅผ ์ฑ์ ํ๋กฌํํธ ์์ฑ"""
27 return self.template.format(**kwargs)
28
29 @classmethod
30 def from_file(cls, path: str):
31 """ํ์ผ์์ ํ
ํ๋ฆฟ ๋ก๋"""
32 with open(path, 'r', encoding='utf-8') as f:
33 return cls(f.read())
34
35# ๊ธฐ๋ณธ ํ
ํ๋ฆฟ
36basic_template = PromptTemplate(
37 template="""You are a {role}.
38Task: {task}
39Input: {input}
40Output:""",
41 input_variables=["role", "task", "input"]
42)
43
44prompt = basic_template.format(
45 role="helpful assistant",
46 task="translate to Korean",
47 input="Hello, world!"
48)
49print("๊ธฐ๋ณธ ํ
ํ๋ฆฟ ์์:")
50print(prompt)
51
52
53# ============================================
54# 2. Zero-shot vs Few-shot
55# ============================================
56print("\n[2] Zero-shot vs Few-shot")
57print("-" * 40)
58
59# Zero-shot ํ๋กฌํํธ
60zero_shot = """๋ค์ ๋ฆฌ๋ทฐ์ ๊ฐ์ฑ์ ๋ถ์ํด์ฃผ์ธ์.
61๋ฆฌ๋ทฐ: "์ด ์ํ๋ ์ ๋ง ์ง๋ฃจํ์ด์."
62๊ฐ์ฑ:"""
63
64print("Zero-shot:")
65print(zero_shot)
66
67# Few-shot ํ๋กฌํํธ
68few_shot = """๋ค์ ๋ฆฌ๋ทฐ์ ๊ฐ์ฑ์ ๋ถ์ํด์ฃผ์ธ์.
69
70๋ฆฌ๋ทฐ: "์ ๋ง ์ฌ๋ฏธ์๋ ์ํ์์ด์!"
71๊ฐ์ฑ: ๊ธ์
72
73๋ฆฌ๋ทฐ: "์ต์
์ ์ํ, ์๊ฐ ๋ญ๋น"
74๊ฐ์ฑ: ๋ถ์
75
76๋ฆฌ๋ทฐ: "๊ทธ๋ฅ ๊ทธ๋ฌ์ด์"
77๊ฐ์ฑ: ์ค๋ฆฝ
78
79๋ฆฌ๋ทฐ: "์ด ์ํ๋ ์ ๋ง ์ง๋ฃจํ์ด์."
80๊ฐ์ฑ:"""
81
82print("\nFew-shot:")
83print(few_shot)
84
85
86# ============================================
87# 3. Few-shot ํ๋กฌํํธ ๋น๋
88# ============================================
89print("\n[3] Few-shot ํ๋กฌํํธ ๋น๋")
90print("-" * 40)
91
92class FewShotPromptTemplate:
93 """Few-shot ํ๋กฌํํธ ์์ฑ๊ธฐ"""
94
95 def __init__(
96 self,
97 examples: list,
98 example_template: str,
99 prefix: str = "",
100 suffix: str = "",
101 separator: str = "\n\n"
102 ):
103 self.examples = examples
104 self.example_template = example_template
105 self.prefix = prefix
106 self.suffix = suffix
107 self.separator = separator
108
109 def format(self, **kwargs) -> str:
110 # ์์๋ค ํฌ๋งทํ
111 formatted_examples = [
112 self.example_template.format(**ex)
113 for ex in self.examples
114 ]
115
116 # ์กฐํฉ
117 parts = []
118 if self.prefix:
119 parts.append(self.prefix)
120 parts.extend(formatted_examples)
121 if self.suffix:
122 parts.append(self.suffix.format(**kwargs))
123
124 return self.separator.join(parts)
125
126# ๊ฐ์ฑ ๋ถ์ Few-shot
127sentiment_examples = [
128 {"text": "์ ๋ง ์ข์์!", "sentiment": "๊ธ์ "},
129 {"text": "๋ณ๋ก์์", "sentiment": "๋ถ์ "},
130 {"text": "๊ทธ๋ฅ ๋ณดํต์ด์์", "sentiment": "์ค๋ฆฝ"},
131]
132
133sentiment_prompt = FewShotPromptTemplate(
134 examples=sentiment_examples,
135 example_template="ํ
์คํธ: {text}\n๊ฐ์ฑ: {sentiment}",
136 prefix="๋ค์ ํ
์คํธ์ ๊ฐ์ฑ์ ๋ถ์ํ์ธ์.",
137 suffix="ํ
์คํธ: {text}\n๊ฐ์ฑ:"
138)
139
140result = sentiment_prompt.format(text="์ค๋ ๊ธฐ๋ถ์ด ์ข๋ค์")
141print("Few-shot ๊ฐ์ฑ ๋ถ์ ํ๋กฌํํธ:")
142print(result)
143
144
145# ============================================
146# 4. Chain-of-Thought (CoT)
147# ============================================
148print("\n[4] Chain-of-Thought (CoT)")
149print("-" * 40)
150
151# Zero-shot CoT
152zero_shot_cot = """Q: Roger has 5 tennis balls. He buys 2 more cans of 3 balls each.
153 How many balls does he have now?
154
155Let's think step by step."""
156
157print("Zero-shot CoT:")
158print(zero_shot_cot)
159
160# Few-shot CoT
161few_shot_cot = """Q: There are 15 trees in the grove. Grove workers plant trees today.
162 After they are done, there will be 21 trees. How many trees did they plant?
163
164A: Let's think step by step.
1651. Started with 15 trees.
1662. After planting, there are 21 trees.
1673. Trees planted = 21 - 15 = 6 trees.
168The answer is 6.
169
170Q: If there are 3 cars in the parking lot and 2 more cars arrive,
171 how many cars are in the parking lot?
172
173A: Let's think step by step.
1741. Started with 3 cars.
1752. 2 more cars arrive.
1763. Total = 3 + 2 = 5 cars.
177The answer is 5.
178
179Q: Roger has 5 tennis balls. He buys 2 more cans of 3 balls each.
180 How many balls does he have now?
181
182A: Let's think step by step."""
183
184print("\nFew-shot CoT:")
185print(few_shot_cot)
186
187
188# ============================================
189# 5. ์ญํ ๊ธฐ๋ฐ ํ๋กฌํํ
190# ============================================
191print("\n[5] ์ญํ ๊ธฐ๋ฐ ํ๋กฌํํ
")
192print("-" * 40)
193
194class RolePrompt:
195 """์ญํ ๊ธฐ๋ฐ ํ๋กฌํํธ ์์ฑ"""
196
197 ROLES = {
198 "developer": """You are a senior software developer with 10 years of experience.
199You write clean, efficient, and well-documented code.
200You always consider edge cases and security implications.""",
201
202 "teacher": """You are a patient and encouraging teacher.
203You explain complex concepts using simple analogies.
204You always check for understanding and provide examples.""",
205
206 "reviewer": """You are a thorough code reviewer.
207You check for:
208- Code readability
209- Potential bugs
210- Performance issues
211- Security vulnerabilities
212You provide constructive feedback.""",
213
214 "translator": """You are a professional translator.
215You translate text while preserving:
216- Original meaning
217- Tone and style
218- Cultural context
219You provide notes for idiomatic expressions."""
220 }
221
222 @classmethod
223 def get_system_prompt(cls, role: str) -> str:
224 return cls.ROLES.get(role, "You are a helpful assistant.")
225
226 @classmethod
227 def create_prompt(cls, role: str, task: str) -> dict:
228 return {
229 "system": cls.get_system_prompt(role),
230 "user": task
231 }
232
233# ์ญํ ํ๋กฌํํธ ์์
234prompt = RolePrompt.create_prompt(
235 role="reviewer",
236 task="""๋ค์ ์ฝ๋๋ฅผ ๋ฆฌ๋ทฐํด์ฃผ์ธ์:
237
238def get_user(id):
239 return db.execute(f"SELECT * FROM users WHERE id = {id}")
240"""
241)
242print("์ฝ๋ ๋ฆฌ๋ทฐ์ด ์ญํ :")
243print(f"System: {prompt['system'][:100]}...")
244print(f"User: {prompt['user']}")
245
246
247# ============================================
248# 6. ๊ตฌ์กฐํ๋ ์ถ๋ ฅ ํ๋กฌํํธ
249# ============================================
250print("\n[6] ๊ตฌ์กฐํ๋ ์ถ๋ ฅ")
251print("-" * 40)
252
253# JSON ์ถ๋ ฅ ํ๋กฌํํธ
254json_prompt = """๋ค์ ํ
์คํธ์์ ์ธ๋ฌผ๊ณผ ์ฅ์๋ฅผ ์ถ์ถํด์ฃผ์ธ์.
255
256ํ
์คํธ: "์ฒ ์๋ ์์ธ์์ ์ํฌ๋ฅผ ๋ง๋ ๋ถ์ฐ์ผ๋ก ์ฌํ์ ๋ ๋ฌ๋ค."
257
258๋ค์ JSON ํ์์ผ๋ก ์๋ตํด์ฃผ์ธ์:
259{
260 "persons": ["์ธ๋ฌผ1", "์ธ๋ฌผ2"],
261 "locations": ["์ฅ์1", "์ฅ์2"]
262}"""
263
264print("JSON ์ถ๋ ฅ ํ๋กฌํํธ:")
265print(json_prompt)
266
267# ๋งํฌ๋ค์ด ๊ตฌ์กฐํ ์ถ๋ ฅ
268markdown_prompt = """๋ค์ ๊ธฐ์ฌ๋ฅผ ๋ถ์ํด์ฃผ์ธ์.
269
270## ์์ฝ
271(2-3๋ฌธ์ฅ์ผ๋ก ์์ฝ)
272
273## ํต์ฌ ํฌ์ธํธ
274- ํฌ์ธํธ 1
275- ํฌ์ธํธ 2
276- ํฌ์ธํธ 3
277
278## ๊ฐ์ฑ
279(๊ธ์ /๋ถ์ /์ค๋ฆฝ ์ค ์ ํ)
280
281## ์ ๋ขฐ๋
282(๋์/์ค๊ฐ/๋ฎ์ ์ค ์ ํ, ์ด์ ์ค๋ช
)"""
283
284print("\n๋งํฌ๋ค์ด ๊ตฌ์กฐํ ์ถ๋ ฅ:")
285print(markdown_prompt)
286
287
288# ============================================
289# 7. ์ถ๋ ฅ ํ์
290# ============================================
291print("\n[7] ์ถ๋ ฅ ํ์")
292print("-" * 40)
293
294import json
295import re
296from typing import Any, Optional
297
298class OutputParser:
299 """LLM ์ถ๋ ฅ ํ์ฑ"""
300
301 @staticmethod
302 def parse_json(text: str) -> Optional[dict]:
303 """JSON ์ถ์ถ ๋ฐ ํ์ฑ"""
304 # JSON ๋ธ๋ก ์ฐพ๊ธฐ
305 json_pattern = r'```json\s*(.*?)\s*```'
306 match = re.search(json_pattern, text, re.DOTALL)
307
308 if match:
309 json_str = match.group(1)
310 else:
311 # JSON ๊ฐ์ฒด ์ง์ ์ฐพ๊ธฐ
312 json_pattern = r'\{[^{}]*\}'
313 match = re.search(json_pattern, text, re.DOTALL)
314 if match:
315 json_str = match.group(0)
316 else:
317 return None
318
319 try:
320 return json.loads(json_str)
321 except json.JSONDecodeError:
322 return None
323
324 @staticmethod
325 def parse_list(text: str) -> list:
326 """๋ฆฌ์คํธ ํญ๋ชฉ ์ถ์ถ"""
327 # ๋ฒํธ ๋งค๊ธด ํญ๋ชฉ
328 numbered = re.findall(r'^\d+\.\s*(.+)$', text, re.MULTILINE)
329 if numbered:
330 return numbered
331
332 # ๋ถ๋ฆฟ ํญ๋ชฉ
333 bulleted = re.findall(r'^[-*]\s*(.+)$', text, re.MULTILINE)
334 return bulleted
335
336 @staticmethod
337 def parse_key_value(text: str) -> dict:
338 """ํค-๊ฐ ์ ์ถ์ถ"""
339 pattern = r'^([^:]+):\s*(.+)$'
340 matches = re.findall(pattern, text, re.MULTILINE)
341 return {k.strip(): v.strip() for k, v in matches}
342
343# ํ
์คํธ
344sample_output = """๋ถ์ ๊ฒฐ๊ณผ:
345- ์ฃผ์ : ์ธ๊ณต์ง๋ฅ
346- ๊ฐ์ฑ: ๊ธ์
347- ์ ๋ขฐ๋: ๋์
348
3491. ์ฒซ ๋ฒ์งธ ํฌ์ธํธ
3502. ๋ ๋ฒ์งธ ํฌ์ธํธ
3513. ์ธ ๋ฒ์งธ ํฌ์ธํธ"""
352
353parser = OutputParser()
354print("๋ฆฌ์คํธ ํ์ฑ:", parser.parse_list(sample_output))
355print("ํค-๊ฐ ํ์ฑ:", parser.parse_key_value(sample_output))
356
357
358# ============================================
359# 8. Self-Consistency
360# ============================================
361print("\n[8] Self-Consistency")
362print("-" * 40)
363
364from collections import Counter
365
366class SelfConsistency:
367 """Self-Consistency: ์ฌ๋ฌ ์ถ๋ก ๊ฒฝ๋ก์ ๋ค์๊ฒฐ"""
368
369 def __init__(self, model_fn, n_samples: int = 5):
370 self.model_fn = model_fn
371 self.n_samples = n_samples
372
373 def generate_with_consistency(self, prompt: str) -> tuple:
374 """์ฌ๋ฌ ์ํ ์์ฑ ํ ๋ค์๊ฒฐ"""
375 responses = []
376
377 for _ in range(self.n_samples):
378 # temperature > 0 ์ผ๋ก ๋ค์ํ ์๋ต ์์ฑ
379 response = self.model_fn(prompt, temperature=0.7)
380 answer = self._extract_answer(response)
381 responses.append(answer)
382
383 # ๋ค์๊ฒฐ
384 counter = Counter(responses)
385 most_common = counter.most_common(1)[0]
386
387 return most_common[0], most_common[1] / self.n_samples
388
389 def _extract_answer(self, response: str) -> str:
390 """์๋ต์์ ์ต์ข
๋ต ์ถ์ถ"""
391 # "The answer is X" ํจํด
392 match = re.search(r'answer is[:\s]*(\d+)', response, re.IGNORECASE)
393 if match:
394 return match.group(1)
395
396 # ๋ง์ง๋ง ์ซ์
397 numbers = re.findall(r'\d+', response)
398 return numbers[-1] if numbers else response
399
400# ๋ชจ์ ํจ์
401def mock_model(prompt, temperature=0.7):
402 import random
403 # ์ค์ ๋ก๋ LLM ํธ์ถ
404 answers = ["42", "42", "42", "41", "42"]
405 return f"The answer is {random.choice(answers)}"
406
407sc = SelfConsistency(mock_model, n_samples=5)
408print("Self-Consistency ์์ (๋ชจ์):")
409print("์ฌ๋ฌ ์ถ๋ก ๊ฒฝ๋ก ์์ฑ ํ ๋ค์๊ฒฐ๋ก ์ต์ข
๋ต ์ ํ")
410
411
412# ============================================
413# 9. ReAct ํจํด
414# ============================================
415print("\n[9] ReAct (Reasoning + Acting)")
416print("-" * 40)
417
418react_prompt = """Answer the following question using this format:
419
420Question: {question}
421
422Thought: (your reasoning about what to do)
423Action: (one of: Search[query], Calculate[expression], Lookup[term], Finish[answer])
424Observation: (result of the action)
425
426Repeat Thought/Action/Observation until you have the answer.
427
428Example:
429Question: What is the capital of the country where the Eiffel Tower is located?
430
431Thought: I need to find where the Eiffel Tower is located.
432Action: Search[Eiffel Tower location]
433Observation: The Eiffel Tower is located in Paris, France.
434
435Thought: Now I know it's in France. I need to find the capital of France.
436Action: Search[capital of France]
437Observation: The capital of France is Paris.
438
439Thought: I have the answer now.
440Action: Finish[Paris]
441
442Now answer:
443Question: {question}
444"""
445
446print("ReAct ํ๋กฌํํธ ํจํด:")
447print(react_prompt.format(question="What year was Python created?"))
448
449
450# ============================================
451# 10. Tree of Thoughts
452# ============================================
453print("\n[10] Tree of Thoughts")
454print("-" * 40)
455
456class TreeOfThoughts:
457 """Tree of Thoughts: ์ฌ๋ฌ ์ฌ๊ณ ๊ฒฝ๋ก ํ์"""
458
459 def __init__(self, model_fn, evaluator_fn):
460 self.model_fn = model_fn
461 self.evaluator_fn = evaluator_fn
462
463 def solve(self, problem: str, depth: int = 3, branches: int = 3) -> str:
464 """ํธ๋ฆฌ ํ์์ผ๋ก ๋ฌธ์ ํด๊ฒฐ"""
465 thoughts = self._generate_thoughts(problem, branches)
466
467 # ๊ฐ ์๊ฐ ํ๊ฐ
468 scored_thoughts = [
469 (thought, self.evaluator_fn(problem, thought))
470 for thought in thoughts
471 ]
472
473 # ์์ ์๊ฐ ์ ํ
474 scored_thoughts.sort(key=lambda x: x[1], reverse=True)
475 best_thoughts = scored_thoughts[:2]
476
477 if depth > 1:
478 # ์ฌ๊ท์ ์ผ๋ก ํ์ฅ
479 for thought, _ in best_thoughts:
480 extended = self.solve(
481 f"{problem}\n\nPartial solution: {thought}",
482 depth - 1,
483 branches
484 )
485 thoughts.append(extended)
486
487 # ์ต์ข
์ ํ
488 return scored_thoughts[0][0]
489
490 def _generate_thoughts(self, problem: str, n: int) -> list:
491 """n๊ฐ์ ์๋ก ๋ค๋ฅธ ์ ๊ทผ๋ฒ ์์ฑ"""
492 prompt = f"""Problem: {problem}
493
494Generate {n} different approaches to solve this problem.
495Each approach should be a distinct strategy.
496
497Approach 1:"""
498
499 # ์ค์ ๋ก๋ LLM ํธ์ถ
500 return [f"Approach {i+1}: ..." for i in range(n)]
501
502print("Tree of Thoughts ํจํด:")
503print("- ์ฌ๋ฌ ์ฌ๊ณ ๊ฒฝ๋ก๋ฅผ ํธ๋ฆฌ ํํ๋ก ํ์")
504print("- ๊ฐ ๋
ธ๋(์๊ฐ)๋ฅผ ํ๊ฐํ๊ณ ์ ๋งํ ๊ฒฝ๋ก ํ์ฅ")
505print("- ๋ณต์กํ ์ถ๋ก ๋ฌธ์ ์ ํจ๊ณผ์ ")
506
507
508# ============================================
509# 11. ํ๋กฌํํธ ์ต์ ํ ์ ๋ต
510# ============================================
511print("\n[11] ํ๋กฌํํธ ์ต์ ํ")
512print("-" * 40)
513
514optimization_strategies = """
515ํ๋กฌํํธ ์ต์ ํ ์ ๋ต:
516
5171. ๋ช
ํ์ฑ (Clarity)
518 Bad: "ํ
์คํธ๋ฅผ ์ ๋ฆฌํด์ค"
519 Good: "๋ค์ ํ
์คํธ๋ฅผ 3๋ฌธ์ฅ์ผ๋ก ์์ฝํ๊ณ , ํต์ฌ ํค์๋ 5๊ฐ๋ฅผ ์ถ์ถํด์ฃผ์ธ์."
520
5212. ๊ตฌ์ฒด์ฑ (Specificity)
522 Bad: "์ข์ ์ฝ๋๋ฅผ ์์ฑํด์ค"
523 Good: "Python 3.10+, ํ์
ํํธ ์ฌ์ฉ, PEP 8 ์ค์, ์๋ฌ ์ฒ๋ฆฌ ํฌํจ"
524
5253. ์ ์ฝ ์กฐ๊ฑด (Constraints)
526 - ์ถ๋ ฅ ๊ธธ์ด: "100๋จ์ด ์ด๋ด๋ก"
527 - ์ถ๋ ฅ ํ์: "JSON ํ์์ผ๋ก"
528 - ์คํ์ผ: "๊ณต์์ ์ธ ์ด์กฐ๋ก"
529
5304. ์์ ์ ๊ณต (Examples)
531 - ์ํ๋ ์ถ๋ ฅ์ ์์ 1-3๊ฐ ์ ๊ณต
532 - ํ์๊ณผ ์คํ์ผ ๋ช
ํํ ์ ๋ฌ
533
5345. ๋จ๊ณ๋ณ ๋ถํด (Decomposition)
535 - ๋ณต์กํ ํ์คํฌ๋ฅผ ์์ ๋จ๊ณ๋ก ๋ถํด
536 - ๊ฐ ๋จ๊ณ๋ณ๋ก ๋ช
ํํ ์ง์
537
5386. ๋ค๊ฑฐํฐ๋ธ ํ๋กฌํํ
(Negative Prompting)
539 - "~ํ์ง ๋ง์ธ์" ์ง์ ์ถ๊ฐ
540 - ์์น ์๋ ์ถ๋ ฅ ๋ฐฉ์ง
541"""
542print(optimization_strategies)
543
544
545# ============================================
546# 12. ํ๋กฌํํธ A/B ํ
์คํธ
547# ============================================
548print("\n[12] ํ๋กฌํํธ A/B ํ
์คํธ")
549print("-" * 40)
550
551class PromptABTest:
552 """ํ๋กฌํํธ A/B ํ
์คํธ ํ๋ ์์ํฌ"""
553
554 def __init__(self, model_fn, evaluator_fn):
555 self.model_fn = model_fn
556 self.evaluator_fn = evaluator_fn
557
558 def run_test(
559 self,
560 prompt_a: str,
561 prompt_b: str,
562 test_cases: list,
563 n_trials: int = 1
564 ) -> dict:
565 """A/B ํ
์คํธ ์คํ"""
566 results = {"A": 0, "B": 0, "tie": 0}
567 details = []
568
569 for case in test_cases:
570 scores_a = []
571 scores_b = []
572
573 for _ in range(n_trials):
574 # ํ๋กฌํํธ A
575 response_a = self.model_fn(prompt_a.format(**case))
576 score_a = self.evaluator_fn(response_a, case.get("expected"))
577 scores_a.append(score_a)
578
579 # ํ๋กฌํํธ B
580 response_b = self.model_fn(prompt_b.format(**case))
581 score_b = self.evaluator_fn(response_b, case.get("expected"))
582 scores_b.append(score_b)
583
584 avg_a = sum(scores_a) / len(scores_a)
585 avg_b = sum(scores_b) / len(scores_b)
586
587 if avg_a > avg_b:
588 results["A"] += 1
589 winner = "A"
590 elif avg_b > avg_a:
591 results["B"] += 1
592 winner = "B"
593 else:
594 results["tie"] += 1
595 winner = "tie"
596
597 details.append({
598 "case": case,
599 "score_a": avg_a,
600 "score_b": avg_b,
601 "winner": winner
602 })
603
604 return {
605 "summary": results,
606 "details": details,
607 "winner": "A" if results["A"] > results["B"] else "B"
608 }
609
610print("ํ๋กฌํํธ A/B ํ
์คํธ ํ๋ ์์ํฌ")
611print("- ๋ ํ๋กฌํํธ์ ์ฑ๋ฅ ๋น๊ต")
612print("- ๋ค์ํ ํ
์คํธ ์ผ์ด์ค์์ ํ๊ฐ")
613print("- ํต๊ณ์ ์ผ๋ก ์ ์๋ฏธํ ๊ฒฐ๊ณผ ๋์ถ")
614
615
616# ============================================
617# 13. ๋๋ฉ์ธ๋ณ ํ๋กฌํํธ ํ
ํ๋ฆฟ
618# ============================================
619print("\n[13] ๋๋ฉ์ธ๋ณ ํ๋กฌํํธ ํ
ํ๋ฆฟ")
620print("-" * 40)
621
622PROMPT_TEMPLATES = {
623 "classification": """Classify the following text into one of these categories: {categories}
624
625Text: {text}
626
627Think step by step:
6281. Identify key features of the text
6292. Match features to categories
6303. Select the best category
631
632Category:""",
633
634 "summarization": """Summarize the following text in {num_sentences} sentences.
635Focus on the key points and main arguments.
636Maintain the original tone.
637
638Text:
639{text}
640
641Summary:""",
642
643 "qa": """Answer the question based on the context below.
644If the answer cannot be found in the context, say "I don't know."
645Do not make up information.
646
647Context: {context}
648
649Question: {question}
650
651Answer:""",
652
653 "code_generation": """Write a {language} function that {task_description}.
654
655Requirements:
656{requirements}
657
658Include:
659- Type hints (if applicable)
660- Docstring
661- Example usage
662- Error handling
663
664Code:
665```{language}
666""",
667
668 "translation": """Translate the following {source_lang} text to {target_lang}.
669Preserve the original tone and meaning.
670For idiomatic expressions, provide a note.
671
672Original ({source_lang}):
673{text}
674
675Translation ({target_lang}):""",
676
677 "extraction": """Extract the following information from the text:
678{fields}
679
680Text:
681{text}
682
683Output as JSON:
684{{
685{json_template}
686}}"""
687}
688
689# ์ฌ์ฉ ์์
690classification_prompt = PROMPT_TEMPLATES["classification"].format(
691 categories="๊ธ์ , ๋ถ์ , ์ค๋ฆฝ",
692 text="์ค๋ ๋ ์จ๊ฐ ์ ๋ง ์ข๋ค์!"
693)
694print("๋ถ๋ฅ ํ๋กฌํํธ:")
695print(classification_prompt[:200] + "...")
696
697
698# ============================================
699# 14. ํ๋กฌํํธ ์ฒด์ด๋
700# ============================================
701print("\n[14] ํ๋กฌํํธ ์ฒด์ด๋")
702print("-" * 40)
703
704class PromptChain:
705 """ํ๋กฌํํธ๋ฅผ ์ฐ๊ฒฐํ์ฌ ๋ณต์กํ ํ์คํฌ ์ํ"""
706
707 def __init__(self, model_fn):
708 self.model_fn = model_fn
709 self.steps = []
710
711 def add_step(self, name: str, prompt_template: str, parser=None):
712 """์ฒด์ธ์ ๋จ๊ณ ์ถ๊ฐ"""
713 self.steps.append({
714 "name": name,
715 "template": prompt_template,
716 "parser": parser
717 })
718 return self
719
720 def run(self, initial_input: dict) -> dict:
721 """์ฒด์ธ ์คํ"""
722 context = initial_input.copy()
723 results = {}
724
725 for step in self.steps:
726 # ํ๋กฌํํธ ์์ฑ
727 prompt = step["template"].format(**context)
728
729 # LLM ํธ์ถ
730 response = self.model_fn(prompt)
731
732 # ํ์ฑ (์ ํ์ )
733 if step["parser"]:
734 response = step["parser"](response)
735
736 # ๊ฒฐ๊ณผ ์ ์ฅ
737 results[step["name"]] = response
738 context[step["name"]] = response
739
740 return results
741
742# ์ฒด์ธ ์์
743chain = PromptChain(lambda x: "Mock response")
744chain.add_step(
745 "summary",
746 "Summarize this text: {text}"
747).add_step(
748 "keywords",
749 "Extract keywords from: {summary}"
750).add_step(
751 "title",
752 "Create a title based on keywords: {keywords}"
753)
754
755print("ํ๋กฌํํธ ์ฒด์ด๋ ์์:")
756print("1. ํ
์คํธ ์์ฝ")
757print("2. ํค์๋ ์ถ์ถ")
758print("3. ์ ๋ชฉ ์์ฑ")
759print("โ ๊ฐ ๋จ๊ณ์ ์ถ๋ ฅ์ด ๋ค์ ๋จ๊ณ์ ์
๋ ฅ์ผ๋ก ์ฌ์ฉ")
760
761
762# ============================================
763# ์ ๋ฆฌ
764# ============================================
765print("\n" + "=" * 60)
766print("ํ๋กฌํํธ ์์ง๋์ด๋ง ์ ๋ฆฌ")
767print("=" * 60)
768
769summary = """
770ํ๋กฌํํ
๊ธฐ๋ฒ ์ ํ ๊ฐ์ด๋:
771
772| ์ํฉ | ์ถ์ฒ ๊ธฐ๋ฒ |
773|---------------------|---------------------|
774| ๊ฐ๋จํ ํ์คํฌ | Zero-shot |
775| ํน์ ํ์ ํ์ | Few-shot + ํ์์ง์ |
776| ๋ณต์กํ ์ถ๋ก | Chain-of-Thought |
777| ์ ๋ขฐ์ฑ ํ์ | Self-Consistency |
778| ๋๊ตฌ ์ฌ์ฉ ํ์ | ReAct |
779| ๋งค์ฐ ๋ณต์กํ ๋ฌธ์ | Tree of Thoughts |
780
781ํต์ฌ ์์น:
7821. ๋ช
ํํ๊ณ ๊ตฌ์ฒด์ ์ธ ์ง์
7832. ์ ์ ํ ์์ ์ ๊ณต
7843. ์ถ๋ ฅ ํ์ ๋ช
์
7854. ๋จ๊ณ๋ณ ์ฌ๊ณ ์ ๋
7865. ๋ฐ๋ณต์ ์ธ ๊ฐ์ ๊ณผ ํ
์คํธ
787
788ํ๋กฌํํธ ๊ตฌ์กฐ:
789 [์์คํ
์ง์] + [์ปจํ
์คํธ] + [ํ์คํฌ] + [์ถ๋ ฅ ํ์]
790"""
791print(summary)