학습일지/AI

Simple LangChain Agent with OpenAI, Wikipedia, DuckDuckGo

inspirit941 2024. 4. 26. 16:59
반응형

LangChain Agents (2024 update)

https://youtu.be/WVUITosaG-g?si=M6fkM-NlUM6XeMJb

 

 

  • duckduckgo, wikipedia를 langchain agent로 사용하는 방법
!pip install duckduckgo-search wikipedia langchain langchainhub langchain_openai

import os
os.environ['OPENAI_API_KEY'] = "your api key"

from langchain_openai import ChatOpenAI
from langchain import hub
from langchain.agents import create_openai_functions_agent
from langchain.agents import AgentExecutor
from langchain.schema import HumanMessage, SystemMessage

llm = ChatOpenAI(temperature=0.5)

## try to find 2023 월드시리즈 챔피언

message = [
  SystemMessage(
    content="A user will input a year, and you will get the baseball world series champion"
  ),
  HumanMessage(
    content="2023"
  ),
]

llm.invoke(message)
# chatgpt는 2023년 데이터를 학습하지 않은 상태이므로 '모른다'고 답변한다.

위키피디아에서 정보를 검색하도록 해보자.

# 공식문서에서 또 바뀌었을 수도 있다.
prompt = hub.pull("hwchase17/openai-functions-agent")

from langchain.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper


api_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=500)
wikitool = WikipediaQueryRun(api_wrapper=api_wrapper)
tools =[
  wikitool
]

agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools = tools)

agent_executor.invoke({"input":"Who won the 2023 world series?"})
## 2023 월드시리즈 우승팀인 텍사스 레인저스를 응답한다.
## duckduckgo, llm math를 tool로 추가한다
from langchain import LLMMathChain
from langchain.agents import Tool


llm_math_chain = LLMMathChain.from_llm(llm=llm, verboase=True)
math_tool = Tool.from_function(
  func=llm_math_chain.run,
  name="calculator",
  description="useful for answering math question. Only math questions and nothing else. Only input math expression.",
)

from langchain.tools import DuckDuckGoSearchRun

search = DuckDuckGoSearchRun()
tools2 = [search, math_tool]

agent2 = create_openai_functions_agent(llm=llm, tool=tools, prompt=prompt)
agent_executor2 = AgentExecutor(agent=agent2, tools=tools2, verbose=True)

agent_executor2.invoke({"input":"Who won the 2021 world series and how many years was it since their last world series won?"})

스크린샷 2024-05-09 오전 10 08 13

 

반응형