본문 바로가기
데이터&AI/LLM

LLM 에이전트(llm agent) 란 무엇일까?- 코드로 알아보기 (feat. prompt engineering)

by 일등박사 2024. 5. 29.

 

https://www.etnews.com/20240501000118

 

AI 에이전트 시대 열린다…단순 답변 넘어 '일상의 동반자'로

인공지능(AI)이 챗봇을 넘어 기차표를 예매하고 레스토랑을 예약해주는 ‘AI 에이전트 시대’가 열린다. 1일 업계에 따르면, 눈과 손이 달린 것처럼 고도화된 업무를 직접 수행하는 AI 에이전트,

www.etnews.com

 

LLM이 이슈가 되면서 이제는 LLM Agent라는 말이 여러 매체에서 화두가되고있습니다

이 LLM Agent란 무엇일까요?

 

LLM에서의 에이전트의 정의와 예시 , 그리고 코드로 알아보기!!

LLM에서의 에이전트란?

LLM 에이전트란 입력받은 정보를 바탕으로 작업을 수행하거나 결정을 내리는 자율적인 개체를 의미합니다

예를 들면 아래와 같은 서비스들이 llm 에이전트 기반으로 작동한다고 볼 수 있지요!

  1. 가상 비서: Siri, Alexa, Google Assistant와 같은 가상 비서는 에이전트의 대표적인 예시입니다. 이들은 음성 명령을 이해하고, 자연어를 처리하며, 관련된 응답이나 행동을 제공합니다. 예를 들어, 사용자가 Alexa에게 좋아하는 노래를 재생해달라고 요청하면, 이를 처리하고 음악 스트리밍 서비스와 상호작용하여 노래를 재생합니다.
  2. 고객 지원 봇: 많은 기업들은 고객 문의를 처리하기 위해 채팅봇 형태의 에이전트를 사용합니다. 이 봇들은 고객의 질문을 이해하고 답변을 제공하며, 복잡한 문제는 인간 에이전트에게 전달할 수 있습니다. 예를 들어, 전자상거래 웹사이트의 고객 지원 봇은 사용자가 주문을 추적하고, 반품을 처리하며, 제품 관련 질문에 답변할 수 있도록 도와줍니다.
  3. 자동 콘텐츠 생성: 에이전트는 자율적으로 콘텐츠를 생성할 수도 있습니다. OpenAI의 GPT-3와 같은 도구는 사용자로부터 받은 프롬프트를 기반으로 기사, 코드, 심지어 시까지 작성할 수 있습니다. 이러한 에이전트는 LLM에 내장된 방대한 지식을 활용하여 인간의 글쓰기와 유사한 고품질의 콘텐츠를 생성합니다.
  4. 언어 번역: 번역 에이전트는 LLM을 사용하여 한 언어에서 다른 언어로 텍스트를 변환하며, 원래 의미를 유지합니다. Google 번역과 같은 서비스는 이러한 에이전트를 사용하여 실시간 번역을 제공하고, 다양한 언어 간의 의사소통을 용이하게 합니다.
  5. 개인화된 학습 도우미: 교육 기술 분야에서 에이전트는 개인화된 튜터 역할을 할 수 있으며, 학생 개개인의 학습 스타일과 속도에 맞춰 조정됩니다. 에이전트는 설명을 제공하고, 질문에 답하며, 학습을 강화하기 위해 퀴즈를 제공할 수 있습니다.

LLM 에이전트를 만들기 위해 필요한 기능!! with 예시코드

LLM 에이전트는 단순히 LLM  API를 연결한 것이 아니라

 

- COT를 바탕으로 순서대로 생각하고!

 

 

- 스스로 정답여부도 체크하고,

# RAG or Search?
def is_in(question, context):
    is_in_conetxt = """도움이 되는 조력자로서, 
질문에 대한 답이 주어진 맥락 안에 있는지 판단하기 위해 최선의 판단을 사용하십시오. 
문맥상 답변이 있는 경우 "예"로 답변해 주시기 바랍니다. 
그렇지 않다면 "아니오"로 응답해 주시기 바랍니다. 
"예" 또는 "아니오"만 제공하고 추가 정보를 포함하지 마십시오. 
최선을 다하세요. 질문과 맥락은 다음과 같습니다:
---
CONTEXT: {context}
---
QUESTION: {question}
---
OUTPUT (예 or 아니오):"""

    is_in_prompt = PromptTemplate.from_template(is_in_conetxt)
    chain = is_in_prompt | ChatUpstage() | StrOutputParser()

    response = chain.invoke({"context": context, "question": question})
    print(response)
    return response.lower().startswith("yes")

 

 

- Guardrail 등의 기능을 활용하여 이상한 오답을 방지하고!

# https://github.com/guardrails-ai/validator-template/blob/main/validator/main.py
from typing import Any, Callable, Dict, Optional
from guardrails import OnFailAction
from guardrails.validator_base import (
    FailResult,
    PassResult,
    ValidationResult,
    Validator,
    register_validator,
)


@register_validator(name="guardrails/solar_validator", data_type="string")
class SolarValidator(Validator):
    """Validates that {fill in how you validator interacts with the passed value}.
    """ 

    # If you don't have any init args, you can omit the __init__ method.
    def __init__(
        self,
        keyword: str = "solar",
        on_fail: Optional[Callable] = OnFailAction.EXCEPTION,
    ):
        super().__init__(on_fail=on_fail, keyword=keyword)
        self._keyword = keyword

    def validate(self, value: Any, metadata: Dict = {}) -> ValidationResult:
        """Validates that {fill in how you validator interacts with the passed value}."""
        # Add your custom validator logic here and return a PassResult or FailResult accordingly.
        if self._keyword in str(value):
            return PassResult()

        return FailResult(
            error_message="{A descriptive but concise error message about why validation failed}",
            fix_value="{The programmtic fix if applicable, otherwise remove this kwarg.}",
        )

 

- tool기능 (function calling)을 활용하여 내부 함수를 호출할주도 알고

 

# Tools
from langchain_core.tools import tool
import requests


@tool
def add(a: int, b: int) -> int:
    """Adds a and b."""
    return a + b


@tool
def multiply(a: int, b: int) -> int:
    """Multiplies a and b."""
    return a * b


@tool
def get_news(topic: str) -> str:
    """Get news on a given topic."""
    # https://newsapi.org/v2/everything?q=tesla&from=2024-04-01&sortBy=publishedAt&apiKey=API_KEY
    # change this to request news from a real API
    news_url = f"https://newsapi.org/v2/everything?q={topic}&apiKey={os.environ['NEWS_API_KEY']}"
    respnse = requests.get(news_url)
    return respnse.json()


def call_tool(tool_call):
    tool_name = tool_call["name"].lower()
    if tool_name not in globals():
        print("Tool not found", tool_name)
        return None
    selected_tool = globals()[tool_name]
    return selected_tool.invoke(tool_call["args"])
    
query = "What is 3 * 12? Also, what is 11 + 49?"

tool_calls = llm_with_tools.invoke(query).tool_calls
print(tool_calls)    
tools = [add, multiply, get_news]

llm_with_tools = llm.bind_tools(tools)

 

 

그렇기에 llm agent를 만들려먼

좋은  llm모델에 더하여!!

function calling, guardrail, prompt engineering 기술 등 여러 능력이 필요하겠지요!??

 

감사합니다.

 

 

댓글