Langchain에서 agent를 생성할 때 AgentType을 선택할 수 있었는데 AgentType들이 어떤것이 있는지 확인해보려고 한다.

 

from langchain.agents import initialize_agent, Tool
from langchain.agents.agent_types import AgentType
from langchain_community.chat_models import ChatOpenAI

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

 

AgentType

확인해보니 deprecated되었다고 한다. 그렇다면 어떤걸 사용하는게 좋을까?

@deprecated(
    "0.1.0",
    message=AGENT_DEPRECATION_WARNING,
    removal="1.0",
)
class AgentType(str, Enum):
    """An enum for agent types.

    See documentation: https://python.langchain.com/docs/modules/agents/agent_types/
    """

    ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
    """A zero shot agent that does a reasoning step before acting."""

    REACT_DOCSTORE = "react-docstore"
    """A zero shot agent that does a reasoning step before acting.
    
    This agent has access to a document store that allows it to look up 
    relevant information to answering the question.
    """

    SELF_ASK_WITH_SEARCH = "self-ask-with-search"
    """An agent that breaks down a complex question into a series of simpler questions.
    
    This agent uses a search tool to look up answers to the simpler questions
    in order to answer the original complex question.
    """
    CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-description"
    CHAT_ZERO_SHOT_REACT_DESCRIPTION = "chat-zero-shot-react-description"
    """A zero shot agent that does a reasoning step before acting.
    
    This agent is designed to be used in conjunction 
    """

    CHAT_CONVERSATIONAL_REACT_DESCRIPTION = "chat-conversational-react-description"

    STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION = (
        "structured-chat-zero-shot-react-description"
    )
    """An zero-shot react agent optimized for chat models.
    
    This agent is capable of invoking tools that have multiple inputs.
    """

    OPENAI_FUNCTIONS = "openai-functions"
    """An agent optimized for using open AI functions."""

    OPENAI_MULTI_FUNCTIONS = "openai-multi-functions"

 

AGENT_DEPRECATION_WARNING

langchain의 agnet는 여전히 지원하지만 LangGraph를 사용하면 유연하게 구성할 수 있다고 한다.

추후 LangGraph를 사용하는 방법도 공부 해야겠다.

공부할 todo를 정해야할듯 하다.

AGENT_DEPRECATION_WARNING = (
    "LangChain agents will continue to be supported, but it is recommended for new "
    "use cases to be built with LangGraph. LangGraph offers a more flexible and "
    "full-featured framework for building agents, including support for "
    "tool-calling, persistence of state, and human-in-the-loop workflows. For "
    "details, refer to the "
    "`LangGraph documentation <https://langchain-ai.github.io/langgraph/>`_"
    " as well as guides for "
    "`Migrating from AgentExecutor <https://python.langchain.com/docs/how_to/migrate_agent/>`_"  # noqa: E501
    " and LangGraph's "
    "`Pre-built ReAct agent <https://langchain-ai.github.io/langgraph/how-tos/create-react-agent/>`_."  # noqa: E501
)

 

agentType enum의 설명을 찾아보자

https://python.langchain.com/api_reference/langchain/agents/langchain.agents.agent_types.AgentType.html

 

AgentType — 🦜🔗 LangChain documentation

Deprecated since version 0.1.0: LangChain agents will continue to be supported, but it is recommended for new use cases to be built with LangGraph. LangGraph offers a more flexible and full-featured framework for building agents, including support for tool

python.langchain.com

 

용어 정리

Zero-Shot: 이전에 학습되어 있는 모델을 가지고 배우지 않은 작업을 수행하는 것 즉, 현재 모델로 일반화된 작업을 수행하게 한다. (간단히 말하면 기본상모델)

reasoning, ReAct: Tool 선택의 추론과정 및 사용
https://arxiv.org/abs/2210.03629

 

ReAct: Synergizing Reasoning and Acting in Language Models

While large language models (LLMs) have demonstrated impressive capabilities across tasks in language understanding and interactive decision making, their abilities for reasoning (e.g. chain-of-thought prompting) and acting (e.g. action plan generation) ha

arxiv.org

