본문 바로가기

IT/개발

(6) Langchain에서 agent와 tool을 사용해보자

반응형

 LangChain에서는 엄청나게 다양한 tool을 연동해서 기능을 구현할 수 있습니다. 

 

agent는 체인이 사용할 도구를 선택해서 지원할 수 있도록하며 LLM을 사용하여 원하는 작업을 수행하는 절차를 정의할 수 있습니다.   이때 어떠한 도구를 사용하여 목적을 달성할 것인지를 스스로 판단하여 사용합니다.

사용자는 구현된 tool이 어떠한 동작을 하는지 정확하게 description 해주기만 하면 알아서 가져다가 쓰도록 되어 있습니다.  

 

agent가 올바른 tools을 사용할 수 있도록 액세스 권한 지정하고 agent가 tool의 기능과 사용법을 알수 있도록 설명하면 되는 것이지요

 

여기서는 wikipedia api tool과 llm-math tool 2가지를 이용하여 현재 미국 대통령이 누구인지 알아내고 그의 나이를 이용하여 간단한 계산을 수행하는 예제를 구현해보도록 하겠습니다. 

 

LangChain에서 제공가능한 다양한 tool의 예는 다음에서 확인하실 수 있습니다.

 

https://python.langchain.com/docs/integrations/tools/

 

Tools | 🦜️🔗 Langchain

📄️ DataForSeo API Wrapper This notebook demonstrates how to use the DataForSeo API wrapper to obtain search engine results. The DataForSeo API allows users to retrieve SERP from most popular search engines like Google, Bing, Yahoo. It also allows to g

python.langchain.com

 

1.  chat 모델 지정 

openAI 를 사용하기 위해 api key를 미리 발급 받아야 합니다. 

 

또한 wikipedia api를 사용하기 위해 패키지를 설치합니다. 

>  pip install wikipedia

 

import os
import apikeys #user defind, apikeys 숨기기

#pip install wikipedia #tool로 사용하고자 함

from langchain.chat_models import ChatOpenAI

#https://platform.openai.com/account/api-keys 에서 발급받는다. 유료

OPENAI_API_KEY = apikeys.OPENAI_API_KEY

#환경 변수에 넣어준다
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY

chatAI = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0.1)

 

2. tool 지정 및 기능 구현  

 


from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType

#Tool: 각각의 기능을 수행하는 도구 예) 구글 검색, wikipedia 검색, 계산, 데이터 조회 등
#Agents: 수많은 tools의 디스크립션을 보고 어떤 tool을 사용할지 어떤 순서로 사용할지를 판단하고 실행

#다양한 tools 참고

tools = load_tools(["wikipedia","llm-math"], llm=chatAI)

#다양한 agent 참고

