포스트

[React] agent 에 Memory 추가하기

여기에 입력하면 된다.


개요

create_react_agent() 함수에 체크포인터(checkpointer) 를 전달함으로써 메모리를 추가할 수 있다.

Tools 정의

1
2
3
4
5
6
7
8
9
10
11
12
13
from langchain_core.tools import tool

@tool
def get_weather(location:str) -> str:
    """Use this to get weather information"""
    if any([city in location.lower() for city in ['nyc','new york city']]):
        return "It might be cloudy in nyc"
    elif any([city in location.lower() for city in ['sf', 'san francisco']]):
        return "It's always sunny in sf"
    else:
        return f"I am not sure what the weather is in {location}"

tools = [get_weather]

Memory 정의

1
2
3
4
5
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent

memory = MemorySaver()
graph = create_react_agent(model, tools=tools, checkpointer=memory)
  • Memory 가 추가되어도 graph 그림 상에서는 나타나지 않는다.

첫번째 질문

  • 뉴욕의 날씨는?
1
2
3
config = {'configurable' : {'thread_id' : "1"}}
inputs = {'messages' : [('user', "What's the weather in NYC?")]}
print_stream(graph.stream(inputs, config=config, stream_mode='values'))
  • config 에 thread_id 를 줌으로써 thread_level 단위에서 기억할 수 있도록 설정한다.

두번째 질문

  • 뉴욕에서 유명한 것은? (it 으로 표현)
1
2
inputs = {'messages' : [('user', "What's it known for?")]}
print_stream(graph.stream(inputs, config=config, stream_mode='values'))
1
2
3
4
================================ Human Message ================================= What's it known for? 

================================== Ai Message ================================== 
I think there might be a bit of confusion. You asked about the current weather conditions, which I found to be cloudy in NYC. If you're asking what NYC is known for generally, it's famous for its iconic landmarks like the Statue of Liberty and Central Park, vibrant culture including Broadway shows, and being a global financial and cultural hub. Would you like more specific information on any particular aspect of NYC?
  • 혼란스러워 하지만 그래도 잘 기억한다.
  • config 가 이전 대화랑 일치하기 때문에 Itnyc 인 것을 기억한다.

  • 코드 주소

Reference

Google AdSense — Post Ad
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

Comments powered by Disqus.