Document Store: 특정 도메인을 관련된 정보를 저장해둔 벡터 저장소, RAG 구성할 때 사용된다.

 

  1. ZERO_SHOT_REACT_DESCRIPTION:  학습되지 않은 범용 agent를 사용하며 동작하기 전 Tool 선택의 추론 과정을 거친다.
  2. REACT_DOCSTORE:  1번 agent + 질문에 관련된 정보를 찾기 위해 Document Store를 사용한다. (즉 RAG)
  3. SELF_ASK_WITH_SEARCH: 복잡한 질문을 여러개의 간단한 질문으로  변환한다. 
    이 agent는 변환한 간단한 질문의 답을 찾기위해 검색툴을 이용한다.
  4. CONVERSATIONAL_REACT_DESCRIPTION: 문맥을 유지
  5. CHAT_ZERO_SHOT_REACT_DESCRIPTION : 문맥을 유지하지 않는 단발성 대화
  6. CHAT_CONVERSATIONAL_REACT_DESCRIPTION: 문맥을 유지하는 대화
  7. STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION : 일반적인 텍스트가아닌 특정 형식으로 구성된 대화

 

TODO

  • Conversational과 chat이 문맥 유지의 여부 차이인데 그렇다면  ONVERSATIONAL_REACT_DESCRIPTION 과 CHAT_CONVERSATIONAL_REACT_DESCRIPTION는 어떤 차이가 있는지 소스 및 프롬프트를 비교해
  • LangGraph를 공부

업무에서는 nginx를 사용하기 이미 설치가 되어 있는 상태였으나 신규로 아파치를 설치하고 사용해야하는 일이 생겼다.

또한 추후 인터넷을 사용할 수 없는 상황에서 설치할 수 있기 때문에 이번에 패키지를 yum install 이 아닌 download 후 install 하는 방식으로 하고자한다.

 

1. 패키지 다운로드 (인터넷 되는 환경에서)

httpd 패키지 다운로드

sudo yum install --downloadonly --downloaddir=./ httpd

 

[ec2-user apache]$ sudo yum install --downloadonly --downloaddir=./ httpd
Updating Subscription Management repositories.
Unable to read consumer identity

This system is not registered with an entitlement server. You can use "rhc" or "subscription-manager" to register.

Last metadata expiration check: 0:02:41 ago on Mon 21 Apr 2025 03:12:48 PM KST.
Dependencies resolved.
============================================================================================================================================================================================================
 Package                                           Architecture                          Version                                            Repository                                                 Size
============================================================================================================================================================================================================
Installing:
 httpd                                             x86_64                                2.4.62-1.el9_5.2                                   rhel-9-appstream-rhui-rpms                                 51 k
Installing dependencies:
 apr                                               x86_64                                1.7.0-12.el9_3                                     rhel-9-appstream-rhui-rpms                                126 k
 apr-util                                          x86_64                                1.6.1-23.el9                                       rhel-9-appstream-rhui-rpms                                 97 k
 apr-util-bdb                                      x86_64                                1.6.1-23.el9                                       rhel-9-appstream-rhui-rpms                                 14 k
 httpd-core                                        x86_64                                2.4.62-1.el9_5.2                                   rhel-9-appstream-rhui-rpms                                1.5 M
 httpd-filesystem                                  noarch                                2.4.62-1.el9_5.2                                   rhel-9-appstream-rhui-rpms                                 15 k
 httpd-tools                                       x86_64                                2.4.62-1.el9_5.2                                   rhel-9-appstream-rhui-rpms                                 86 k
 mailcap                                           noarch                                2.1.49-5.el9                                       rhel-9-baseos-rhui-rpms                                    35 k
 redhat-logos-httpd                                noarch                                90.4-2.el9                                         rhel-9-appstream-rhui-rpms                                 18 k
Installing weak dependencies:
 apr-util-openssl                                  x86_64                                1.6.1-23.el9                                       rhel-9-appstream-rhui-rpms                                 17 k
 mod_http2                                         x86_64                                2.0.26-2.el9_4.1                                   rhel-9-appstream-rhui-rpms                                167 k
 mod_lua                                           x86_64                                2.4.62-1.el9_5.2                                   rhel-9-appstream-rhui-rpms                                 60 k

