■ 외부 채팅 히스토리를 사용하는 챗봇을 만드는 방법을 보여준다.
※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다.
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
from dotenv import load_dotenv from langchain_openai import ChatOpenAI from langchain_core.tools import tool from langgraph.graph import StateGraph from langgraph.graph import MessagesState from langgraph.prebuilt import ToolNode from langgraph.graph import START from langgraph.graph import END from langchain_core.messages import HumanMessage from langchain_core.messages import AIMessage from typing import Literal from typing import List load_dotenv() class ChatBot: def __init__(self): self.chatOpenAI = ChatOpenAI(model = "gpt-4o-mini", temperature = 0) self.setToolList() self.setGraph() def setToolList(self): @tool def search(query : str): """Call to surf the web.""" if "sf" in query.lower() or "san francisco" in query.lower(): return "It's 60 degrees and foggy." return "It's 90 degrees and sunny." self.toolList = [search] self.runnableBinding = self.chatOpenAI.bind_tools(self.toolList) def setGraph(self): self.stateGraph = StateGraph(MessagesState) def chat(messageState: MessagesState): messageList = messageState["messages"] responseAIMessage = self.runnableBinding.invoke(messageList) return {"messages" : [responseAIMessage]} toolNode = ToolNode(self.toolList) self.stateGraph.add_node("chatbot_node", chat ) self.stateGraph.add_node("tool_node" , toolNode) self.stateGraph.add_edge(START, "chatbot_node") def shouldContinue(messageState : MessagesState) -> Literal["tool_node", END]: messageList = messageState["messages"] lastMessage = messageList[-1] if lastMessage.tool_calls: return "tool_node" return END self.stateGraph.add_conditional_edges("chatbot_node", shouldContinue) self.stateGraph.add_edge("tool_node", 'chatbot_node') self.compiledStateGraph = self.stateGraph.compile() def chat(self, message : str, chatHistoryMessageList : List = None) -> str: if chatHistoryMessageList is None: chatHistoryMessageList = [] humanMessage = HumanMessage(content = message) allMessageList = chatHistoryMessageList + [humanMessage] response = self.compiledStateGraph.invoke({"messages" : allMessageList}) return response["messages"][-1].content if __name__ == "__main__": chatbot = ChatBot() chatHistoryMessageList = [ HumanMessage(content = "Hello!"), AIMessage(content = "Hi there! How can I help you today?") ] message1 = "저의 이름은 홍길동 입니다." responseString1 = chatbot.chat(message1, chatHistoryMessageList) print("User :", message1) print("AI :" , responseString1) print("-" * 50) chatHistoryMessageList.append(HumanMessage(content = message1)) chatHistoryMessageList.append(AIMessage(content = responseString1)) message2 = "저의 이름은 무엇입니까?" responseString2 = chatbot.chat(message2, chatHistoryMessageList) print("User :", message2) print("AI :" , responseString2) print("-" * 50) chatHistoryMessageList.append(HumanMessage(content = message2)) chatHistoryMessageList.append(AIMessage(content = responseString2)) print(chatHistoryMessageList) print("-" * 50) """ User : 저의 이름은 홍길동 입니다. AI : 안녕하세요, 홍길동님! 어떻게 도와드릴까요? -------------------------------------------------- User : 저의 이름은 무엇입니까? AI : 홍길동님이십니다! 다른 질문이 있으신가요? -------------------------------------------------- [HumanMessage(content='Hello!', additional_kwargs={}, response_metadata={}, id='26060985-a5df-4444-9d22-5f207b497b0e'), AIMessage(content='Hi there! How can I help you today?', additional_kwargs={}, response_metadata={}, id='65f8d5c9-b0b5-4a14-b998-51a11e8a38ae'), HumanMessage(content='저의 이름은 홍길동 입니다.', additional_kwargs={}, response_metadata={}, id='eba05c18-468a-45c4-8d0b-6a14ad7b2c69'), AIMessage(content='안녕하세요, 홍길동님! 어떻게 도와드릴까요?', additional_kwargs={}, response_metadata={}, id='d6524d1d-feb1-4952-98d5-743b6959e92f'), HumanMessage(content='저의 이름은 무엇입니까?', additional_kwargs={}, response_metadata={}), AIMessage(content='홍길동님이십니다! 다른 질문이 있으신가요?', additional_kwargs={}, response_metadata={})] -------------------------------------------------- """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
annotated-types==0.7.0 anyio==4.7.0 certifi==2024.12.14 charset-normalizer==3.4.1 colorama==0.4.6 distro==1.9.0 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 idna==3.10 jiter==0.8.2 jsonpatch==1.33 jsonpointer==3.0.0 langchain-core==0.3.28 langchain-openai==0.2.14 langgraph==0.2.60 langgraph-checkpoint==2.0.9 langgraph-sdk==0.1.48 langsmith==0.2.6 msgpack==1.1.0 openai==1.58.1 orjson==3.10.12 packaging==24.2 pydantic==2.10.4 pydantic_core==2.27.2 python-dotenv==1.0.1 PyYAML==6.0.2 regex==2024.11.6 requests==2.32.3 requests-toolbelt==1.0.0 sniffio==1.3.1 tenacity==9.0.0 tiktoken==0.8.0 tqdm==4.67.1 typing_extensions==4.12.2 urllib3==2.3.0 |
※ pip install python-dotenv langchain-openai langgraph 명령을 실행했다.