공부/AI

GPT_2(노마드코더)

줘요 2023. 11. 30. 23:45

1. FewShotPromptTemplate

 

FewShotPromptTemplate를 import 해준다.

from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.callbacks import StreamingStdOutCallbackHandler

chat = ChatOpenAI(
    temperature=0.1,
    streaming=True,
    callbacks=[StreamingStdOutCallbackHandler()]
)

 

 

출력 형식의 예제를 보여준다. ex) 질문: 프랑스에 대해 아니? 답: 수도-파리, 언어-프랑스어, 음식-와인 그리고 치즈, 통화-유로

examples = [
{
"question": "What do you know about France?",
"answer": """
Here is what I know:
Capital: Paris
Language: French
Food: Wine and Cheese
Currency: Euro
""",
},
{
"question": "What do you know about Italy?",
"answer": """
I know this:
Capital: Rome
Language: Italian
Food: Pizza and Pasta
Currency: Euro
""",
},
{
"question": "What do you know about Greece?",
"answer": """
I know this:
Capital: Athens
Language: Greek
Food: Souvlaki and Feta Cheese
Currency: Euro
""",
},
]

 

PromptTemplate를 통해 template를 지정해 준다.

example_prompt = PromptTemplate.from_template("Human: {question} \n AI: {answer}")

 

FewShotPromptTemplate는 각각의 examples를 가져와 example_prompt를 이용하여 형식화해주고 suffix의 질문을 넣어준다.

prompt = FewShotPromptTemplate(
    example_prompt= example_prompt,
    examples=examples,
    suffix="Human: What do you know about {country}?",
    input_variables=["country"],
)

 

chain형식으로 invoke 해주면 예제와 똑같이 답변을 해준다.

chain = prompt | chat

chain.invoke({
    "country":"Turkey"
})

결과 화면

========================================================================================

 

2. FewShotChatMessagePromptTemplate

 

import를 PromptTemplate, FewShotPromptTemplate를  ChatPromptTemplate, FewShotChatMessagePromptTemplate로 변경해 준다.

from langchain.prompts import ChatPromptTemplate
from langchain.prompts.few_shot import FewShotChatMessagePromptTemplate

 

 

예제의 question을 country로 변경 후 나라 이름만 넣어준다.

examples = [
{
"country": "France",
"answer": """
Here is what I know:
Capital: Paris
Language: French
Food: Wine and Cheese
Currency: Euro
""",
},
{
"country": "Italy",
"answer": """
I know this:
Capital: Rome
Language: Italian
Food: Pizza and Pasta
Currency: Euro
""",
},
{
"country": "Greece",
"answer": """
I know this:
Capital: Athens
Language: Greek
Food: Souvlaki and Feta Cheese
Currency: Euro
""",
},
]

 

ChatPromptTemplate에 human은 이렇게 질문할 거고 ai는 예제의 답변처럼 대답할 거라고 형식을 지정해 준다.

FewShotChatMessagePromptTemplate에 형식화해서 변수에 담아준다.

example_prompt = ChatPromptTemplate.from_messages([
    ("human", "What do you know about {country}?"),
    ("ai","{answer}"),
])

example_prompt = FewShotChatMessagePromptTemplate(
    example_prompt= example_prompt,
    examples=examples,
)

 

시스템 메시지, 예제, 질문이 포함된 최종 프롬프트

final_prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a geography expert, you give short answers"),
    example_prompt,
    ("human", "What do you know about {country}?")
])

 

chain형식으로 invoke 해주면 예제와 똑같이 답변을 해준다.

chain = final_prompt | chat

chain.invoke({
    "country":"Thailand"
})

결과 화면

========================================================================================

3. 예제를 랜덤으로 하나 가져오기

 

BaseExampleSelector를 import 해준다.

from langchain.prompts.example_selector.base import BaseExampleSelector

 

RandomExampleSelector 클래스를 만들어주고 함수를 작성해 준다.

class RandomExampleSelector(BaseExampleSelector):

    def __init__(self,examples):
        self.examples=examples

    def add_example(self, example):
        self.examples.append(example)
       

    def select_examples(self, input_variables):
        from random import choice
        return [choice(self.examples)]

example_prompt = PromptTemplate.from_template("Human: {question} \n AI: {answer}")

example_selector = RandomExampleSelector(
    examples=examples,
)

prompt = FewShotPromptTemplate(
    example_prompt= example_prompt,
    example_selector=example_selector,
    suffix="Human: What do you know about {country}?",
    input_variables=["country"],
)

prompt.format(country="Brazil")

 

결과 화면

========================================================================================

4. 프롬프트를 따로 저장해 두고 다른 누구나 프롬프트를 가져다 쓸 수 있게

 

json파일과 yaml 파일을 쓸 수 있음

 

prompt.json 파일 작성

{
  "type": "prompt",
  "template": "What is the capital of {country}",
  "input_variables": ["country"]
}

 

prompt.yaml 파일 작성

_type: "prompt"
template: "What is the capital of {country}"
input_variables: ["country"]

 

아래와 같이 작성