Transaction Summary
============================================================================================================================================================================================================
Install  12 Packages

Total download size: 2.2 M
Installed size: 6.1 M
YUM will only download packages for the transaction.
Is this ok [y/N]: y
Downloading Packages:
(1/12): apr-util-openssl-1.6.1-23.el9.x86_64.rpm                                                                                                                            439 kB/s |  17 kB     00:00
(2/12): apr-util-bdb-1.6.1-23.el9.x86_64.rpm                                                                                                                                353 kB/s |  14 kB     00:00
(3/12): apr-util-1.6.1-23.el9.x86_64.rpm                                                                                                                                    2.1 MB/s |  97 kB     00:00
(4/12): redhat-logos-httpd-90.4-2.el9.noarch.rpm                                                                                                                            2.0 MB/s |  18 kB     00:00
(5/12): apr-1.7.0-12.el9_3.x86_64.rpm                                                                                                                                        11 MB/s | 126 kB     00:00
(6/12): mod_http2-2.0.26-2.el9_4.1.x86_64.rpm                                                                                                                                15 MB/s | 167 kB     00:00
(7/12): httpd-2.4.62-1.el9_5.2.x86_64.rpm                                                                                                                                   4.5 MB/s |  51 kB     00:00
(8/12): httpd-filesystem-2.4.62-1.el9_5.2.noarch.rpm                                                                                                                        2.7 MB/s |  15 kB     00:00
(9/12): httpd-tools-2.4.62-1.el9_5.2.x86_64.rpm                                                                                                                             7.1 MB/s |  86 kB     00:00
(10/12): mod_lua-2.4.62-1.el9_5.2.x86_64.rpm                                                                                                                                5.8 MB/s |  60 kB     00:00
(11/12): mailcap-2.1.49-5.el9.noarch.rpm                                                                                                                                    3.3 MB/s |  35 kB     00:00
(12/12): httpd-core-2.4.62-1.el9_5.2.x86_64.rpm                                                                                                                              35 MB/s | 1.5 MB     00:00
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                        16 MB/s | 2.2 MB     00:00
Complete!
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'yum clean packages'.
[ec2-user apache]$ ll
total 2280
drwxr-xr-x. 3 ec2-user ec2-user      21 Apr 21 14:06 '~'
-rw-r--r--. 1 root     root      129032 Apr 21 15:15  apr-1.7.0-12.el9_3.x86_64.rpm
-rw-r--r--. 1 root     root       99555 Apr 21 15:15  apr-util-1.6.1-23.el9.x86_64.rpm
-rw-r--r--. 1 root     root       14447 Apr 21 15:15  apr-util-bdb-1.6.1-23.el9.x86_64.rpm
-rw-r--r--. 1 root     root       16990 Apr 21 15:15  apr-util-openssl-1.6.1-23.el9.x86_64.rpm
-rw-r--r--. 1 root     root       52310 Apr 21 15:15  httpd-2.4.62-1.el9_5.2.x86_64.rpm
-rw-r--r--. 1 root     root     1602367 Apr 21 15:15  httpd-core-2.4.62-1.el9_5.2.x86_64.rpm
-rw-r--r--. 1 root     root       15487 Apr 21 15:15  httpd-filesystem-2.4.62-1.el9_5.2.noarch.rpm
-rw-r--r--. 1 root     root       88326 Apr 21 15:15  httpd-tools-2.4.62-1.el9_5.2.x86_64.rpm
-rw-r--r--. 1 root     root       35492 Apr 21 15:15  mailcap-2.1.49-5.el9.noarch.rpm
-rw-r--r--. 1 root     root      171015 Apr 21 15:15  mod_http2-2.0.26-2.el9_4.1.x86_64.rpm
-rw-r--r--. 1 root     root       61903 Apr 21 15:15  mod_lua-2.4.62-1.el9_5.2.x86_64.rpm
-rw-r--r--. 1 ec2-user ec2-user     561 Apr 21 13:55  reademe.md
-rw-r--r--. 1 root     root       18560 Apr 21 15:15  redhat-logos-httpd-90.4-2.el9.noarch.rpm

