Global outage event
If you’re experiencing issues with your AWS services, then please refer to the AWS Health Dashboard. You can find the overall status of ongoing outages, the health of AWS services, and the latest updates from AWS engineers.
Bedrock의 Claude3 Haiku 모델을 활용하여 간단한 AI 채팅 프로그램을 개발하는 방법
해당 기사에서는 Claude3 의 최신 모델인 Haiku를 사용하여 Langchain과 Streamlit을 이용하여 간단한 채팅 웹을 개발하는 방법에 대해서 가이드 합니다.
이 가이드는 Langchain과 Streamlit이라는 프레임워크 를 활용하여 대화형 AI 애플리케이션을 구축하는 방법을 단계적으로 안내합니다. 특히 Bedrock의 claude3 Haiku 모델을 사용하여 고품질의 자연스러운 대화를 생성할 수 있습니다.
Langchain은 대규모 언어 모델을 쉽게 통합하고 관리할 수 있는 프레임워크입니다. 한편 Streamlit은 Python 기반의 웹 앱 프레임워크로, 몇 줄의 코드만으로도 인터랙티브한 웹 인터페이스를 구축할 수 있습니다. 이 두 가지 도구를 결합하면 강력한 대화형 AI 애플리케이션을 만들 수 있습니다.
실제 대화형 AI 애플리케이션 예제를 구축하면서 claude3 Haiku 모델의 작동 원리와 Langchain, Streamlit의 사용법을 이해할 수 있습니다. 이렇게 구축된 애플리케이션은 AI 기술에 대한 접근성을 높이고 다양한 분야에 적용할 수 있는 기회를 제공할 수 있습니다.
사전 준비 사항
- 사용하고 싶은 모델에 대한 모델 엑세스가 허용 되어있어야합니다.
- 현 기사에서는 Claude 3 Haiku와 관련되어 엑세스 권한이 부여됨으로 설정하였습니다.
Langchain, Streamlit, Boto3 라이브러리 설치
- 파이썬 IDE에 아래의 명령어를 입력하여 라이브러리를 설치합니다.
pip install boto3
pip install langchain
pip install streamlit
코드 개발
- 아래의 코드는 Bedrock의 Haiku 모델을 사용합니다.
- 히스토리 관리를 위해 Langchain을 사용하고 인터페이스를 위해 Streamlit을 사용하여 구축합니다.
bedrock 클라이언트 생성
- haiku_chatbot.py 이름으로 파이썬 파일을 생성합니다.
- 아래의 코드는 bedrock-runtime의 client를 생성하는 코드입니다.
- Bedrock 모델을 사용할 리전을 설정해야합니다. (Bedrock이 지원되는 리전을 입력합니다.) [1]
import boto3
bedrock_runtime = boto3.client(
service_name="bedrock-runtime",
region_name="<region>",
)
사용할 모델 및 파라미터 값 지정
- model_id 파라미터에 사용하고 싶은 하는 모델 id를 입력합니다. [2]
- 현재 기사에서는 anthropic.claude-3-haiku-20240307-v1:0를 사용합니다.
- 필수 파라미터 값을 수정하여 자신의 환경에 맞도록 설정합니다. [3]
model_id = "<model_id>"
model_kwargs = {
"temperature": 0.0,
"top_k": 250,
"top_p": 1,
"stop_sequences": ["\n\nHuman"],
}
template = [
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
Langchain 설정 및 화면 구성
- 이후 Streamlit을 사용하여 Anthropic Claude 모델과 대화형 챗봇 인터페이스를 구축합니다.
- 사용자 입력을 받아 Claude 모델에 전달하고, 모델의 응답을 화면에 표시합니다.
- 사이드바에는 이전 대화 내용 중 답변만을 기록합니다.
import streamlit as st
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts import MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_models import BedrockChat
from langchain_community.chat_message_histories import StreamlitChatMessageHistory
chain = prompt | model | StrOutputParser()
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: StreamlitChatMessageHistory(key="chat_messages"),
input_messages_key="question",
history_messages_key="history",
)
st.set_page_config(page_title='Anthropic claude3 haiku')
st.header("Anthropic Haiku 챗봇")
if "messages" not in st.session_state:
st.session_state['history']=[]
st.session_state["messages"] = [{"role": "ai", "content": "무엇을 도와 드릴까요?"}]
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
if customer_input := st.chat_input():
config = {"configurable": {"session_id": "any"}}
st.chat_message("human").write(customer_input)
st.session_state.messages.append({"role": "human", "content": customer_input})
response = chain_with_history.invoke({"question": customer_input}, config)
st.chat_message("ai").write(response)
st.session_state.messages.append({"role": "ai", "content": response})
st.session_state.history.append(response)
with st.sidebar:
st.title("히스토리")
historys=st.session_state['history']
if len(historys)>=1:
for history in historys:
status_container = st.container(border=True)
status_container.write(history)
전체코드
import boto3
import streamlit as st
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts import MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_models import BedrockChat
from langchain_community.chat_message_histories import StreamlitChatMessageHistory
bedrock_runtime = boto3.client(
service_name="bedrock-runtime",
region_name="<region>",
)
model_kwargs = {
"temperature": 0.0,
"top_k": 250,
"top_p": 1,
"stop_sequences": ["\n\nHuman"],
}
model_id = "<model_id>"
template = [
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
prompt = ChatPromptTemplate.from_messages(template)
model = BedrockChat(
client=bedrock_runtime,
model_id=model_id,
model_kwargs=model_kwargs,
)
chain = prompt | model | StrOutputParser()
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: StreamlitChatMessageHistory(key="chat_messages"),
input_messages_key="question",
history_messages_key="history",
)
st.set_page_config(page_title='Anthropic claude3 haiku')
st.header("Anthropic Haiku 챗봇")
if "messages" not in st.session_state:
st.session_state['history']=[]
st.session_state["messages"] = [{"role": "ai", "content": "무엇을 도와 드릴까요?"}]
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
if customer_input := st.chat_input():
config = {"configurable": {"session_id": "any"}}
st.chat_message("human").write(customer_input)
st.session_state.messages.append({"role": "human", "content": customer_input})
response = chain_with_history.invoke({"question": customer_input}, config)
st.chat_message("ai").write(response)
st.session_state.messages.append({"role": "ai", "content": response})
st.session_state.history.append(response)
with st.sidebar:
st.title("히스토리")
historys=st.session_state['history']
if len(historys)>=1:
for history in historys:
status_container = st.container(border=True)
status_container.write(history)
테스트
- terminal 에서 아래와 같은 명령어를 이용하여 streamlit 으로 python파일을 실행합니다.
streamlit run ./haiku_chatbot.py
참고 자료
[1] 지원 AWS 지역
https://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/bedrock-regions.html
[2] Amazon Bedrock model IDs
https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html
[3] AnthropicClaude텍스트 완성 API 요청 및 응답
- 언어
- 한국어
