본문 바로가기
🤖 AI/LangChain - GPT 강의

🦜 풀스택 GPT - MODEL IO

by 정람지 2024. 2. 20.

모듈
LangChain은 다음과 같은 주요 모듈을 위한 확장 가능한 표준 인터페이스 및 외부 통합 기능을 제공

 

Modules | 🦜️🔗 Langchain

LangChain provides standard, extendable interfaces and external integrations for the following main modules:

python.langchain.com


- Model I/O
언어 모델과의 인터페이스

- Retrieval
애플리케이션별 데이터를 사용한 인터페이스

- Agents
높은 수준의 지침이 주어지면 체인이 어떤 도구를 사용할지 선택하도록 합니다

- Chains
일반적인 빌딩 블록 구성

- Memory
체인 실행 간 지속적인 응용 프로그램 상태

- Callbacks
모든 체인의 중간 단계 기록 및 스트리밍

 

Model I/O | 🦜️🔗 Langchain

The core element of any language model application is...the model. LangChain gives you the building blocks to interface with any language model.

python.langchain.com

 

+ prompt Template

t = PromptTemplate.from_template("Tell me about the species about {animal}")
t.format(animal = "hamster")

🦜FewShotPromptTemplate

fewShot! 찾아봤었는데!

LM에게 답변 예시 제공

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
""",
},
]

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

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

prompt.format(country = "Germany")

예시를 포함한 프롬프트 생성

'Human: What do you know about France?\nAi:\nHere is what I know:\nCapital: Paris\nLanguage: French\nFood: Wine and Cheese\nCurrency: Euro\n\n\nHuman: What do you know about Italy?\nAi:\nI know this:\nCapital: Rome\nLanguage: Italian\nFood: Pizza and Pasta\nCurrency: Euro\n\n\nHuman: What do you know about Greece?\nAi:\nI know this:\nCapital: Athens\nLanguage: Greek\nFood: Souvlaki and Feta Cheese\nCurrency: Euro\n\n\nHuman: What do you know about Germany?'

chain = prompt | chat 

chain.invoke({"country": "German"})
 
Ai: I know this: Capital: Berlin Language: German Food: Bratwurst and Sauerkraut Currency: Euro

🦜 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 = final_prompt | chat

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

 

🦜LengthBasedExampleSelector

다이나믹하게 예시들을 선택하는 방법

from langchain.prompts.example_selector import LengthBasedExampleSelector

예제들을 형식화/ 양 조절 

요금냠냠방지


🦜BaseExampleSelector

사용자 맞춤형 - 유저의 로그인 여부나 사용 언어에 따라 예시 수 조정 등등

from langchain.prompts.example_selector.base import BaseExampleSelector
# BaseExampleSelector - 사용자 맞춤 구현하기
class RandomExampleSelector(BaseExampleSelector):
    def __init__(self, examples):
        self.examples = examples

    def add_example(self, example): #이미 존재하는 example에 example을 추가하는 함수인 add_example 필요
        self.examples.append(example)

    def select_examples(self, input_variables):
        from random import choice # 무작위 예시 랜덤 선택

        return [choice(self.examples)]

# 선제공예시 개수 조절 example_selector
example_selector = RandomExampleSelector(
    examples=examples,
)

 


🦜Serialization

디스크에서 prompt templates 가져오기 ( 별도로 템플릿 관리하기)

 

- json 

- yaml 

from langchain.prompts import load_prompt

prompt = load_prompt("./prompt.json") # 또는 yaml
prompt.format(country = "Germany")

🦜Composition

from langchain.prompts.pipeline import PipelinePromptTemplate

많은 프롬트프들을 하나로 합칠 수 있게 해줌


🦜caching

캐싱을 사용하면 LM의 응답을 저장할 수 있음

똑같은 질문 시 재사용 가능!

from langchain.globals import set_llm_cache
from langchain.cache import InMemoryCache

set_llm_cache(InMemoryCache())

모든 response 가 메모리에 저장됨

같은 응답으로!


🦜debug

로그같이 뭘 하고 있는지 보여줌

from langchain.globals import set_debug
set_debug(True) #디버그 로그

 


🦜Serialization

- 돈 지출 방식

- 모델을 어떻게 저장하고 불러오는지

from langchain.callbacks import get_openai_callback


with get_openai_callback() as usage: # LLM을 콜백으로 불러옴
    a = chat.predict("What is the recipe for hamster")
    print(a, "\n")
    print(usage)

햄스터의 레시피를 물어보는 데 0.2원 정도 썼다

그런데 제대로 알려주지도 않았다!!

 

I'm sorry, but I cannot provide a recipe for hamster as it is not ethical or safe to consume hamsters or any other type of pet. Hamsters are small animals that are meant to be kept as pets and should not be eaten. If you are looking for a recipe for a pet hamster, I recommend researching proper care and nutrition guidelines for hamsters as pets.


from langchain.chat_loading import load_llm

chat = load_llm("model.json")

모델 가져오기 가능

configuration 파일에서 open ai 채팅 모델 가져오기


와 사람이 많아여