[LangChain for LLM Application Development] 랭체인 Agent

본 게시물은 Deeplearning.ai 코스를 수강 후 요약 및 정리한 내용입니다.


 

본 강의의 마지막 파트 Agent 이다 ㅎㅎ

 

Agent의 주된 개념은 Language model 이 다음에 취할 행동 (Action)을 선택하도록 하게끔 하는 것이다.

따라서 Agent에서 Language model은 어떤 Action을 취할지 결정하는 Reasoning Engine의 역할을 한다.

 

앞서 우리는 QA task와 같은 많은 task들을 다뤘지만, Reasoning Engine 과 같은 기능이 LLM에 있으면 좋을 것으로 생각된다.

Agent 에서 중요한 것은 Language model을 Reasoning Engine으로 사용 할 것이기 때문에 temperature=0으로 지정해두고 코드를 작성해야 한다!

 

(temperature는 얼마나 정확한 답변을 도출할지를 나타내는 parameter라고 생각하면 된다. 0에 가까울수록 확률이 높은 정보만을 출력하고 1에 가까울수록 창의력이 좋은 답변을 출력한다.)

 

Agent 생성하기

 

아래와 같이 모듈들을 import 해 주고, temperature를 0으로 지정해준다.

from langchain.agents.agent_toolkits import create_python_agent
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
from langchain.tools.python.tool import PythonREPLTool
from langchain.python import PythonREPL
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(temperature=0, model=llm_model)

tools = load_tools(["llm-math","wikipedia"], llm=llm)
agent= initialize_agent(
    tools, 
    llm, 
    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    handle_parsing_errors=True,
    verbose = True)

 

위에서 볼 수 있듯이 llm 을 temperature = 0 으로 지정해주었고, 

tool로서 llm-math 툴과 wikipedia 툴을 각각 불러와 agent를 생성해 주었다. 

각각의 툴들은 아래와 같은 기능들을 한다.

 

  • llm-math : LLM + Calculator , LLM Chain 그 자체로 동작한다.
  • wikipedia : wikipedia와 연결하여 사용할 수 있는 API tool

 

그렇다.

Agent 를 이용하면 외부 API tool 사용이 가능해진다!

 

또한 agent를 생성하면서 

verbose = True

로 설정하면서 중간 과정을 볼 수 있도록 생성하였다. ㅎㅎ

 

 

 위 코드에서 확인할 수 있듯이 Agent type은 아래와 같이 정의할 수 있다. 

 

  • Tool, LM, Agent type
  • 위 코드에서 설정한 Agent type의 Chat_zero_shot_react_description의 의미
    • 첫 번째 Chat은 LM에 의해 Optimize
    • 두 번째 Chat 부터는 Agent 에 의해 Prompt technique로 조정되어 LM 의 Reasoning task에서 best Performance를 낼 수 있도록 한다.

 

https://js.langchain.com/docs/modules/agents/

 

Agents | 🦜️🔗 Langchain

The core idea of agents is to use a language model to choose a sequence of actions to take.

js.langchain.com

 

역시나 제가 사랑하는 공식 문서를 참고해봅니다 ㅎㅎ

 

llm math tool

agent("What is the 25% of 300?")

 

다음과 같이 agent를 작동시킬 수 있다.

그럼 llm-math 툴이 동작하면서 300의 25%를 계산해 줄 것이다

(여러분들도 한 번 계산해보세요)

 

llm-math tool

 

verbose = True로 설정했기 때문에 다음과 같이 구체적인 tool load과정을 확인할 수 있다. 

action으로 Calculator가 설정되고 Action input을 통해 계산이 되는 것을 확인할 수 있다.

 

(참고로 llm-math tool은 python을 기반으로 이루어지며, 지난 번 언급했던 대규모 언어 모델이 단순한 수학적 계산을 잘 해내지 못해는 한계를 tool을 이용하여 극복해 낼 수 있다!)

 

 

예제 말고 하나 더 해보고 싶어서 GPT를 통해 prompt를 하나 생성 후 이를 기반으로도 agent를 작동시켜 보았다.

GPT 로 생성한 math problem prompt

 

 

Agent 실행 과정 및 결과

 

 

와우.. 신기하다..

 

 

 

Wikipedia tool

 

다음으로는 wiki pedia tool을 실습해 보았다.

예제에서는 다른 prompt를 이용하여 질문을 진행했는데,

나는 내가 제일 좋아하는 영국배우 우리의 스네이프 선생님에 대해 물어보았다.

 

스네이프를 연기한 Alan Rickman을 아시나요?

 

Wikipedia tool Agent

 

wikipedia API를 이용하여 wikipedia를 기반으로 한 검색을 진행하기 때문에 다음과 같이 결과가 출력되는 것을 확인할 수 있다.

알란의 대표작인 다이하드, 러브액츄얼리 등도 출력되는 것을 확인할 수 있다 !!!!

 

 

 

Python REPL

 

 앞서 말한대로, LLM model 같은 경우, 간단한 사칙연산을 못한다거나 하는 고질적인 문제가 존재한다고 했다. 그런 문제들을 해결하기 위해서 앞서 수학 계산 처럼 python tool을 이용해서 단계적으로 문제를 해결하곤 하는데, 그러기 위해 사용하는 tool이 바로 Python REPL tool 이다.

 

from langchain.agents import Tool
from langchain_experimental.utilities import PythonREPL

python_repl = PythonREPL()

 

REPL은 간단히 생각하면 Jupyter notebook 같은 것이라고 생각하면 된다!

REPL = Read Evaluate Print Loop (콘솔 화면에서 파이썬 구문을 입력하면 바로 결과를 반환하고 다시 입력할 수 있는 도구를 말한다.)

agent.run(f"""Sort these customers by \
last name and then first name \
and print the output: {customer_list}""")

 

요런 프롬프트를 사용하였다. 따라서 이름들을 정렬해야 한다.

 

python REPL

 

Python REPL tool을 이용해

sorted_customers = sorted(customers, key = lambda x : (x[1], x[0]))

for customer in sorted_customers : 
	print(customer)

 

요 파이썬 코드가 동작함을 확인할 수 있다.

 

이렇게 Python tool을 이용하면 CoT가 일어나는 일련의 과정을 확인할 수 있고, 또 앞서 배운 것 처럼 Langchain.debug 를 이용하면 그 과정을 좀 더 자세히 확인할 수 있다.

 


 

Agent의 가장 큰 장점은 Own Information, Own API, Own Data와 연결 가능하다는 것이다! 

따라서 Custom tool도 만들어 낼 수 있다.

 

custom tool은 아래를 참고하여 만들면 된다.

 

from langchain.agents import tool
from datetime import date

@tool
def time(text: str) -> str:
	"""Returns todays date, use this for any \
	questions related to knowing todays date. \
	The input should always be an empty string, \
	and this function will always return todays \
	date - any date mathmatics should occur \
	outside this function."""
	return str(date.today())

agent = initialize_agent(
	tools + [time]
	llm,
	agent = AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
	handle_parsing_errors = True,
	verbose = True)

 

Agent가 가끔 wrong concolusion을 내뱉을 수 있으므로 아래 코드를 따라해본다.

 

try : 
	result = agent("whats the date today?")
except : 
	print("exception on external access")