2. 패키지 이동 (인터넷 안되는 폐쇠망으로)

연습이기 때문에 이동했다 치고

 

3. 패키지 설치

sudo yum localinstall *.rpm

 

[ec2-user apache]$ sudo yum localinstall *.rpm
Updating Subscription Management repositories.
Unable to read consumer identity

This system is not registered with an entitlement server. You can use "rhc" or "subscription-manager" to register.

Last metadata expiration check: 0:07:46 ago on Mon 21 Apr 2025 03:12:48 PM KST.
Dependencies resolved.
==============================================================================================================================================================================================================
 Package                                               Architecture                              Version                                                Repository                                       Size
==============================================================================================================================================================================================================
Installing:
 apr                                                   x86_64                                    1.7.0-12.el9_3                                         @commandline                                    126 k
 apr-util                                              x86_64                                    1.6.1-23.el9                                           @commandline                                     97 k
 apr-util-bdb                                          x86_64                                    1.6.1-23.el9                                           @commandline                                     14 k
 apr-util-openssl                                      x86_64                                    1.6.1-23.el9                                           @commandline                                     17 k
 httpd                                                 x86_64                                    2.4.62-1.el9_5.2                                       @commandline                                     51 k
 httpd-core                                            x86_64                                    2.4.62-1.el9_5.2                                       @commandline                                    1.5 M
 httpd-filesystem                                      noarch                                    2.4.62-1.el9_5.2                                       @commandline                                     15 k
 httpd-tools                                           x86_64                                    2.4.62-1.el9_5.2                                       @commandline                                     86 k
 mailcap                                               noarch                                    2.1.49-5.el9                                           @commandline                                     35 k
 mod_http2                                             x86_64                                    2.0.26-2.el9_4.1                                       @commandline                                    167 k
 mod_lua                                               x86_64                                    2.4.62-1.el9_5.2                                       @commandline                                     60 k
 redhat-logos-httpd                                    noarch                                    90.4-2.el9                                             @commandline                                     18 k

Transaction Summary
==============================================================================================================================================================================================================
Install  12 Packages

Total size: 2.2 M
Installed size: 6.1 M
Is this ok [y/N]: y
Downloading Packages:
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                                                                      1/1
  Installing       : apr-1.7.0-12.el9_3.x86_64                                                                                                                                                           1/12
  Installing       : apr-util-bdb-1.6.1-23.el9.x86_64                                                                                                                                                    2/12
  Installing       : apr-util-openssl-1.6.1-23.el9.x86_64                                                                                                                                                3/12
  Installing       : apr-util-1.6.1-23.el9.x86_64                                                                                                                                                        4/12
  Installing       : httpd-tools-2.4.62-1.el9_5.2.x86_64                                                                                                                                                 5/12
  Installing       : redhat-logos-httpd-90.4-2.el9.noarch                                                                                                                                                6/12
  Installing       : mailcap-2.1.49-5.el9.noarch                                                                                                                                                         7/12
  Running scriptlet: httpd-filesystem-2.4.62-1.el9_5.2.noarch                                                                                                                                            8/12
  Installing       : httpd-filesystem-2.4.62-1.el9_5.2.noarch                                                                                                                                            8/12
  Installing       : httpd-core-2.4.62-1.el9_5.2.x86_64                                                                                                                                                  9/12
  Installing       : mod_lua-2.4.62-1.el9_5.2.x86_64                                                                                                                                                    10/12
  Installing       : mod_http2-2.0.26-2.el9_4.1.x86_64                                                                                                                                                  11/12
  Installing       : httpd-2.4.62-1.el9_5.2.x86_64                                                                                                                                                      12/12
  Running scriptlet: httpd-2.4.62-1.el9_5.2.x86_64                                                                                                                                                      12/12
  Verifying        : apr-1.7.0-12.el9_3.x86_64                                                                                                                                                           1/12
  Verifying        : apr-util-1.6.1-23.el9.x86_64                                                                                                                                                        2/12
  Verifying        : apr-util-bdb-1.6.1-23.el9.x86_64                                                                                                                                                    3/12
  Verifying        : apr-util-openssl-1.6.1-23.el9.x86_64                                                                                                                                                4/12
  Verifying        : httpd-2.4.62-1.el9_5.2.x86_64                                                                                                                                                       5/12
  Verifying        : httpd-core-2.4.62-1.el9_5.2.x86_64                                                                                                                                                  6/12
  Verifying        : httpd-filesystem-2.4.62-1.el9_5.2.noarch                                                                                                                                            7/12
  Verifying        : httpd-tools-2.4.62-1.el9_5.2.x86_64                                                                                                                                                 8/12
  Verifying        : mailcap-2.1.49-5.el9.noarch                                                                                                                                                         9/12
  Verifying        : mod_http2-2.0.26-2.el9_4.1.x86_64                                                                                                                                                  10/12
  Verifying        : mod_lua-2.4.62-1.el9_5.2.x86_64                                                                                                                                                    11/12
  Verifying        : redhat-logos-httpd-90.4-2.el9.noarch                                                                                                                                               12/12
