[랭체인] 도구 체인 구축 가이드steemCreated with Sketch.

in #kr-dev28 days ago (edited)

안녕하세요, 여러분! 오늘은 LangChain을 사용하여 강력한 도구 체인을 구축하는 방법에 대해 알아보겠습니다. 이 튜토리얼을 통해 우리는 날씨 정보를 가져오고 현재 위치를 확인하는 도구를 만들어 볼 것입니다. 그럼 시작해볼까요?

1. 환경 설정

먼저, 필요한 라이브러리를 설치하고 임포트합니다.

!pip install -Uq langchain_core langchain_openai
import os
from google.colab import userdata

# API 키 설정 (Colab이 아닌 환경에서는 직접 설정)
os.environ["OPENAI_API_KEY"] = userdata.get('OPENAI_API_KEY')

참고: 이 부분은 Google Colab에서 작업할 때 필요한 단계입니다. 로컬 환경에서는 API 키를 직접 설정해주세요.

import json
import requests

from langchain_core.tools import tool
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI

2. 도구 만들기

이제 우리의 첫 번째 도구인 날씨 정보 가져오기 도구를 만들어 보겠습니다.

@tool
def get_current_weather(latitude: float, longitude: float) -> str:
    """
    Open-Meteo API를 사용하여 지정된 위도와 경도의 현재 날씨 데이터를 가져옵니다.
    """
    base_url = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current_weather": True,
        "daily": "temperature_2m_max,temperature_2m_min",
        "timezone": "auto"
    }
    response = requests.get(base_url, params=params)
    info = {}
    if response.status_code == 200:
        info = response.json()
    return json.dumps(info)

이 도구는 Open-Meteo API를 사용하여 주어진 위도와 경도의 현재 날씨 정보를 가져옵니다.

다음으로, 현재 위치를 가져오는 도구를 만들어 보겠습니다.

@tool
def get_current_location() -> str:
    """
    IPinfo.io API를 사용하여 IP 주소 기반의 현재 위치를 가져옵니다.
    """
    response = requests.get('https://ipinfo.io')
    info = response.json()
    return json.dumps(info)

이 도구는 IPinfo.io API를 사용하여 현재 IP 주소 기반의 위치 정보를 가져옵니다.

3. LLM 설정

이제 우리의 도구를 사용할 LLM(Large Language Model)을 설정해 보겟습니다.

llm = ChatOpenAI(model="gpt-3.5-turbo")
tools = [get_current_weather, get_current_location]
llm_with_tools = llm.bind_tools(tools)

여기서 우리는 OpenAI의 GPT-3.5-turbo 모델을 사용하고, 우리가 만든 도구들을 이 모델에 바인딩했습니다.

4. 도구 호출 헬퍼 함수 만들기

다음으로, 도구를 순차적으로 호출하는 헬퍼 함수를 만들어 보겠습니다.

def call_tools(msg: AIMessage) -> Runnable:
    """순차적인 도구 호출을 위한 간단한 헬퍼 함수입니다."""
    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

이 함수는 AI 메시지에 포함된 도구 호출을 순차적으로 실행하고 그 결과를 반환합니다.

5. 체인 구성

이제 우리의 LLM과 도구 호출 헬퍼 함수를 연결하여 체인을 구성해 보겠습니다.

chain = llm_with_tools | call_tools

이 체인은 사용자의 입력을 받아 LLM이 처리한 후, 필요한 도구를 호출하고 그 결과를 반환합니다.

6. 체인 사용하기

이제 우리가 만든 체인을 사용해 볼 차례입니다!

result = chain.invoke("What is the weather in Seoul?")
print(result)

result = chain.invoke("What is the current location?")
print(result)

이 코드는 서울의 날씨를 물어보고, 현재 위치를 확인하는 쿼리를 실행합니다.

7. 대화형 인터페이스 만들기

마지막으로, 사용자와 대화할 수 있는 간단한 인터페이스를 만들어 보겠습니다.

def chat_with_user(user_message):
    ai_message = chain.invoke(user_message)
    return ai_message

while True:
    user_message = input("USER > ")
    if user_message.lower() == "quit":
        break
    ai_message = chat_with_user(user_message)
    print(f" A I > {ai_message}")

이 코드는 사용자의 입력을 받아 우리의 체인을 통해 처리하고, 그 결과를 출력합니다. 'quit'를 입력하면 대화가 종료됩니다.

결론

이렇게 해서 우리는 LangChain을 사용하여 날씨 정보와 위치 정보를 가져올 수 있는 도구 체인을 구축해 보았습니다. 이 체인은 사용자의 질문에 답하기 위해 필요한 도구를 자동으로 선택하고 실행합니다.

LCEL을 사용하면 이렇게 복잡한 작업을 간단하고 명확한 방식으로 구현할 수 있습니다. 여러분도 이 예제를 바탕으로 자신만의 도구 체인을 만들어 보시는 건 어떨까요?

행운을 빕니다!

#LangChain

Posted using Obsidian Steemit plugin

Sort:  

[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.

Congratulations, your post has been upvoted by @upex with a 0.22% upvote. We invite you to continue producing quality content and join our Discord community here. Visit https://botsteem.com to utilize usefull and productive automations #bottosteem #upex