5️⃣Agents

LangChain: Agents

import os
from dotenv import load_dotenv  

load_dotenv()
api_key = os.getenv("<OPENAI_API_KEY>")
os.environ["SERPAPI_API_KEY"] = "<Serp_API_KEY>" # Serp API 가입 후 key 발급
# 패키지 설치
#%pip install google-search-results
from langchain.agents import load_tools
from langchain.chat_models import ChatOpenAI

# 도구 준비
tools = load_tools(
    tool_names=["serpapi", "llm-math"], # 도구 이름
    llm=ChatOpenAI(
        model="gpt-3.5-turbo",
        temperature=0
    ) # 도구의 초기화에 사용할 LLM
)
from langchain.chains.conversation.memory import ConversationBufferMemory

# 메모리 생성
memory = ConversationBufferMemory(
    memory_key="chat_history", 
    return_messages=True
)
from langchain.agents import initialize_agent

# 에이전트 생성
agent = initialize_agent(
    agent="chat-conversational-react-description", # 에이전트 유형 설정
    llm=ChatOpenAI(
        model="gpt-3.5-turbo",
        temperature=0
    ), # 에이전트 초기화에 사용할 LLM
    tools=tools, # 도구
    memory=memory, # 메모리
    verbose=True # 상세 정보 출력
)
# 에이전트 실행
agent.run("좋은 아침입니다.")
> Entering new AgentExecutor chain...
```json
{
    "action": "Final Answer",
    "action_input": "Good morning!"
}
```

> Finished chain.





'Good morning!'
# 에이전트 실행
agent.run("우리집 반려견 이름은 보리입니다.")
> Entering new AgentExecutor chain...
```json
{
    "action": "Final Answer",
    "action_input": "우리집 반려견 이름은 보리입니다."
}
```

> Finished chain.





'우리집 반려견 이름은 보리입니다.'
# 에이전트 실행
agent.run("우리집 반려견 이름을 불러주세요.")
> Entering new AgentExecutor chain...
```json
{
    "action": "Final Answer",
    "action_input": "우리집 반려견 이름은 보리입니다."
}
```

> Finished chain.





'우리집 반려견 이름은 보리입니다.'
# 에이전트 실행
agent.run("123*4를 계산기로 계산해 주세요")
> Entering new AgentExecutor chain...
```json
{
    "action": "Calculator",
    "action_input": "123*4"
}
```
Observation: Answer: 492
Thought:```json
{
    "action": "Final Answer",
    "action_input": "492"
}
```

> Finished chain.





'492'
# 에이전트 실행
agent.run("오늘 서울의 날씨를 웹에서 검색해 주세요.")
> Entering new AgentExecutor chain...
```json
{
    "action": "Search",
    "action_input": "Today's weather in Seoul"
}
```
Observation: {'type': 'weather_result', 'temperature': '53', 'unit': 'Fahrenheit', 'precipitation': '0%', 'humidity': '91%', 'wind': '6 mph', 'location': 'Seoul, South Korea', 'date': 'Monday', 'weather': 'Cloudy'}
Thought:```json
{
    "action": "Final Answer",
    "action_input": "The weather in Seoul, South Korea on Monday is cloudy with a temperature of 53°F, 0% precipitation, 91% humidity, and wind speed of 6 mph."
}
```

> Finished chain.





'The weather in Seoul, South Korea on Monday is cloudy with a temperature of 53°F, 0% precipitation, 91% humidity, and wind speed of 6 mph.'

Last updated