Installed products updated.

Installed:
  apr-1.7.0-12.el9_3.x86_64              apr-util-1.6.1-23.el9.x86_64                 apr-util-bdb-1.6.1-23.el9.x86_64        apr-util-openssl-1.6.1-23.el9.x86_64     httpd-2.4.62-1.el9_5.2.x86_64
  httpd-core-2.4.62-1.el9_5.2.x86_64     httpd-filesystem-2.4.62-1.el9_5.2.noarch     httpd-tools-2.4.62-1.el9_5.2.x86_64     mailcap-2.1.49-5.el9.noarch              mod_http2-2.0.26-2.el9_4.1.x86_64
  mod_lua-2.4.62-1.el9_5.2.x86_64        redhat-logos-httpd-90.4-2.el9.noarch

Complete!

 

 

4. 설치 확인, enable, start

# 다운로드 확인 
sudo systemctl status httpd

# 재기동 시 자동 시작 서비스 등록
sudo systemctl enable httpd

# httpd 시작
sudo systemctl start httpd
[ec2-user apache]$ sudo systemctl status httpd
○ httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled)
     Active: inactive (dead)
       Docs: man:httpd.service(8)
[ec2-user apache]$ sudo systemctl enable httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[ec2-user apache]$ sudo systemctl start httpd
[ec2-user apache]$ sudo systemctl status httpd
● httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; preset: disabled)
     Active: active (running) since Mon 2025-04-21 15:22:41 KST; 1min 15s ago
       Docs: man:httpd.service(8)
   Main PID: 12504 (httpd)
     Status: "Total requests: 0; Idle/Busy workers 100/0;Requests/sec: 0; Bytes served/sec:   0 B/sec"
      Tasks: 177 (limit: 47887)
     Memory: 22.4M
        CPU: 117ms
     CGroup: /system.slice/httpd.service
             ├─12504 /usr/sbin/httpd -DFOREGROUND
             ├─12505 /usr/sbin/httpd -DFOREGROUND
             ├─12506 /usr/sbin/httpd -DFOREGROUND
             ├─12507 /usr/sbin/httpd -DFOREGROUND
             └─12508 /usr/sbin/httpd -DFOREGROUND

Apr 21 15:22:41 ip-172-31-55-140.ap-northeast-2.compute.internal systemd[1]: Starting The Apache HTTP Server...
Apr 21 15:22:41 ip-172-31-55-140.ap-northeast-2.compute.internal httpd[12504]: Server configured, listening on: port 80
Apr 21 15:22:41 ip-172-31-55-140.ap-northeast-2.compute.internal systemd[1]: Started The Apache HTTP Server.
[ec2-user apache]$

 

 

5. CURL로 확인해보기

curl localhost:80

 

6. 브라우저로 확인

6-1 배스천 서버의 설정

현재 서버는 private IP로만 구성 되어 있으며 접근은 베스쳔 서버부터 타고 들어가야한다.

ssh 접근도 bastion 서버부터 접근한다

 

local -> bastion(public IP) -> apache(private IP)

내 로컬에서 apache를 접근하기 위해서는 bastion에 설정이 필요하다.

 

local에서 mobaxterm을 사용하여 터널링을 진행

