Model I/O

  • 랭체인의 다양한 모듈 중 하나

1. Few-shot prompt templates

  • fewShot : 모델에게 예제를 제공
  • 단 예제를 무한히 줄 수는 없음 : 비용문제, 제한존재
from langchain_core.prompts.few_shot import FewShotPromptTemplate
from langchain_core.prompts.prompt import PromptTemplate

examples = [
    {
        "question": "Who lived longer, Muhammad Ali or Alan Turing?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
""",
    },
    {
        "question": "When was the founder of craigslist born?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952
""",
    },
    {
        "question": "Who was the maternal grandfather of George Washington?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
""",
    },
    {
        "question": "Are both the directors of Jaws and Casino Royale from the same country?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate Answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate Answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate Answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate Answer: New Zealand.
So the final answer is: No
""",
    },
]

example_prompt = PromptTemplate(
    input_variables=["question", "answer"], template="Question: {question}\n{answer}"
)

print(example_prompt.format(**examples[0]))

2. Few-shot examples for chat models

from langchain_core.prompts import (
    ChatPromptTemplate,
    FewShotChatMessagePromptTemplate,
)

examples = [
    {"input": "2+2", "output": "4"},
    {"input": "2+3", "output": "5"},
]
# This is a prompt template used to format each individual example.
example_prompt = ChatPromptTemplate.from_messages(
    [
        ("human", "{input}"),
        ("ai", "{output}"),
    ]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
    example_prompt=example_prompt,
    examples=examples,
)

print(few_shot_prompt.format())

final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human", "{input}"),
    ]
)
from langchain_community.chat_models import ChatAnthropic

chain = final_prompt | ChatAnthropic(temperature=0.0)

chain.invoke({"input": "What's the square of a triangle?"})

3. Select by length

3.1 LengthBasedExampleSelector

from langchain_core.example_selectors import LengthBasedExampleSelector
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

# Examples of a pretend task of creating antonyms.
examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "energetic", "output": "lethargic"},
    {"input": "sunny", "output": "gloomy"},
    {"input": "windy", "output": "calm"},
]

example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template="Input: {input}\nOutput: {output}",
)
example_selector = LengthBasedExampleSelector(
    # The examples it has available to choose from.
    examples=examples,
    # The PromptTemplate being used to format the examples.
    example_prompt=example_prompt,
    # The maximum length that the formatted examples should be.
    # Length is measured by the get_text_length function below.
    max_length=25,
    # The function used to get the length of a string, which is used
    # to determine which examples to include. It is commented out because
    # it is provided as a default value if none is specified.
    # get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x))
)
dynamic_prompt = FewShotPromptTemplate(
    # We provide an ExampleSelector instead of examples.
    example_selector=example_selector,
    example_prompt=example_prompt,
    prefix="Give the antonym of every input",
    suffix="Input: {adjective}\nOutput:",
    input_variables=["adjective"],
)
# An example with small input, so it selects all examples.  
print(dynamic_prompt.format(adjective="big"))

# An example with long input, so it selects only one example.  
long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else"  
print(dynamic_prompt.format(adjective=long_string))

# You can add an example to an example selector as well.  
new_example = {"input": "big", "output": "small"}  
dynamic_prompt.example_selector.add_example(new_example)  
print(dynamic_prompt.format(adjective="enthusiastic"))

'GPT' 카테고리의 다른 글

AI EXPO KOREA SUMMIT 참석 후 기억에 남는 이야기 정리  (0) 2024.05.07
ChatOpenAI  (0) 2024.04.30
🦜 랭체인(LangChain)  (0) 2024.04.29
GPT 프로젝트를 위한 Python 환경설정  (0) 2024.04.29

ChatOpenAI 객체 생성 옵션

  • 랭체인(langchain)의 OpenAI GPT 모델(ChatOpenAI)temperature
    • 사용할 샘플링 온도는 0과 2 사이에서 선택합니다. 0.8과 같은 높은 값은 출력을 더 무작위하게 만들고, 0.2와 같은 낮은 값은 출력을 더 집중되고 결정론적으로 만듭니다.

max_tokens

  • 채팅에서 생성할 토큰의 최대 개수

