인공지능 Agent는 사용자의 요청을 받은 후 어떤 기능을 어떤 순서로 실행할지 결정하는 역할을 합니다. Agent의 주요 특징들은 다음과 같습니다.
- 목표(정책) 기반 행동: 주어진 목표를 달성하기 위해 행동합니다.
- 자율성: 목표가 주어지면 자동으로 작동합니다.
- 감지: 주변 환경에서 정보를 수집합니다.
Tools는 Agent가 할 수 있는 일에 해당합니다. 도구, 기술, 함수들이죠.
Agent의 작업 처리 순서도
Agent의 처리 흐름은 다음과 같습니다.
- Input: 사용자가 Agent에게 작업을 할당합니다.
- Thought: Agent가 작업을 완수하기 위해 무엇을 할지 생각합니다.
- Action/Action Input: 사용할 도구를 결정하고, 도구의 입력(함수의 입력값)을 결정합니다.
- Observation: 도구의 출력 결과를 관찰합니다.
- 관찰 결과 작업을 완료(Finish)했다는 판단에 도달할 때까지 2~4번 과정을 반복합니다.
위의 과정이 Agent의 작업 수행 과정인데, LangChain에서는 이 과정을 처리하는 객체를 Agent Executor라고 합니다.
LangChain Agent의 종류
LangChain에는 여러 종류의 Agent들이 있습니다. 몇 가지를 살펴보겠습니다.
- Zero-shot ReAct: 작업과 도구 설명을 보고 사용할 도구를 결정합니다. ReAct는 Reasoning + Acting으로 Yao et al. (2022)의 논문에 소개된 개념입니다. Reasoning은 생각(Chain-of-Thought, COT), Acting은 외부 도구 실행을 의미합니다.
- Structured input ReAct: input이 여러 개인 도구를 사용할 때 필요한 Agent입니다.
- Conversational: 대화 + ReAct로 대화 저장을 위한 메모리가 필요합니다.
- Self-ask with search: 인터넷 검색 후 답변하는 Agent로 검색 도구가 필요합니다.
- ReAct document store: 문서 저장소 + ReAct로 문서 검색 도구가 필요합니다.
필요한 작업에 따라 정하면 되는데, Zero-shot ReAct가 가장 기본이 되는 Agent입니다.
LangChain Tools
LangChain Tools는 Agent가 수행하는 특정 기능으로, 외부 환경에 영향을 끼쳐 Agent가 새로운 정보를 관찰할 수 있도록 합니다. 도구를 추가할 때마다 LLM에 새로운 능력을 부여하는 셈이죠. 영화 매트릭스에서 트리니티가 순식간에 헬리콥터 조종 기술을 다운받는 것처럼 LLM에게도 순식간에 새로운 능력을 가르칠 수 있습니다. LangChain에는 미리 준비된 다양한 도구들이 존재하고, 필요하면 직접 도구를 만들어 쓸 수도 있습니다. LangChain의 기본 도구들을 몇 가지 살펴보겠습니다.
- 일반적인 검색 도구: Google, Bing, DuckDuckGo
- 특수 목적 검색 도구: Wolfram Alpha, Wikipedia, Youtube, Weather, News
- 수학 계산: Math
- 인터넷 RestAPI: Requests
- 컴퓨터: Shell, Python REPL
이 외에도 여러 가지 도구들이 계속 추가되고 있습니다. 도구들 중에는 별도의 API 키가 필요한 도구도 있고, 무료로 사용할 수 있는 도구들도 있습니다. API 키가 필요한 도구들은 사용량에 따라 해당 서비스 제공자에게 사용료를 지불해야 할 수도 있습니다. 또한 도구들 중에는 실행을 위해 LLM이 필요한 도구도 있고 필요 없는 도구도 있습니다. LLM이 필요한 도구는 사용시 LLM을 지정해줘야 합니다.
예제: Math, Wikipedia
예제 코드를 보겠습니다.
!pip install langchain openai wikipedia
from langchain.chat_models import ChatOpenAI
from langchain.agents import load_tools, initialize_agent
llm = ChatOpenAI(temperature=0)
tools = load_tools(["llm-math","wikipedia"], llm=llm)
# llm-math 도구는 llm이 필요합니다.
agent= initialize_agent(
tools,
llm,
agent='zero-shot-react-description',
handle_parsing_errors=True,
verbose = True)
# 수학 문제
agent("500의 20.5%는 몇인가요?")
# 결과: {'input': '500의 20.5%는 몇인가요?', 'output': '102.5'}
# wikipedia 검색 문제
question = "광안대교 길이는 몇 km인가요?"
result = agent(question)
# 결과: {'input': '광안대교 길이는 몇 km인가요?', 'output': 'The length of the Gwangan Bridge is 7,420 meters.'}
LangChain 내부 프롬프트들이 영어로 되어 있어서 응답 결과는 기본적으로 영어로 나옵니다. Wikipedia 도구는 Wikipedia에서 검색한 페이지의 내용을 모두 가져오는게 아니라 요약 부분만 가져오기 때문에 요약 부분에 원하는 내용이 없으면 질문에 대한 답을 못 찾을 수도 있습니다. 그럴땐 Python wikipedia 라이브러리를 이용해 페이지 전체를 받아서 답을 찾는 사용자 정의 도구를 만들거나 다른 검색 도구를 사용할 수 있습니다. 다음 예제에서 DuckDuckGo 검색엔진을 사용해봅시다.
예제: DuckDuckGo Search
! pip install duckduckgo-search
tools = load_tools(["ddg-search"])
agent= initialize_agent(
tools,
llm,
agent='zero-shot-react-description',
handle_parsing_errors=True,
verbose = True)
result = agent(question)
# 결과: {'input': '광안대교 길이는 몇 km인가요?', 'output': 'The length of the Gwangan Bridge is 7.4 kilometers.'}
Google이나 Bing은 API Key가 필요하지만, DuckDuckGo는 API Key 없이 사용할 수 있는 검색엔진입니다.
예제: Youtube
이번엔 인터넷 검색에 유튜브 검색까지 같이 해봅시다.
! pip install youtube_search
from langchain.tools import YouTubeSearchTool
tools = load_tools(["ddg-search"]) + [YouTubeSearchTool()]
agent= initialize_agent(
tools,
llm,
agent='zero-shot-react-description',
handle_parsing_errors=True,
verbose = True)
result = agent("이퀼리브리엄 영화에서 주인공이 저항군 아지트에서 들은 클래식 음악이 무엇인지 찾아서 유튜브 링크를 알려줘")
### 길지만 이해를 위해 중간 과정을 살펴 봅시다.
Entering new AgentExecutor chain...
- Thought: I need to find the name of the classical music heard by the protagonist in the movie "Equilibrium" and provide a YouTube link.
- Action: duckduckgo_search
- Action Input: "Equilibrium movie protagonist classical music"
- Observation: What classical music is played in the movie 'Equilibrium'? The character of Preston listens to Ludwig van Beethoven 's 9th Symphony, First Movement that he accidentally activates on the Victrola. If the audio is a recording of the actual song please check the replies to this comment to see if the bots u/RecognizeSong, u/songfinderbot and u/find-song identified it correctly :) (might take a few seconds to reply) . Please flair your post as Answered if the bots got it right, or comment to say if they listed the wrong song(s), so that people would know if help is still needed. What classical music is played in the movie 'Equilibrium'? The character of Preston listens to Ludwig van Beethoven's 9th Symphony, First Movement that he accidentally activates on the Victrola. What classical music is played in the movie 'Equilibrium'? The character of Preston listens to Ludwig van Beethoven's 9th Symphony, First Movement that he accidentally activates on the Victrola. Equilibrium hit theaters on Dec. 6, 2002, with a budget of $20 million. It only made $5 million back. That's despite a positive review from Roger Ebert, who praised the film's blend of ...
- Thought:I have found the name of the classical music heard in the movie "Equilibrium" and it is Ludwig van Beethoven's 9th Symphony, First Movement.
- Action: youtube_search
- Action Input: "Ludwig van Beethoven 9th Symphony First Movement,1"
- Observation: 'https://www.youtube.com/watch?v=VKxX2EJozxo&pp=ygUwTHVkd2lnIHZhbiBCZWV0aG92ZW4gOXRoIFN5bXBob255IEZpcnN0IE1vdmVtZW50'
- Thought:I now know the final answer.
- Final Answer: The classical music heard by the protagonist in the movie "Equilibrium" is Ludwig van Beethoven's 9th Symphony, First Movement. You can listen to it on YouTube at this link: [https://www.youtube.com/watch?v=VKxX2EJozxo&pp=ygUwTHVkd2lnIHZhbiBCZWV0aG92ZW4gOXRoIFN5bXBob255IEZpcnN0IE1vdmVtZW50]
- Finished chain.
# 최종 반환값입니다.
{'input': '이퀼리브리엄 영화에서 주인공이 저항군 아지트에서 들은 클래식 음악이 무엇인지 찾아서 유튜브 링크를 알려줘',
'output': 'The classical music heard by the protagonist in the movie "Equilibrium" is Ludwig van Beethoven\'s 9th Symphony, First Movement. You can listen to it on YouTube at this link: [https://www.youtube.com/watch?v=VKxX2EJozxo&pp=ygUwTHVkd2lnIHZhbiBCZWV0aG92ZW4gOXRoIFN5bXBob255IEZpcnN0IE1vdmVtZW50]'}
앞에 나온 순서도의 중간 과정을 두 번 반복했습니다. 먼저 DuckDuckGo 검색을 사용하고 그 결과를 이용해 두 번째에는 Youtube 검색으로 최종 결과를 얻었습니다. 만약 Youtube 링크가 주어졌을 때 영상을 틀어주는 도구를 추가한다면 바로 음악을 틀어달라고 요청할 수도 있겠죠? 이번엔 사용자 지정 도구를 만들어 봅시다.
예제: 사용자 도구 만들기
사용자 도구는 LangChain의 tool 데코레이터로 함수를 꾸며주면 됩니다. 함수 설명 문자열에 함수의 기능과 입력 인자 정보를 넣어야 Agent에서 해당 내용을 보고 어떤 도구인지, 어떻게 사용하는지 알 수 있습니다. OpenAI API의 Function Call에서 함수와 인자의 description에 해당하는 부분이죠. LLM이 사용하는 도구이므로 함수의 입력과 출력은 모두 문자열로 해줍니다.
from langchain.agents import tool
from datetime import date
@tool
def date_today(text):
"""오늘 날짜 반환, input은 ''"""
return str(date.today())
agent= initialize_agent(
[date_today],
llm,
agent='zero-shot-react-description',
handle_parsing_errors=True,
verbose = True)
agent("오늘 날짜는?")
{'input': '오늘 날짜는?', 'output': '오늘 날짜는 2023-10-26입니다.'}
이렇게 OpenAI API의 함수 호출 기능에 비해 비교적 간단히 LLM에게 새로운 기능을 추가해줄 수 있습니다.