agent = initialize_agent(tools, llm=chatAI, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

AI_response = agent.run("현재 미국 대통령이 누구인지? 그리고 그 사람의 현재 나이를 3배로 곱해")

#등록한 tools 정보를 확인
#중요한건 description
print(agent.tools)
print(AI_response)

 

간단하게 이렇게 구성하면 agent가 설정된 tools 중에서 필요한 부분을 알아서 가져다가 적용을 시작합니다. 

verbose=True로 설정해 놓으면 진행 과정을 모둘 확인 가능합니다 .

 

아래의 내용을 보시면 "The current president of the United States is Joe Biden, and his current age multiplied by 3 is 234."

마지막 결론을 내기 위해서 어떻게 추론을 진행 했는지 절차를 확인할 수 있네요. 

 


'''
> Entering new AgentExecutor chain...
I need to find out who the current president of the United States is and then calculate their current age multiplied by 3.
Action: Wikipedia
Action Input: "current president of the United States"
Observation: Page: President of the United States
Summary: The president of the United States (POTUS) is the head of state and head of government of the United States. The president directs the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces.
The power of the presidency has grown substantially since the first president, George Washington, took office in 1789. While presidential power has ebbed and flowed over time, the presidency has played an increasingly significant role in American political life since the beginning of the 20th century, with notable expansion during the presidency of Franklin D. Roosevelt. In modern times, the president is one of the world's most powerful political figures – the leader of the only remaining global superpower. As the leader of the nation with the largest economy by nominal GDP, the president possesses significant domestic and international hard and soft power.
Article II of the Constitution establishes the executive branch of the federal government and vests executive power in the president. The power includes the execution and enforcement of federal law and the responsibility to appoint federal executive, diplomatic, regulatory, and judicial officers.  Based on constitutional provisions empowering the president to appoint and receive ambassadors and conclude treaties with foreign powers, and on subsequent laws enacted by Congress, the modern presidency has primary responsibility for conducting U.S. foreign policy. The role includes responsibility for directing the world's most expensive military, which has the second largest nuclear arsenal.
The president also plays a leading role in federal legislation and domestic policymaking. As part of the system of separation of powers, Article I, Section 7 of the Constitution gives the president the power to sign or veto federal legislation. Since modern presidents are typically viewed as leaders of their political parties, major policymaking is significantly shaped by the outcome of presidential elections, with presidents taking an active role in promoting their policy priorities to members of Congress who are often electorally dependent on the president. In recent decades, presidents have also made increasing use of executive orders, agency regulations, and judicial appointments to shape domestic policy.
The president is elected indirectly through the Electoral College to a four-year term, along with the vice president. Under the Twenty-second Amendment, ratified in 1951, no person who has been elected to two presidential terms may be elected to a third. In addition, nine vice presidents have become president by virtue of a president's intra-term death or resignation. In all, 45 individuals have served 46 presidencies spanning 58 four-year terms. Joe Biden is the 46th and current president of the United States, having assumed office on January 20, 2021.

Page: List of presidents of the United States
Summary: The president of the United States is the head of state and head of government of the United States, indirectly elected to a four-year term via the Electoral College. The officeholder leads the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces. Since the office was established in 1789, 45 men have served in 46 presidencies. The first president, George Washington, won a unanimous vote of the Electoral College; one, Grover Cleveland, served two non-consecutive terms and is therefore counted as the 22nd and 24th president of the United States, giving rise to the discrepancy between the number of presidencies and the number of persons who have served as president. The incumbent president is Joe Biden.The presidency of William Henry Harrison, who died 31 days after taking office in 1841, was the shortest in American history. Franklin D. Roosevelt served the longest, over twelve years, before dying early in his fourth term in 1945. He is the only U.
Thought:I have found the information about the current president of the United States. Now I need to calculate their current age multiplied by 3.
Action: Wikipedia
Action Input: "Joe Biden"
Observation: Page: Joe Biden
Summary: Joseph Robinette Biden Jr. ( (listen) BY-dən; born November 20, 1942) is an American politician who is the 46th and current president of the United States. A member of the Democratic Party, he previously served as the 47th vice president from 2009 to 2017 under President Barack Obama and represented Delaware in the United States Senate from 1973 to 2009.
Born in Scranton, Pennsylvania, Biden moved with his family to Delaware in 1953. He studied at the University of Delaware before earning his law degree from Syracuse University. He was elected to the New Castle County Council in 1970 and to the U.S. Senate in 1972. As a senator, Biden drafted and led the effort to pass the Violent Crime Control and Law Enforcement Act and the Violence Against Women Act; and oversaw six U.S. Supreme Court confirmation hearings, including the contentious hearings for Robert Bork and Clarence Thomas. Biden ran unsuccessfully for the Democratic presidential nomination in 1988 and 2008. In 2008, Barack Obama chose Biden as his running mate, and Biden was a close counselor to Obama during his two terms as vice president. In the 2020 presidential election, Biden and his running mate, Kamala Harris, defeated incumbents Donald Trump and Mike Pence.
Taking office at age 78, Biden is the oldest president in U.S. history, the first to have a female vice president, and the first from Delaware. In 2021, he signed a bipartisan infrastructure bill, as well as a $1.9 trillion economic stimulus package in response to the COVID-19 pandemic and subsequent recession. Biden proposed the Build Back Better Act, which failed in Congress, but aspects of which were incorporated into the Inflation Reduction Act that was signed into law in 2022. Biden also signed the bipartisan CHIPS and Science Act, which focused on manufacturing. He appointed Ketanji Brown Jackson to the Supreme Court. He worked with congressional Republicans to prevent a first ever national default by negotiating a deal to raise the debt ceiling. In foreign policy, Biden restored America's membership in the Paris Agreement. He oversaw the complete withdrawal of U.S. troops from Afghanistan that ended the war in Afghanistan, during which the Afghan government collapsed and the Taliban seized control. Biden has responded to the Russian invasion of Ukraine by imposing sanctions on Russia and authorizing civilian and military aid to Ukraine. In April 2023, he announced his candidacy for the Democratic Party nomination in the 2024 presidential election.

Page: Family of Joe Biden
Summary: Joe Biden, the 46th and current president of the United States, has family members who are prominent in law, education, activism and politics. Biden's immediate family became the first family of the United States on his inauguration on January 20, 2021. His immediate family circle was also the second family of the United States from 2009 to 2017, when Biden was vice president.  Biden's family is mostly descended from the British Isles, with most of their ancestors coming from Ireland and England, and a smaller number descending from the French.Of Joe Biden's sixteen great-great grandparents, ten were born in Ireland. He is descended from the Blewitts of County Mayo and the Finnegans of County Louth. One of Biden's great-great-great grandfathers was born in Sussex, England, and emigrated to Maryland in the United States by 1820.



Page: Presidency of Joe Biden
Summary: Joe Biden's tenure as the 46th president of the United States began with his inauguration on January 20, 2021. Biden, a Democrat from Delaware who previously served as vice president under Barack Obama, took office following his victory in the 2020 presidential election over Republican incumbent president Donald Trump. Upon his inauguration, he became the oldest president in American history. Biden entered office amid the COVID-19 pandemic, an economic crisis, and increased political polarization.On the first day of his presidency, B
Thought:I have found the information about Joe Biden, the current president of the United States. Now I can calculate his current age multiplied by 3.
Action: Calculator
Action Input: 78 * 3
Observation: Answer: 234
Thought:I now know the final answer.
Final Answer: The current president of the United States is Joe Biden, and his current age multiplied by 3 is 234.

> Finished chain.
The current president of the United States is Joe Biden, and his current age multiplied by 3 is 234.
'''

 

반응형

 

참고. langchain에서 지원하는 tools 

 


'''
chain에 사용가능한 다양한 tools

DataForSeo API Wrapper
Google Serper API
SerpAPI
Google Search
Python REPL
Zep Memory
Dynamodb Chat Message History
Google Serper
Document Comparison
Natural Language APIs
Github Toolkit
Comparing Chain Outputs
Agent VectorDB Question Answering Benchmarking
AutoGPT
BabyAGI with Tools
Plug-and-Plai
Wikibase Agent
SalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base
Custom Agent with PlugIn Retrieval
Agent Debates with Tools
Adding Message Memory backed by a database to an Agent
How to add Memory to an Agent
Multi-Input Tools
Defining Custom Tools
Self ask with search
ReAct document store
OpenAI Multi Functions Agent
Combine agents and vector stores
Custom MRKL agent
Handle parsing errors
Shared memory across agents and tools
Custom multi-action agent
Running Agent as an Iterator
Timeouts for agents
Add Memory to OpenAI Functions Agent
Cap the max number of iterations
Custom agent
Use ToolKits with OpenAI Functions
Custom agent with tool retrieval
'''

 

 

반응형