LangChain – Prompt (3/)
프롬프트에 예들을 담으면 llm이 응답을 더 잘 할수 있다고 하니, 프롬프트를 만드는 프롬프트 템플릿도 이를 지원해야 한다. 예라면 몇 개 정도겠지. llm에서는 몇 개 예를 제공하는 것을 few shot이라고 한다. few shot을 가질 수 있는 프롬프트 템플릿은 FewShotPromptTemplate. FewShotPromptTemplate은 StringPromptTemplate이다.
few shot을 갖는 프롬프트 템플릿을 만들어보자.
few shot으로 사용할 예들이 있어야 한다.
1 2 3 4 5 |
# First, create the list of few shot examples. examples = [ {"word": "happy", "antonym": "sad"}, {"word": "tall", "antonym": "short"}, ] |
템플릿으로 만들 프롬프트가 있어야 한다. 프롬프트 동적 부분에 예들이 들어갈 수 있도록 한다.
1 2 3 4 5 6 7 8 |
example_formatter_template = """ Word: {word} Antonym: {antonym}\n """ example_prompt = PromptTemplate( input_variables=["word", "antonym"], template=example_formatter_template, ) |
few shot 예들이 설정되어야 하고, 예들을 사용한 프롬프트가 설정되어야 한다. examples, example_prompt
예들 앞과 뒤에 들어갈 텍스트를 작성할 수 있다. 보통은 앞에는 intructions이, 뒤에는 사용자 입력이 들어간다. prefix, suffix
예들과 앞과 뒤에 들어간 텍스트들과 구분해주는게 좋겠지. example_separator
1 2 3 4 5 6 7 8 9 10 |
few_shot_prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Word: {input}\nAntonym:", input_variables=["input"], example_separator="\n\n", ) |
예가 많을 때는 부분적으로 선택하고 싶을 수 있다. 부분적으로 선택해서 응답이 잘 나와야지. ExampleSelector
컨텍스트의 길이가 제약을 넘어설 것 같을 때라면 단순하게 길이로 선택하고자 할 수도 있다. 긴 입력을 넣는다면 예는 적게 선택해야겠지. LengthBasedExampleSelector
짧은 것은 많이, 긴 것은 적게 한다면 좀 더 많은 예를 포함할 수 있겠네. 최대 길이로 제약할 수 있다. max_length
예들과 프롬프트 템플릿은 LengthBasedExampleSelector에 설정한다. examples, example_prompt
예들 선택기는 FewShotPromptTemplate에 설정한다. example_selector
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from langchain.prompts.example_selector import LengthBasedExampleSelector examples = [ {"word": "happy", "antonym": "sad"}, {"word": "tall", "antonym": "short"}, {"word": "energetic", "antonym": "lethargic"}, {"word": "sunny", "antonym": "gloomy"}, {"word": "windy", "antonym": "calm"}, ] example_selector = LengthBasedExampleSelector( examples=examples, example_prompt=example_prompt, max_length=25, ) dynamic_prompt = FewShotPromptTemplate( example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Word: {input}\nAntonym:", input_variables=["input"], example_separator="\n\n", ) |