본문 바로가기

LangChain&LangGraph

디버깅 - #4 중간 메시지 변경

중간 메시지 변경

특정 단계의 메시지를 변경한 후 replay  를 수행하여 답변의 차이를 검증 간능하다

 

원본 시나리오 

Human > 1+10 은?

AI > tool calls ( 1+10)      <<< 변경 대상

Tool > 1+ 10 = 11

AI > 11 입니다

 

메시지 변경 시나리오

Human > 1+10 은?

AI > tool calls ( 100+1000)

Tool > 100+ 1000 = 1100

AI > 1100 입니다

 

핵심 코드

@tool
def sum_tools(a:int, b:int)->int:
    """ get a, b  two number add"""
    return a+b
 
**************중간 생략**********
 
 
# 그래프 상태 스냅샷 생성
snapshot = graph.get_state(config)
# 교체하고자 하는 대상 메시지
orgin_messages = snapshot.values['messages'][-1]
# 대상 원본
print ( orgin_messages )
# {'name': 'sum_tools', 'args': {'a': 1, 'b': 1000}, 'id': '9c3a4bb7-92ee-41dc-84a1-81e5e8ebf2ff', 'type': 'tool_call'}
# 교체하고자하는 대상 tool_calls
new_messages = orgin_messages.tool_calls[0]
# params 변경
new_messages['args']={'a':100,'b':1000}
# 변경된 메시지
print ( new_messages )
# {'name': 'sum_tools', 'args': {'a': 100, 'b': 1000}, 'id': '9c3a4bb7-92ee-41dc-84a1-81e5e8ebf2ff', 'type': 'tool_call'}
 
# 새로운 매시지 생성 핵심은 바꾸고자하는 ID 값을 넣어줘야 대체됨!!!!!!!!!
_new_messages = [
    AIMessage(
        content=orgin_messages.content,
        tool_calls=[new_messages],
        id = orgin_messages.id
    )
]
 
# 변경내용 없데이트
graph.update_state(
    # 업데이트할 상태 지정
    config,
    # 제공할 업데이트된 값. `State`의 메시지는 "추가 전용"으로 기존 상태에 추가됨
    {"messages": _new_messages},
)
 
# 이어서 실행
events = graph.stream(None, config, stream_mode="values")
# 이벤트 반복 처리
for event in events:
    # 메시지가 이벤트에 포함된 경우
    print(event)
    print("\n\n")

 

 

로그

 

메시지 변경전

https://smith.langchain.com/public/4dc11c72-6d18-4da5-b86a-c40ce12f850b/r

 

LangSmith

 

smith.langchain.com

메시지 변경 업데이트 

https://smith.langchain.com/public/ee607c39-69d1-4f55-9506-9e903fa2bb62/r

 

LangSmith

 

smith.langchain.com

메시지 이어서 실행

https://smith.langchain.com/public/969fb141-899b-4e11-9068-4c7947308b5c/r

 

LangSmith

 

smith.langchain.com

 

 

튜토리얼을 따라하기만 할때는 크게 필요하지않앗지만, 실제 내가 생각한 코드를 구성하고 디버깅하기위해서는 이러한 기능을 반드시 숙지해야할 필요가있다. 그렇지 않으면 개발 및 디버깅이 너무 힘듬..

 

interrupt, 이어서 실행, replay , 메시지변경 등을 통해 다양한 디버깅 및 시나리오 검증등이 가능하다.