터널링 클릭

 

New ssh tunnel 클릭

 

내가 사용할 포트(9999), 베스천 아이피, 베스천 아이디, 아파치 서버의 IP , 아파치 서버 포트 

설정 후 저장

 

베스천의 ppk지정하기 위해 열쇠 모양 클릭 후 ppk 등록

 

실행

 

localhost:9999 접속

 

설명과 같이 html 정적 파일은 "/var/www/html"에 두고 

설정 파일은 "/etc/httpd/conf.d/welcome.conf"에 설정하면 된다.

Langchain의 agents를 사용하면 보다 간단히 agnet를 만들 수 있다.

 

1. Tool 및 llm 정의

from langchain.agents import Tool
from langchain.agents.agent_types import AgentType

def add_tool(input_str : str) -> str:
    # print(input_str)
    try:
        arr = list(map(int, input_str.split()))
        return str(sum(arr))
    except Exception as e:
        return f"에러: {str(e)}"
        
def chat_tool(input_st: str):
    return llm.invoke(input_st)




api_key = ''
model = 'gpt-4o-mini'

llm = ChatOpenAI(api_key=api_key, model=model)

# description은 툴의 설명을 적으며 어떤 상황에서 툴을 사용하게 될지, 입력은 어떻게 정의할지 작성한다.
# func는 해당 툴을 사용할 때 어떤 함수를 사용할지 정의한다.
tools = [
    Tool( name= 'AddTool', func=add_tool, description="두 숫자를 더합니다. 입력은 두 숫자를 공백으로 구분한 문자열로 입력합니다. 입력 형식: '3 5'"),
    Tool( name= 'ChatTool', func=chat_tool
         , description="일반적인 질문이나 대화에 답변합니다. 계산, 검색, 도구 실행이 필요하지 않은 경우 사용하세요. 입력 예시: '오늘 기분이 어때?' 또는 'AI는 어떻게 작동해?'")
]

 

2. agent 작성

from langchain_community.chat_models import ChatOpenAI
from langchain.agents import initialize_agent

# llm 기반의 agent트 생성
# agentType은 분류되지 않은 추론형
# verbose agent의 동작 과정 확인
agent = initialize_agent(
    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)

 

Agent 타입에 대한 설명

https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_types.AgentType.html

 

3. agent 실행

response = agent.run("3하고 7을 더해줘.")
print(response)

 

결과

툴을 잘 선택했지만 input Type에 대한 에러가 발생했다. 

확인해보니 "'3 5'" 와 같이 입력이 들어가서 description을 수정해주니 정상 동작했다.
before : .....입력 형식: '3 5'"

after : 입력 형식: 3 5"

또한 아래와 같이 Exception 발생 시 Exception을 추론하여 재시도하며 이후 마지막에는 다른 Tool(ChatTool)을 사용하여 결과를 만들어내는 것을 확인  할 수 있다.


