Ssul's Blog

Langchain Prompt template 정리 본문

AI & ML/개념잡기

Langchain Prompt template 정리

Ssul 2024. 5. 14. 17:01

Langchain.... 좋기는 한데, 많이 복잡한 감이 없지 하나 있다.

 

그래서, 우선 PromptTemplate부터 차근차근 정리해보고자 한다.

 

1. PromptTemplate

- 기본단위

- PromptTemplate.from_template(~~~)변수를 지정하여 넣을수 있음

- .format을 하면 string값이 나옴

prompt_template = PromptTemplate.from_template(
    "Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")

결과값: 'Tell me a funny joke about chickens.'

prompt_template = PromptTemplate.from_template("Tell me a joke")
prompt_template.format()

결과값: 'Tell me a joke'

 

2. SystemMessagePromptTemplate

- 시스템 메세지를 설정하는 템플릿. PromptTemplate와 동일

- ChatPromptTemplate에 넣을수 있음

system_template = SystemMessagePromptTemplate.from_template("Your name is {name}.")
system_template.format(name="Kim")

결과값: "Your name is Kim."

 

3. HumanMessagePromptTemplate

- 유저 메세지를 설정하는 템플릿

- ChatPromptTemplate에 넣을수 있음

human_template = HumanMessagePromptTemplate.from_template("Hi! My name is {human_name}.")
human_template.format(human_name="Choi")

결과값: "Hi! My name is Choi."

*AIMessagePromptTemplate: HumanMessagePromptTemplate과 동일. 대화를 주고 받을때, gpt의 예전응답을 기록하는데도 사용함

 

 

4. ChatPromptTemplate

- System, Human, AI 메세지 템플릿을 넣을수 있음

- .from_messages 사용

ChatPromptTemplate.from_messages(
	[SystemMessageTemplate]
    + [HumanMessageTemplate]
    + [AIMessageTemplate]
    + [HumanMessageTemplate]
)

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}"),
    ]
)
chat_template.format_messages(name="Bob", user_input="What is your name?")

 

- system, human, ai는 .from_template로 셋팅 > ChatPromptTemplate에 결합 > .format_messages를 통해 변수 입력

 

5. Chaining 진행

- System메세지 설정: "너는 친절한 {major}선생님이다."

- Human메세지 설정: "안녕하세요 선생님. 제 이름은 {name}입니다. 중학교 1학년 수준의 {major}과목 문제 한개 내주세요."

- Chat메세지 생성: system, human메세지 넣어주고,

- .format_message로 과목, 이름 설정

- chaining하고, LLM에 질문하기

import os

import openai
from dotenv import load_dotenv
from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate
from langchain_openai import ChatOpenAI

load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')

llm = ChatOpenAI(temperature=0.8, max_tokens=200, model="gpt-3.5-turbo", api_key=api_key)

system_template = SystemMessagePromptTemplate.from_template("너는 친절한 {major}선생님이다.")
human_template = HumanMessagePromptTemplate.from_template("안녕하세요 선생님. 제 이름은 {name}입니다. 중학교 1학년 수준의 문제 한개 내주세요.")

chat_template = ChatPromptTemplate.from_messages(
    [system_template]
    + [human_template]
)

chain = chat_template | llm

out = chain.invoke({"major":"수학", "name":"김철수"})

print(out)

 

결과값이 AIMessage(content='.....',.....)로, AIMessage객체로 나온다.

 

6. StrOutputParser()

- parser를 적용하면, 응답 텍스트만 받을수 있다

import os

import openai
from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate
from langchain_openai import ChatOpenAI

load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')

llm = ChatOpenAI(temperature=0.8, max_tokens=200, model="gpt-3.5-turbo", api_key=api_key)

system_template = SystemMessagePromptTemplate.from_template("너는 친절한 {major}선생님이다.")
human_template = HumanMessagePromptTemplate.from_template("안녕하세요 선생님. 제 이름은 {name}입니다. 중학교 1학년 수준의 문제 한개 내주세요.")

chat_template = ChatPromptTemplate.from_messages(
    [system_template]
    + [human_template]
)

chain = chat_template | llm

out = chain.invoke({"major":"수학", "name":"김철수"})

print(type(out))

chain2 = chat_template | llm | StrOutputParser()

out2 = chain2.invoke({"major":"수학", "name":"김철수"})
print(out2)

 

out2의 결과값:

"안녕하세요, 김철수 학생님. 물론입니다! 다음은 중학교 1학년 수준의 문제입니다.
문제: \(5x + 3 = 18\) 일 때, \(x\)의 값은 무엇인가요? 
이 문제를 풀어보세요. 어려운 점이 있으면 언제든 물어봐주세요!"

 

 

랭체인의 가장 기본적인 PromptTemplate를 활용해서, LLM과 소통하는 방법을 알아봤다.

다음은 조금 더 복잡한, 대화내용을 기억하는 것을 살펴보자~