LangChain을 활용한 Tool Calling # 4

2024. 11. 29. 03:33·AI/어플리케이션 개발

자연어 처리와 대화형 AI 모델을 통해 복잡한 문제를 해결하려면, 단순히 언어를 이해하는 것을 넘어서 다양한 툴을 활용할 필요가 있습니다. LangChain은 이러한 필요성을 충족시킬 수 있는 프레임워크로, 특히 Tool Calling 기능을 통해 외부 데이터와의 상호작용을 쉽게 만들어 줍니다. 이 글에서는 LangChain을 활용한 Tool Calling의 작동 원리와 실제 사용 방법을 구체적인 예제를 통해 소개하겠습니다.

 


 

LangChain이란?

LangChain은 자연어 처리 모델을 좀 더 강력하고 유연하게 사용할 수 있게 도와주는 Python 기반의 오픈소스 프레임워크입니다. 이 프레임워크는 AI 모델과 다양한 외부 도구를 연결하는 데 초점을 맞추고 있어, AI 모델이 API 호출, 데이터베이스 쿼리, 계산 작업 등을 직접 수행하도록 할 수 있습니다. Tool Calling은 이러한 외부 툴들과의 상호작용을 통해 문제를 해결하는 데 사용되는 LangChain의 핵심 기능 중 하나입니다. LangChain에 대한 추가적인 정보는 블로그의 이전 포스트를 참고해주세요.

 

LLM 애플리케이션 개발 훑어보기 - LangChain #1 Intro 및 QuickStart

Introduction LangChain은 인공 지능(AI) 및 그 기계 학습 하위 집합으로 작업하는 소프트웨어 개발자가 대규모 언어 모델을 다른 외부 구성 요소와 결합하여 LLM 기반 애플리케이션을 개발할 수 있는 오

dytis.tistory.com

 

Tool Calling의 개념

Tool Calling은 말 그대로 특정 작업을 수행할 수 있는 툴을 호출하는 것을 의미합니다. 예를 들어, AI가 날씨 정보를 제공해야 할 때, AI가 직접 날씨 API를 호출하여 사용자가 원하는 정보를 전달하는 방식입니다. LangChain을 통해 LLM(Large Language Model)이 직접 툴을 호출하고, 그 결과를 사용하여 사용자에게 답변을 제공할 수 있습니다. Tool Calling에 대한 추가적인 정보는 블로그의 이전 포스트를 참고해주세요.

 

LLM 어플리케이션에서의 Tool Calling: AI가 더 똑똑해지는 방법

LLM(대형 언어 모델) 어플리케이션이 갈수록 더 많은 일들을 할 수 있게 되면서, "Tool calling" 기능은 그중에서도 가장 주목할 만한 혁신 중 하나로 자리 잡고 있습니다. 이 기능은 AI가 외부의 도구

dytis.tistory.com

 


 

How to: add a human-in-the-loop for tools

 

How to add a human-in-the-loop for tools | 🦜️🔗 LangChain

There are certain tools that we don't trust a model to execute on its own. One thing we can do in such situations is require human approval before the tool is invoked.

python.langchain.com

모델이 스스로 실행할 수 있다고 믿지 못하는 특정 도구가 있습니다. 그런 상황에서 할 수 있는 한 가지는 도구를 호출하기 전에 인간의 승인을 요구하는 것입니다.

 

Chain

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass()

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini")
from typing import Dict, List

from langchain_core.messages import AIMessage
from langchain_core.runnables import Runnable, RunnablePassthrough
from langchain_core.tools import tool


@tool
def count_emails(last_n_days: int) -> int:
    """Dummy function to count number of e-mails. Returns 2 * last_n_days."""
    return last_n_days * 2


@tool
def send_email(message: str, recipient: str) -> str:
    """Dummy function for sending an e-mail."""
    return f"Successfully sent email to {recipient}."


