AI 에이전트는 LLM의 응용 분야로 각광받고 있는 분야 중 하나이다. 기존의 Chain이 고정된 흐름을 처리한다면, 어떤 처리를 할 것인지 LLM이 선택해서 움직여주기를 원하는 경우가 있을 수 있다. 가령, 사용자의 질의에 대해 필요에 따라 사내 문서를 Vector Store 에서 검색하여 답변하거나 웹 상의 정보를 바탕으로 답변해준다는 등으로 작동하면 LLM의 활용 범위는 크게 늘어날 수 있다. 이를 가능케 하는 것이 랭체인의 Agent 다.
에이전트 사용 예시
랭체인에는 다양한 종류의 Agents가 구현되어있다. 그 중, ReAct 라는 Agent를 사용하는 예시를 살펴보자.
from langchain import hub
from langchain.agents import AgentExecutor, create_react_agent, load_tools
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
tools = load_tools(["terminal"], allow_dangerous_tools=True)
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = agent_executor.invoke({"input": "sample_data 디렉터리에 있는 파일 목록을 알려줘"})
여기서 load_tools 라는 함수로 terminal 이라는 도구를 준비한다. terminal은 Bash와 같은 셸에서 명령을 실행할 수 있는 도구이다. 결과는 아래와 같다.
anscombe.json
california_housing_test.csv
california_housing_train.csv
mnist_test.csv
mnist_train_small.csv
README.md
실제로 코드 실행 환경 (Colab)에 있는 파일들과 일치하는 것을 확인할 수 있다. 이는 단순히 ChatGPT에게 질문을 해서 얻는 결과와 다르다. ( ChatGPT는 상상에 의한 결과 또는 추론에 의한 결과를 말해줄 것이다 )
Agents의 작동 원리와 ReAct 개념
앞서 소개된 ReAct는 'ReAct: Synergizing Reasoning adn Acting in Language Models'라는 논문에 소개한 메커니즘으로 작동한다. ReAct의 구조를 이해하기 위해서는 내부 프롬프트에 주목해야한다.
우선 다음 프롬프트에서 LLM이 호출된다.
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 the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought:{agent_scratchpad}
위 예시를 이 프롬프트에 적용해보면 결과는 아래와 같다.
I can use the terminal to list the files in the sample_data directory
Action: terminal
Action Input: ls sample_data
첫 번째 단계에서 LLM은 sample_data 디렉터리의 파일 목록을 나열하기 위해 터미널을 사용할 수 있다는 생각을 한다. 그 후, 액션이 terminal로 지정되었고 terminal에서 실행할 input을 결정한다.
랭체인의 Agent는 이 응답 문자열에서 Action과 Action Input의 내용을 정규식으로 추출한다. 그리고 terminal이라는 도구에서 'ls smaple_data'를 실행하고 싶다는 내용에 따라 실제로 셸에서 이를 실행한다.
Observation: anscombe.json
california_housing_test.csv
california_housing_train.csv
mnist_test.csv
mnist_train_small.csv
README.md
I now know the files in the sample_data directory.
Final Anser: anscombe.json
california_housing_test.csv
california_housing_train.csv
mnist_test.csv
mnist_train_small.csv
README.md
랭체인의 Agents는 Final Anser 부분을 최종 답변으로 가져온다.
Tools 그리고 Toolkits
랭체인의 Agents에는 다양한 툴을 부여할 수 있다. 대표적으로 아래와 같은 툴들이 존재하며, 스스로 도구를 직접 만들 수도 있다.
- terminal: 셸에서 명령어 실행하기
- Python_REPL: 파이썬 코드 실행하기
- google_search: 구글에서 검색하기
- Wikipedia: 위키피디아 검색하기
- human: 인간에게 입력하게 하기
Toolkits은 동시에 사용할 수 있는 몇 가지 툴을 모아놓은 것이다.
- GmailToolkit: Gmail에서 이메일 검색 및 전송
- JiraToolkit: Jira에서 과제 검색 및 생성
- SQLDatabaseToolkit: 데이터베이스 스키마 가져오기 및 SQL 실행
- VectorStoreToolkit: 벡터 스토어의 단순 검색과 소스가 포함된 검색
Function calling을 사용하는 에이전트
ReAct나 Plan-and-Solve와 같은 방식으로 Agents를 구동할 수 있지만 이 방식으로 안정적으로 동작하는 것은 쉽지 않다. LLM이 지정된 출력 형식을 다르지 않아서 에이전트의 실행에 오류가 발생하는 경우가 종종 있기 때문이다.
Function calling을 사용하는 Agents를 사용하면 작동이 안정적이다. 예시는 다음과 같다.
from langchain.agents import load_tools
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
tools = load_tools(["terminal"], allow_dangerous_tools=True)
prompt = hub.pull("hwchase17/openai-functions-agent")
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "sample_data 디렉터리에 있는 파일 목록을 알려줘"})
'Programming > Langchain' 카테고리의 다른 글
LCEL 에 관하여 (3) | 2024.12.05 |
---|---|
랭체인 활용 - Data Connection (3) | 2024.10.09 |
랭체인 기초 (1) | 2024.09.19 |