[React] LangGraph pre-built ReAct agent
여기에 입력하면 된다.
ReAct 란
ReAct 는 2022년 Google 과 Princeton 연구자들이 제안한 방법론으로, LLM 이 Tought(생각) 와 Action(행동) 을 번갈아 수행하면서 문제를 해결하게 만드는 prompt 구조이다.
LangGraph Prebuilt create_react_agent
ReAct 에이전트는 간단히 pre-built 된 create_react_agent 함수를 통해서 구현이 가능하다.
작동 방식
에이전트가 입력을 받고, 툴을 사용할지 말지를 판단한다. 그리고 다음과 같은 루프가 반복된다.
- 에이전트가 “툴을 사용하라” 고 판단하면 툴을 실행하고 그 결과를 에이전트에 전달한다.
- 에이전트가 “툴을 사용하지 않는다”고 판단하면 사용자에게 최종 응답을 보낸다.
Agent 정의
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
from langchain_openai import ChatOpenAI
from typing import Literal
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
model = ChatOpenAI(
model="qwen2.5:14b",
base_url='http://127.0.0.1:11434/v1',
api_key='ollama',
temperature=0)
@tool
def get_weather(city: Literal["nyc", "sf"]):
"""Use this to get weather information."""
if city == "nyc":
return "It might be cloudy in nyc"
elif city == "sf":
return "It's always sunny in sf"
else:
raise AssertionError("Unknown city")
tools = [get_weather]
# We can add our system prompt here
prompt = "Respond in Italian"
# Define the graph
graph = create_react_agent(model, tools=tools, prompt=prompt)
Agent 출력 (stream)
1
2
3
4
5
6
7
def print_stream(stream):
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
출력 결과
1
2
inputs = {"messages": [("user", "What's the weather in NYC?")]}
print_stream(graph.stream(inputs, stream_mode="values"))
1
2
3
4
5
6
7
================================ Human Message ================================= What's the weather in NYC?
================================== Ai Message ================================== Tool Calls: get_weather (call_4mwvzef9) Call ID: call_4mwvzef9 Args: city: nyc
================================= Tool Message ================================= Name: get_weather It might be cloudy in nyc
================================== Ai Message ================================== Potrebbe essere nuvoloso a New York. Vuoi che controlli altre informazioni sul tempo?
Google AdSense — Post Ad
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.
Comments powered by Disqus.