본문 바로가기
데이터&AI/LLM

파이썬 langchain 활용기반, 쉽게 챗봇사이트 만들기 (gradio)

by 일등박사 2024. 5. 18.

 

streamlit에 이어

파이썬의 기본 기능과 langchain 기능을 결합,

쉽게 챗봇사이트를 만들도록 도와주는 그라디어 (Gradio)의 

사용방법에 대하여 알아보겠습니다!!


 

 

1. pip 로 패키지 설치!!

 pip install gradio

 

 

2. 패키지 로드!! 이번에는 gpt3.5를 사용해보겠습니다!!

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
model =  "gpt-3.5-turbo"

## 모델설정
chatgpt35 = ChatOpenAI(temperature=0, model=model, openai_api_key="{나의 API키}")

 

3. 체인 만들기!! - 과건용을 기억하도록 lang chain 그조를 만들어줍니다!!

## 프롬포트에는 history라는 variable로 과거내역이 계속들어갑니다!!
chat_with_history_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant."),
        MessagesPlaceholder(variable_name="history"),
        ("human", "{message}"),
    ]
)

chain = chat_with_history_prompt | chatgpt35 | StrOutputParser()

# r과거 내역을 기억하는 history prompt 함수!!
def chat(message, history):
    history_langchain_format = []
    for human, ai in history:
        history_langchain_format.append(HumanMessage(content=human))
        history_langchain_format.append(AIMessage(content=ai))

    return chain.invoke({"message": message, "history": history_langchain_format})

 

 

 

4. 사이트 구성 : 웹페이지 구성요소를 간단하게 넣어줍니다!!

with gr.Blocks() as demo:
    chatbot = gr.ChatInterface(
        chat,
        examples=[
            "파이선 웹프레임워크 소개해줘",
            "streamlit에대하여 알고있니?",
            "GRADIO에 대하여 알려줘",
        ],
        title="GRADIO로 만든 챗봇",
        description="파이썬에서 손쉽게 챗봇을 만들어보세요",
    )
    chatbot.chatbot.height = 300

 

 

 

5. 실행!!

if __name__ == "__main__":
    demo.launch()

local url과 함꼐 실행됩니다~~

이제 챗봇이 잘 작동함을 볼 수 있어요!!

게다가!! 과거 내역도 잘 기억하며 채팅할수 있습니다~!^^

 

어떄요!! 참 쉽죠!?

댓글