tools = [count_emails, send_email]
llm_with_tools = llm.bind_tools(tools)


def call_tools(msg: AIMessage) -> List[Dict]:
    """Simple sequential tool calling helper."""
    tool_map = {tool.name: tool for tool in tools}
    tool_calls = msg.tool_calls.copy()
    for tool_call in tool_calls:
        tool_call["output"] = tool_map[tool_call["name"]].invoke(tool_call["args"])
    return tool_calls


chain = llm_with_tools | call_tools
chain.invoke("how many emails did i get in the last 5 days?")

 

 

Adding human approval

대규모 통화 요청을 승인하거나 거부할지 묻는 단계를 체인에 추가해 보겠습니다. 거부되면 해당 단계에서는 예외가 발생하고 나머지 체인의 실행이 중지됩니다.

import json


class NotApproved(Exception):
    """Custom exception."""


def human_approval(msg: AIMessage) -> AIMessage:
    """Responsible for passing through its input or raising an exception.

    Args:
        msg: output from the chat model

    Returns:
        msg: original output from the msg
    """
    tool_strs = "\n\n".join(
        json.dumps(tool_call, indent=2) for tool_call in msg.tool_calls
    )
    input_msg = (
        f"Do you approve of the following tool invocations\n\n{tool_strs}\n\n"
        "Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no.\n >>>"
    )
    resp = input(input_msg)
    if resp.lower() not in ("yes", "y"):
        raise NotApproved(f"Tool invocations not approved:\n\n{tool_strs}")
    return msg
chain = llm_with_tools | human_approval | call_tools
chain.invoke("how many emails did i get in the last 5 days?")

 

Yes 입력시

 

No 입력시

저작자표시 (새창열림)

'AI > 어플리케이션 개발' 카테고리의 다른 글

MCP(Model Context Protocol)이 뭐길래? 실습편  (3) 2025.03.21
MCP(Model Context Protocol)이 뭐길래?  (5) 2025.03.20
LangChain을 활용한 Tool Calling # 3  (0) 2024.11.29
LangChain을 활용한 Tool Calling # 2  (3) 2024.11.29
LangChain을 활용한 Tool Calling # 1  (2) 2024.11.29
  1. How to: add a human-in-the-loop for tools
  2. Chain
  3. Adding human approval
'AI/어플리케이션 개발' 카테고리의 다른 글
  • MCP(Model Context Protocol)이 뭐길래? 실습편
  • MCP(Model Context Protocol)이 뭐길래?
  • LangChain을 활용한 Tool Calling # 3
  • LangChain을 활용한 Tool Calling # 2
pfldy2850
pfldy2850
인공지능의 서비스화와 현실화에 관심이 많은 엔지니어입니다.
  • pfldy2850
    DEV.DY
    Github LinkedIn
  • 전체
    오늘
    어제
    • All (105)
      • AI (68)
        • 어플리케이션 개발 (11)
        • 모델 인퍼런스 (9)
        • 검색 시스템 (11)
        • MLOps (8)
        • 기술,논문 리뷰 (7)
        • Lecture notes (10)
        • 오픈소스 릴리즈 노트 (12)
      • Infra (4)
        • Kubernetes (1)
        • Service Mesh (1)
        • Service Proxy (1)
        • Storage (1)
      • Data Engineering (4)
        • Spark (3)
        • Kafka (1)
        • Delta Lake (0)
      • 컴퓨터 공학 (2)
        • 소프트웨어 공학 (2)
      • 개발 (16)
        • ReactJS (8)
        • NodeJS (2)
        • Python (4)
        • Pytorch (1)
        • git (1)
      • 영어공부 (2)
        • GPT로 영어 회화 공부 (2)
      • 활동 (2)
        • 2017 NDC (2)
      • 기타 (1)
      • 레거시 (6)
        • OS (6)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
pfldy2850
LangChain을 활용한 Tool Calling # 4
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.