Python/NLP Code

LangChain 활용 ReAct 알고리즘 구현 예제

jimmy_AI 2025. 1. 14. 00:29
반응형

안녕하세요.

오늘은 LangChain으로 LLM에서 원하는 종류의 output을 얻기 위하여

추론 및 적절한 도구를 호출하는 과정을 반복하는 ReAct 알고리즘을 구현하는

간략한 예제를 다루어보도록 하겠습니다.

 

 

Step 1. LangChain 세팅

LangChain 모듈 활용을 위한 설치가 필요합니다.

설치가 되어있지 않은 경우 다음 명령어를 통해 설치를 진행해주시면 됩니다.

$pip install langchain
$pip install langchain-openai

 

이 예제에서는 openai 모델을 활용할 예정이므로, API 키 값이 필요합니다.

OPENAI_API_KEY 환경 변수에 해당 값을 매칭시키기 위하여

.env 파일 정의를 권장합니다.

OPENAI_API_KEY="openai에서 발급받은 API Key"

 

다음과 같이 dotenv를 통해서 환경 변수를 불러오면 편리합니다.

(모듈 설치가 필요하다면 $pip install python-dotenv를 입력해줍니다.)

from dotenv import load_dotenv

load_dotenv()

 

 

Step 2. Tool 정의

ReAct 알고리즘에서 사용할 Tool을 정의해야 합니다.

 

각 도구는 파이썬 함수이며, 도구를 정의하는 방법은 다음과 같습니다.

from langchain.agents import tool

@tool # 데코레이터 필수
def my_func(input):
    """도구에 대한 설명 부분 -> 필수!"""

    return output

 

파이썬 함수에 @tool이라는 데코레이터와

함수에 대한 docstring을 포함시켜주시면 도구 정의는 완료됩니다.

 

docstring은 LLM 모델이 어떤 도구를 사용해야 할지를 정하는 과정에서

매우 중요하기 때문에 반드시 상세히 작성해주셔야 합니다.

 

문자열에서 A의 개수를 세는 도구와 정수를 이진수로 바꾸는 도구를

정의한 예시는 다음과 같습니다.

from langchain.agents import tool

# 도구 1: 문자열에서 "A"의 개수를 세는 도구
@tool
def get_count_A(text: str) -> int:
    """Returns the number of A in input string"""

    return text.count("A")

# 도구 2: 정수를 이진수로 변환하는 도구
@tool
def convert_binary_string(number: int | str) -> str:
    """Convert decimal integer to binary value"""

    return bin(int(number))[2:]

 

 

Step 3. ReAct 알고리즘 구현

도구 정의가 완료되었다면 사용할 도구 후보들을 리스트에 넣어줍니다.

tools = [get_count_A, convert_binary_string]

 

prompt는 ReAct 알고리즘에 널리 사용되는 프롬프트를 langchain hub에서 불러오겠습니다.

from langchain import hub

prompt = hub.pull("hwchase17/react")

 

참고로, 해당 프롬프트의 상세 내용은 다음과 같습니다.

(LangSmith의 hub 페이지에 검색 후 쉽게 찾을 수 있습니다.)

Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}

 

다음으로, LLM 모델과 Agent를 정의해야 합니다.

해당하는 코드 스니펫은 다음과 같습니다.

from langchain.agents import tool, create_react_agent, AgentExecutor

# LLM 모델 정의
llm = ChatOpenAI(model="gpt-4o-mini")

# Agent 정의(LLM, 도구 목록, 프롬프트를 전달)
agent = create_react_agent(llm, tools, prompt)

# Agent 내에서 실행되는 결과를 볼 수 있도록 도와줌
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

 

이제 원하는 질문을 Agent에게 던져보도록 하겠습니다.

문자열을 준 뒤, A의 갯수를 이진수로 변환해서 언급하도록 시켜보았습니다.

res = agent_executor.invoke({"input": "Count 'A' from this string and convert binary version of this number: 'AAABBBAAA'"})

print(res)
# {'input': "Count 'A' from this string and convert binary version of this number: 'AAABBBAAA'", 'output': '110'}

 

A는 주어진 문자열에서 6개이고, 최종 output은 이진수 110이므로 정답이 맞습니다.

 

터미널 상에는 중간 추론 결과도 출력이 되는데요.

결과를 살펴보면 다음과 같이 도구를 적절히 골라 추론을 진행하는 모습을 확인할 수 있습니다.

I need to count the number of 'A' characters in the given string 'AAABBBAAA' and then convert that count to its binary representation. 

Action: get_count_A  
Action Input: 'AAABBBAAA'  6I have counted the number of 'A's in the string, which is 6. Now I need to convert this count to its binary representation.

Action: convert_binary_string  
Action Input: 6  110I now know the final answer
Final Answer: 110

 

이 글이 LangChain을 활용한 ReAct 알고리즘 구현 방법에 도움이 되셨기를 바랍니다.

잘 봐주셔서 감사드립니다.