model_name

  • 적용 가능한 모델 리스트
    import openai
    

model_list = sorted([m['id'] for m in openai.Model.list()['data']])
for m in model_list:
print(m)

```python
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)

messages = [  
("system", "You are a helpful assistant that translates English to French."), 
("human", "Translate this sentence from English to French. I love programming."),  
]  

llm.invoke(messages)

ChatPromptTemplate

from langchain.prompts import ChatPromptTemplate

template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI bot. Your name is {name}."),
    ("human", "Hello, how are you doing?"),
    ("ai", "I'm doing well, thanks!"),
    ("human", "{user_input}"),
])

prompt_value = template.invoke(
    {
        "name": "Bob",
        "user_input": "What is your name?"
    }
)

Chaining


- Runnables를 '|'을사용해서 Chaining 할 수 있다

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are a helpful assistant that translates {input_language} to {output_language}.",
        ),
        ("human", "{input}"),
    ]
)

chain = prompt | llm
chain.invoke(
    {
        "input_language": "English",
        "output_language": "German",
        "input": "I love programming.",
    }
)

참고


'GPT' 카테고리의 다른 글

AI EXPO KOREA SUMMIT 참석 후 기억에 남는 이야기 정리  (0) 2024.05.07
🦜️🔗 Model I/O  (0) 2024.05.01
🦜 랭체인(LangChain)  (0) 2024.04.29
GPT 프로젝트를 위한 Python 환경설정  (0) 2024.04.29

1. 랭체인(LangChain)이란?

  • LLM과 애플리케이션 통합을 간소화하도록 설계된 SDK

기고 | LLM과 함께 뜨는 중··· 개발자를 위한 '랭체인' 안내서

데이터 소스

  • LLM에 대한 컨텍스트 구축을 위한 소스
  • PDF, 웹 페이지, CSV, DBMS와 같은 서로 다은 소스에서 데이터에 액세스하고 검색할 수 있는 모듈과 통합 지원

단어 임베딩

  • 일부 외부 소스에서 검색된 데이터는 벡터로 전환되어야함
  • 랭체인은 선택한 LLM을 기반으로 최적의 임베딩 모델 선택

벡터 데이터 베이스

대규모 언어 모델(LLM)

  • 랭체인은 오픈AI, 코히어(Cohere), AI21에서 제공하는 주류 LLM과 허깅페이스(Hugging Face)에서 제공되는 오픈소스 LLM을 지원

2. 랭체인 모듈

  • 이미지는 랭체인 프레임워크의 핵심을 나타낸다. 스택 상단의 애플리케이션은 파이썬 또는 자바스크립트 SDK를 통해 여러 랭체인 모듈 중 하나와 상호 작용한다.

3. 테스트 코드

  • 주피터 노트북 환경에서 테스트
  • .env 파일에 OPENAI_API_KEY="" 입력
from langchain.chat_models import ChatOpenAI

chat = ChatOpenAI()

chat.invoke("랭체인은 무엇인가요?")

AIMessage(content='랭체인은 블록체인 기술을 기반으로 한 게임 랭킹 시스템을 말합니다. 이를 통해 게임 플레이어들은 공정하고 투명한 방식으로 게임에서의 업적을 인증하고 랭킹을 확인할 수 있습니다. 또한 랭체인은 게임 개발사들에게도 플레이어들의 성과를 신뢰성 있게 기록하고 관리할 수 있는 기회를 제공합니다. 이러한 방식으로 랭체인은 게임 산업에 혁신을 가져다 줄 수 있는 기술적인 도구로 주목받고 있습니다.')


참고문헌

  1. LangCahin Quickstart
  2. LLM과 함께 뜨는 중··· 개발자를 위한 '랭체인' 안내서, CIO Korea
  3. 랭체인(LangChain) 입문부터 응용까지

'GPT' 카테고리의 다른 글

AI EXPO KOREA SUMMIT 참석 후 기억에 남는 이야기 정리  (0) 2024.05.07
🦜️🔗 Model I/O  (0) 2024.05.01
ChatOpenAI  (0) 2024.04.30
GPT 프로젝트를 위한 Python 환경설정  (0) 2024.04.29

+ Recent posts