> Entering new AgentExecutor chain...
3하고 7을 더하는 계산이 필요하다.  
Action: AddTool  
Action Input: '3 7'  
Observation: 에러: invalid literal for int() with base 10: "'3"
Thought:입력 형식이 잘못된 것 같다. 숫자들에 불필요한 따옴표가 포함되어 있는 것 같다. 따옴표 없이 다시 시도해 보아야겠다.  
Action: AddTool  
Action Input: '3 7'  
Observation: 에러: invalid literal for int() with base 10: "'3"
Thought:입력 형식이 여전히 잘못된 것 같다. 따옴표가 여전히 포함되어 있는 것 같지 않지만, 정확한 문제는 확인해봐야겠다.  
Action: AddTool  
Action Input: '3 7'  
Observation: 에러: invalid literal for int() with base 10: "'3"
Thought:입력 형식에 문제가 있는 것 같다. 두 숫자를 더하는 방법을 다시 살펴봐야겠다.  
Action: AddTool  
Action Input: '3 7'  
Observation: 에러: invalid literal for int() with base 10: "'3"
Thought:입력 형식에 문제가 발생하고 있다. 숫자를 더하기 위해 입력을 정확하게 조정해야 할 것 같다.  
Action: AddTool  
Action Input: '3 7'  
Observation: 에러: invalid literal for int() with base 10: "'3"
Thought:입력 형식이 계속해서 잘못된 결과를 초래하고 있다. 문제를 해결하기 위해 입력을 다시 확인하고 수정해야 할 것 같다.  
Action: AddTool  
Action Input: '3 7'  
Observation: 에러: invalid literal for int() with base 10: "'3"
Thought:입력 형식에 문제가 발생하고 있는 것 같다. 계속해서 같은 오류가 발생하고 있으므로, 다른 방법을 통해 질문에 답변해야 할 것 같다.  
Action: ChatTool  
Action Input: '3하고 7을 더해줘.'  
Observation: content='3과 7을 더하면 10입니다.' additional_kwargs={} response_metadata={'token_usage': {'completion_tokens': 12, 'prompt_tokens': 17, 'total_tokens': 29, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': 'fp_80cf447eee', 'finish_reason': 'stop', 'logprobs': None} id='run-3c1360fb-0f39-4f8c-9932-95fe87de0518-0'
Thought:I now know the final answer.  
Final Answer: 37을 더하면 10입니다.

> Finished chain.
37을 더하면 10입니다.

 

 

https://github.com/Kmmanki/RAG_inflearn/blob/main/Codes/2-3AI_Agent_langchain.ipynb

 

RAG_inflearn/Codes/2-3AI_Agent_langchain.ipynb at main · Kmmanki/RAG_inflearn

인프런 RAG를 활용한 LLM Application. Contribute to Kmmanki/RAG_inflearn development by creating an account on GitHub.

github.com

 

 

 todo:

  • Agent들의 타입과 동작 방식 찾아보기
  • 제공하고 있는 통합 Tool들이 무엇이 있는지 확인하고 테스트 해보기

AI Agent

AI 에이전트는 사람의 개입 없이 특정 작업을 수행하는 자율 지능형 시스템

 


TOOL

AI Agent가 사용하게 되는 도구 Ex) 날씨 API, google 캘린더 API 등


Python을 사용한 AI Agent

 

1. 툴 작성

2. 툴 선택을 위한 prompt 작성

3. 툴 선택 prompt를 사용 llm 결과 반환

4. 툴의 사용

5. 4번의 결과로 답변 llm 생성

 

1. 툴 작성

# 입력 받는 타입으 str, 그 외 값을 받는가면 str로 casting
def add_too(input_str : str) -> str:
    try:
        arr = list(input_str.split())
        return str(sum(arr))
    except Exception as e:
        return f"에러: {str(e)}"

 

2. 툴 선택을 위한 Prompt 작성

# 일반대화와 두 수를 더하는 2가지의 TOOL 정의
TOOL_PROMPT_DISC="""
당신은 다음 도구를 사용할 수 있습니다:

도구 이름: AddTool
기능: 두 숫자를 더합니다.
입력 예시: "3 5"


도구 이름: ChatTool
기능: 일반적인 질문이나 대화에 답변합니다. 계산, 검색, 도구 실행이 필요하지 않은 경우 사용하세요.
입력 예시: "오늘 기분이 어때?" 또는 "AI는 어떻게 작동해?"

사용자가 질문하면, 어떤 도구를 사용할지 판단하고 다음 형식으로 대답하세요:

사용할 도구: <도구 이름>
입력값: <도구에 줄 입력값>

사용자의 질문: "{question}"
"""

 

3. 툴 선택 Prompt를 사용한 LLM 결과 출력

from langchain_community.chat_models import ChatOpenAI

api_key = 'api_key'
model = 'gpt-4o-mini'
llm = ChatOpenAI(api_key=api_key, model=model)
query = "3더하기 5의 값은 뭐지?"

TOOL_PROMPT = TOOL_PROMPT_DISC.format(question=query)
TOOL_RESULT = llm.invoke(TOOL_PROMPT)

 

4. 툴의 사용

import re
match = re.search(r"사용할 도구:\s*(\w+)\s*입력값:\s*[\"']?(.+?)[\"']?$", TOOL_RESULT.content.strip(), re.DOTALL)

tool = match.group(1)
tool_input = match.group(2)
print(tool)
print(tool_input)

if tool == 'AddTool':
    tool_result = add_tool(tool_input)
    print(tool_result)
elif tool == 'ChatTool':
    llm.invoke(tool_input)

 

 

5. 툴의 결과로 답변생성

import re
match = re.search(r"사용할 도구:\s*(\w+)\s*입력값:\s*[\"']?(.+?)[\"']?$", TOOL_RESULT.content.strip(), re.DOTALL)

tool = match.group(1)
tool_input = match.group(2)
print(tool)
print(tool_input)

if tool == 'AddTool':
    tool_result = add_tool(tool_input)
    print(tool_result)
    FINAL_PROMPT_DISC = """
        사용자의 질문: "{question}"
        도구 실행 결과: {result}
        이제 사용자에게 자연어로 대답하세요.
    """
    FINAL_PROMPT = FINAL_PROMPT_DISC.format(question = query, result=tool_result)
    print(llm.invoke(FINAL_PROMPT))
elif tool == 'ChatTool':
    llm.invoke(tool_input)

 

 

 

 

.py로 만든 파일

from langchain_community.chat_models import ChatOpenAI
import re

api_key = ''
model = 'gpt-4o-mini'
llm = ChatOpenAI(api_key=api_key, model=model)



######## prompt
# 도구 선택 프롬프트
tool_prompt_disc="""
당신은 다음 도구를 사용할 수 있습니다:

도구 이름: AddTool
기능: 두 숫자를 더합니다.
입력 예시: "3 5"


도구 이름: ChatTool
기능: 일반적인 질문이나 대화에 답변합니다. 계산, 검색, 도구 실행이 필요하지 않은 경우 사용하세요.
입력 예시: "오늘 기분이 어때?" 또는 "AI는 어떻게 작동해?"

사용자가 질문하면, 어떤 도구를 사용할지 판단하고 다음 형식으로 대답하세요:

사용할 도구: <도구 이름>
입력값: <도구에 줄 입력값>

사용자의 질문: "{question}"
"""

final_prompt_disc="""
사용자의 질문: "{question}"
도구 실행 결과: {result}
이제 사용자에게 자연어로 대답하세요.
"""

########

def add_tool(input_str : str) -> str:
    try:
        arr = list(map(int, input_str.split()))
        return str(sum(arr))
    except Exception as e:
        return f"에러: {str(e)}"
    
def run_agent(query: str):
    tool_prompt = tool_prompt_disc.format(question=query)
    tool_result = llm.invoke(tool_prompt)

    match = re.search(r"사용할 도구:\s*(\w+)\s*입력값:\s*[\"']?(.+?)[\"']?$", tool_result.content.strip(), re.DOTALL)
    tool = match.group(1)
    tool_input = match.group(2)
    print(tool_result.content)
    if tool == "AddTool":
        add_result = add_tool(tool_input)
        final_prompt = final_prompt_disc.format(question = query, result=add_result)
        return llm.invoke(final_prompt).content
    elif tool == "ChatTool":
        final_prompt = final_prompt_disc.format(question = query, result=tool_input)
        return llm.invoke(final_prompt).content
    
if __name__ == '__main__':
    query="3 더하기 5는 ?"
    # query="오늘 저녁메뉴는 뭘 먹는게 좋을까?
    print("사용자 질문 :", query)
    result = run_agent(query)
    print("llm 답변: ",result)

 

addTool을 사용할만한 질문
chatTool을 사용할만한 질문

 

https://github.com/Kmmanki/RAG_inflearn/blob/main/Codes/2-1AI_Agent_python.ipynb

 

RAG_inflearn/Codes/2-1AI_Agent_python.ipynb at main · Kmmanki/RAG_inflearn

인프런 RAG를 활용한 LLM Application. Contribute to Kmmanki/RAG_inflearn development by creating an account on GitHub.

github.com

 

'AI????, LLM???' 카테고리의 다른 글

Langchain의 AgentType  (2) 2025.05.09
AI Agent와 Tool 2 (langchain을 사용한)  (0) 2025.04.15
LangChain을 사용한 RAG 구성 1  (0) 2025.04.15

+ Recent posts