■ 커스텀 상태를 사용해 동작하는 방법을 보여준다.
※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다.
※ TAVILY_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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
from dotenv import load_dotenv from langchain_openai import ChatOpenAI from langchain_community.tools.tavily_search import TavilySearchResults from pydantic import BaseModel from typing_extensions import TypedDict from typing import Annotated from langgraph.graph.message import add_messages from langchain_core.messages import AIMessage from langchain_core.messages import ToolMessage from langgraph.prebuilt import tools_condition from langgraph.graph import StateGraph from langgraph.prebuilt import ToolNode from langgraph.graph import START from langgraph.graph import END from langgraph.checkpoint.memory import MemorySaver load_dotenv() chatOpenAI = ChatOpenAI(model = "gpt-4o-mini") tavilySearchResults = TavilySearchResults(max_results = 2) class RequestAssistance(BaseModel): """Escalate the conversation to an expert. Use this if you are unable to assist directly or if the user requires support beyond your permissions. To use this function, relay the user's 'request' so the expert can provide the right guidance. """ request : str runnableBinding = chatOpenAI.bind_tools([tavilySearchResults, RequestAssistance]) class State(TypedDict): messages : Annotated[list, add_messages] askHuman : bool def chat(state : State): responseAIMessage = runnableBinding.invoke(state["messages"]) askHuman = False if (responseAIMessage.tool_calls and responseAIMessage.tool_calls[0]["name"] == RequestAssistance.__name__): askHuman = True return {"messages" : [responseAIMessage], "askHuman" : askHuman} def createToolMessage(content : str, aiMessage : AIMessage): return ToolMessage(content = content, tool_call_id = aiMessage.tool_calls[0]["id"]) def humanNode(state : State): newMessageList = [] if not isinstance(state["messages"][-1], ToolMessage): # 일반적으로 사용자는 인터럽트 중에 상태를 업데이트했을 것이다. # 그렇지 않은 경우 LLM이 계속 진행되도록 플레이스홀더 ToolMessage를 포함한다하. newMessageList.append(createToolMessage("No response from human.", state["messages"][-1])) return {"messages" : newMessageList, "askHuman" : False} def selectNextNode(state : State): if state["askHuman"]: return "human_node" return tools_condition(state) stateGraph = StateGraph(State) stateGraph.add_node("chatbot_node", chat) stateGraph.add_node("human_node" , humanNode) stateGraph.add_node("tools" , ToolNode(tools = [tavilySearchResults])) stateGraph.add_edge(START , "chatbot_node") stateGraph.add_edge("tools" , "chatbot_node") stateGraph.add_edge("human_node", "chatbot_node") stateGraph.add_conditional_edges("chatbot_node", selectNextNode, {"human_node" : "human_node", "tools" : "tools", END : END}) memorySaver = MemorySaver() compiledStateGraph = stateGraph.compile(checkpointer = memorySaver, interrupt_before = ["human_node"]) userInput = "I need some expert guidance for building this AI agent. Could you request assistance for me?" configurableDictionary = {"configurable" : {"thread_id" : "1"}} generator1 = compiledStateGraph.stream({"messages" : [("user", userInput)]}, configurableDictionary, stream_mode = "values") for addableUpdatesDict in generator1: if "messages" in addableUpdatesDict: print(addableUpdatesDict) print("-" *50) stateSnapshot = compiledStateGraph.get_state(configurableDictionary) aiMessage = stateSnapshot.values["messages"][-1] toolMessage = createToolMessage ( "We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.", aiMessage ) compiledStateGraph.update_state(configurableDictionary, {"messages" : [toolMessage]}) generator2 = compiledStateGraph.stream(None, configurableDictionary, stream_mode = "values") for addableUpdatesDict in generator2: if "messages" in addableUpdatesDict: print(addableUpdatesDict) print("-" *50) """ { 'messages' : [ HumanMessage( content = 'I need some expert guidance for building this AI agent. Could you request assistance for me?', additional_kwargs = {}, response_metadata = {}, id = '597c2770-d5cd-4460-80f3-2cbfe2e4affd' ) ] } { 'messages' : [ HumanMessage( content = 'I need some expert guidance for building this AI agent. Could you request assistance for me?', additional_kwargs = {}, response_metadata = {}, id = '597c2770-d5cd-4460-80f3-2cbfe2e4affd' ), AIMessage( content = '', additional_kwargs = { 'tool_calls' : [ { 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'function' : { 'arguments' : '{"request":"I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent."}', 'name' : 'RequestAssistance' }, 'type' : 'function' } ], 'refusal' : None }, response_metadata = { 'token_usage' : { 'completion_tokens' : 48, 'prompt_tokens' : 160, 'total_tokens' : 208, 'completion_tokens_details' : { 'accepted_prediction_tokens' : 0, 'audio_tokens' : 0, 'reasoning_tokens' : 0, 'rejected_prediction_tokens' : 0 }, 'prompt_tokens_details' : {'audio_tokens' : 0, 'cached_tokens' : 0} }, 'model_name' : 'gpt-4o-mini-2024-07-18', 'system_fingerprint' : 'fp_0aa8d3e20b', 'finish_reason' : 'tool_calls', 'logprobs' : None }, id = 'run-94370388-2485-44e2-a42e-f5b39abfd707-0', tool_calls= [ { 'name' : 'RequestAssistance', 'args' : {'request' : 'I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent.'}, 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'type' : 'tool_call' } ], usage_metadata = { 'input_tokens' : 160, 'output_tokens' : 48, 'total_tokens' : 208, 'input_token_details' : {'audio' : 0, 'cache_read' : 0}, 'output_token_details' : {'audio' : 0, 'reasoning' : 0} } ) ], 'askHuman' : True } -------------------------------------------------- { 'messages' : [ HumanMessage( content = 'I need some expert guidance for building this AI agent. Could you request assistance for me?', additional_kwargs = {}, response_metadata = {}, id='597c2770-d5cd-4460-80f3-2cbfe2e4affd' ), AIMessage( content = '', additional_kwargs = { 'tool_calls' : [ { 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'function' : { 'arguments' : '{"request":"I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent."}', 'name' : 'RequestAssistance' }, 'type' : 'function' } ], 'refusal' : None }, response_metadata = { 'token_usage' : { 'completion_tokens' : 48, 'prompt_tokens' : 160, 'total_tokens' : 208, 'completion_tokens_details' : { 'accepted_prediction_tokens' : 0, 'audio_tokens' : 0, 'reasoning_tokens' : 0, 'rejected_prediction_tokens' : 0 }, 'prompt_tokens_details' : {'audio_tokens' : 0, 'cached_tokens' : 0} }, 'model_name' : 'gpt-4o-mini-2024-07-18', 'system_fingerprint' : 'fp_0aa8d3e20b', 'finish_reason' : 'tool_calls', 'logprobs' : None }, id = 'run-94370388-2485-44e2-a42e-f5b39abfd707-0', tool_calls = [ { 'name' : 'RequestAssistance', 'args' : {'request' : 'I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent.'}, 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'type' : 'tool_call' } ], usage_metadata = { 'input_tokens' : 160, 'output_tokens' : 48, 'total_tokens' : 208, 'input_token_details' : {'audio' : 0, 'cache_read' : 0}, 'output_token_details' : {'audio' : 0, 'reasoning' : 0} } ), ToolMessage( content = "We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.", id = '90011801-5705-46ab-89b2-9cfcfd124f87', tool_call_id = 'call_TnzKa6e4uqsMi99PVEADbh6p' ) ], 'askHuman' : True } { 'messages' : [ HumanMessage( content = 'I need some expert guidance for building this AI agent. Could you request assistance for me?', additional_kwargs = {}, response_metadata = {}, id = '597c2770-d5cd-4460-80f3-2cbfe2e4affd' ), AIMessage( content = '', additional_kwargs = { 'tool_calls' : [ { 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'function' : { 'arguments' : '{"request":"I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent."}', 'name' : 'RequestAssistance' }, 'type' : 'function' } ], 'refusal' : None }, response_metadata = { 'token_usage' : { 'completion_tokens' : 48, 'prompt_tokens' : 160, 'total_tokens' : 208, 'completion_tokens_details' : { 'accepted_prediction_tokens' : 0, 'audio_tokens' : 0, 'reasoning_tokens' : 0, 'rejected_prediction_tokens' : 0 }, 'prompt_tokens_details' : { 'audio_tokens' : 0, 'cached_tokens' : 0 } }, 'model_name' : 'gpt-4o-mini-2024-07-18', 'system_fingerprint' : 'fp_0aa8d3e20b', 'finish_reason' : 'tool_calls', 'logprobs' : None }, id = 'run-94370388-2485-44e2-a42e-f5b39abfd707-0', tool_calls = [ { 'name' : 'RequestAssistance', 'args' : {'request' : 'I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent.'}, 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'type' : 'tool_call' } ], usage_metadata = { 'input_tokens' : 160, 'output_tokens' : 48, 'total_tokens' : 208, 'input_token_details' : {'audio' : 0, 'cache_read' : 0}, 'output_token_details' : {'audio' : 0, 'reasoning' : 0} } ), ToolMessage( content = "We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.", id = '90011801-5705-46ab-89b2-9cfcfd124f87', tool_call_id = 'call_TnzKa6e4uqsMi99PVEADbh6p' ) ], 'askHuman' : False } { 'messages' : [ HumanMessage( content = 'I need some expert guidance for building this AI agent. Could you request assistance for me?', additional_kwargs = {}, response_metadata = {}, id = '597c2770-d5cd-4460-80f3-2cbfe2e4affd' ), AIMessage( content = '', additional_kwargs = { 'tool_calls' : [ { 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'function' : { 'arguments' : '{"request":"I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent."}', 'name' : 'RequestAssistance' }, 'type' : 'function' } ], 'refusal' : None }, response_metadata = { 'token_usage' : { 'completion_tokens' : 48, 'prompt_tokens' : 160, 'total_tokens' : 208, 'completion_tokens_details' : { 'accepted_prediction_tokens' : 0, 'audio_tokens' : 0, 'reasoning_tokens' : 0, 'rejected_prediction_tokens' : 0 }, 'prompt_tokens_details' : {'audio_tokens' : 0, 'cached_tokens' : 0} }, 'model_name' : 'gpt-4o-mini-2024-07-18', 'system_fingerprint' : 'fp_0aa8d3e20b', 'finish_reason' : 'tool_calls', 'logprobs' : None }, id = 'run-94370388-2485-44e2-a42e-f5b39abfd707-0', tool_calls = [ { 'name' : 'RequestAssistance', 'args' : {'request' : 'I am looking for expert guidance on building an AI agent. I need advice on the best practices, technologies, and frameworks to use for developing an effective AI agent.'},\ 'id' : 'call_TnzKa6e4uqsMi99PVEADbh6p', 'type' : 'tool_call' } ], usage_metadata = { 'input_tokens' : 160, 'output_tokens' : 48, 'total_tokens' : 208, 'input_token_details' : {'audio' : 0, 'cache_read' : 0}, 'output_token_details' : {'audio' : 0, 'reasoning' : 0} } ), ToolMessage( content = "We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.", id = '90011801-5705-46ab-89b2-9cfcfd124f87', tool_call_id = 'call_TnzKa6e4uqsMi99PVEADbh6p' ), AIMessage( content = "The experts recommend using LangGraph to build your AI agent. It's considered more reliable and extensible compared to simple autonomous agents. If you have any specific questions about using LangGraph or need further assistance, feel free to ask!", additional_kwargs = {'refusal' : None}, response_metadata = { 'token_usage' : { 'completion_tokens' : 47, 'prompt_tokens' : 249, 'total_tokens' : 296, 'completion_tokens_details' : { 'accepted_prediction_tokens' : 0, 'audio_tokens' : 0, 'reasoning_tokens' : 0, 'rejected_prediction_tokens' : 0 }, 'prompt_tokens_details' : {'audio_tokens' : 0, 'cached_tokens' : 0} }, 'model_name' : 'gpt-4o-mini-2024-07-18', 'system_fingerprint' : 'fp_0aa8d3e20b', 'finish_reason' : 'stop', 'logprobs' : None }, id = 'run-91719ca7-a533-4ccf-955e-1c65a240140f-0', usage_metadata = { 'input_tokens' : 249, 'output_tokens' : 47, 'total_tokens' : 296, 'input_token_details' : {'audio' : 0, 'cache_read' : 0}, 'output_token_details' : {'audio' : 0, 'reasoning' : 0} } ) ], 'askHuman' : False } -------------------------------------------------- """ |
▶ 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
aiohappyeyeballs==2.4.4 aiohttp==3.11.11 aiosignal==1.3.2 annotated-types==0.7.0 anyio==4.7.0 attrs==24.3.0 certifi==2024.12.14 charset-normalizer==3.4.1 colorama==0.4.6 dataclasses-json==0.6.7 distro==1.9.0 frozenlist==1.5.0 greenlet==3.1.1 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 httpx-sse==0.4.0 idna==3.10 jiter==0.8.2 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.13 langchain-community==0.3.13 langchain-core==0.3.28 langchain-openai==0.2.14 langchain-text-splitters==0.3.4 langgraph==0.2.60 langgraph-checkpoint==2.0.9 langgraph-sdk==0.1.48 langsmith==0.2.7 marshmallow==3.23.2 msgpack==1.1.0 multidict==6.1.0 mypy-extensions==1.0.0 numpy==2.2.1 openai==1.58.1 orjson==3.10.13 packaging==24.2 propcache==0.2.1 pydantic==2.10.4 pydantic-settings==2.7.1 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 SQLAlchemy==2.0.36 tenacity==9.0.0 tiktoken==0.8.0 tqdm==4.67.1 typing-inspect==0.9.0 typing_extensions==4.12.2 urllib3==2.3.0 yarl==1.18.3 |
# pip install python-dotenv langchain-community langchain-openai langgraph 명령을 실행했다.