from langchain.prompts import load_prompt

# json 파일일때
prompt = load_prompt("./prompt.json")

# yaml 파일일때
prompt = load_prompt("./prompt.yaml")

chat = ChatOpenAI(
    temperature=0.1,
    streaming=True,
    callbacks=[StreamingStdOutCallbackHandler()]
)

prompt.format(country="Germany")

결과 화면

========================================================================================

5. 여러 prompt 사용

 

from langchain.chat_models import ChatOpenAI
from langchain.callbacks import StreamingStdOutCallbackHandler
from langchain.prompts import PromptTemplate
from langchain.prompts.pipeline import PipelinePromptTemplate

chat = ChatOpenAI(
    temperature=0.1,
    streaming=True,
    callbacks=[StreamingStdOutCallbackHandler()]
)

 

4개의 prompt 작성

# 롤플레잉을 도와주고 어떤 캐릭터를 흉내내는 ai라고 알려줌
intro = PromptTemplate.from_template(
    """
    You are a role playing assistant.
    And you are impersonating a {character}
"""
)

# 어떻게 캐릭터들이 말하는지에 대한 예제
example = PromptTemplate.from_template(
    """
   This is an example of how you talk:

   Human: {example_question}
   You: {example_answer}
"""
)

# ai도우미가 우리의 텍스트를 완성해주는 start 예제
start = PromptTemplate.from_template(
    """
   Start now!

   Human: {question}
   You:
"""
)

# 위 모든 것을 합친 prompt
final = PromptTemplate.from_template(
    """
   {intro}

   {example}

   {start}
"""
)

 

PipelinePromptTemplate를 통해 형식화하고 어떤 식으로 전달해 줄지 지정해 줌

 

prompts = [
    ("intro", intro),
    ("example", example),
    ("start", start)
]

full_prompt = PipelinePromptTemplate(final_prompt=final,pipeline_prompts=prompts)

chain = full_prompt | chat

chain.invoke({
    "character":"Pirate",
    "example_question":"What is your location?",
    "example_answer":"Arrrg! That is a secret!! Arg arg!",
    "question":"What is your fav food?"
})

결과 화면

========================================================================================

6. 똑같은  질문을 받으면 계속 답변을 만들지 않고 이미 답변한 답을 캐싱하고 사용

 

방법 1

set_llm_cache과 InMemoryCache를 import 하고 set_llm_cache(InMemoryCache()) 코드 작성

from langchain.chat_models import ChatOpenAI
from langchain.callbacks import StreamingStdOutCallbackHandler
from langchain.globals import set_llm_cache
from langchain.cache import InMemoryCache

set_llm_cache(InMemoryCache())


chat = ChatOpenAI(
    temperature=0.1,
    # streaming=True,
    # callbacks=[StreamingStdOutCallbackHandler()]
)

chat.predict("How do you make italian pasta")

 

방법 2

set_debug를 import 하고 set_debug(True) 코드 작성 답변이 생성될 때 로그를 보여줌 

from langchain.chat_models import ChatOpenAI
from langchain.callbacks import StreamingStdOutCallbackHandler
from langchain.globals import set_llm_cache, set_debug
from langchain.cache import InMemoryCache

set_llm_cache(InMemoryCache())
set_debug(True)


chat = ChatOpenAI(
    temperature=0.1,
    # streaming=True,
    # callbacks=[StreamingStdOutCallbackHandler()]
)

chat.predict("How do you make italian pasta")

 

방법 3

SQLiteCache를 import 하고 set_llm_cache(SQLiteCache("cache.db")) 코드 작성

from langchain.chat_models import ChatOpenAI
from langchain.callbacks import StreamingStdOutCallbackHandler
from langchain.globals import set_llm_cache, set_debug
from langchain.cache import InMemoryCache, SQLiteCache

set_llm_cache(SQLiteCache("cache.db"))


chat = ChatOpenAI(
    temperature=0.1,
    # streaming=True,
    # callbacks=[StreamingStdOutCallbackHandler()]
)

chat.predict("How do you make italian pasta")

 

cache.db라는 파일이 생성됨

같은 질문을 했을 때 답변속도가 40초에서 0.5초로 줄어들음

========================================================================================

7. 모델을 부를 때마다 비용이 얼마나 드는지 

get_openai_callback를 import 하고

 

with get_openai_callback() as usage:
    chat.predict("what the recipe for soju")
    print(usage)

 

해당 코드를 통해 비용을 볼 수 있음

from langchain.chat_models import ChatOpenAI
from langchain.callbacks import get_openai_callback

chat = ChatOpenAI(
    temperature=0.1,
)

with get_openai_callback() as usage:
    chat.predict("what the recipe for soju")
    print(usage)

내용까지 보려면

print(a, b, "\n")를 추가

from langchain.chat_models import ChatOpenAI
from langchain.callbacks import get_openai_callback

chat = ChatOpenAI(
    temperature=0.1,
)

with get_openai_callback() as usage:
    a = chat.predict("what the recipe for soju")
    b = chat.predict("what the recipe for bread")
    print(a,b,"\n")
    print(usage)