본문 바로가기
딥러닝 머신러닝 데이터 분석/Langchain & LLM

[Langchain coding bot] 랭체인을 이용해서 코딩을 해 보자 - 2

by SteadyForDeep 2024. 3. 24.
반응형

이 글은 아래의 의존성을 가진다.

 

https://github.com/hyun06000/langchain-codingbot/blob/main/python_programmer.ipynb

 

langchain-codingbot/python_programmer.ipynb at main · hyun06000/langchain-codingbot

Contribute to hyun06000/langchain-codingbot development by creating an account on GitHub.

github.com

2024.03.24 - [딥러닝 머신러닝 데이터 분석/Langchain & LLM] - [Langchain coding bot] 랭체인을 이용해서 코딩을 해 보자 - 1

 

[Langchain coding bot] 랭체인을 이용해서 코딩을 해 보자 - 1

랭체인을 이용해서 코딩을 해 보자. 독자의 랭체인과 LLM에 대한 기본적인 이해가 있다는 전재를 두고 이 글을 이어가겠다. // 무엇을 코딩할 것인가 우선은 무슨 코딩을 할지 정해야 한다. 사실

davi06000.tistory.com

 

이전 글에서 설명을 뛰어넘고 간 도구 부분을 설명하고자 한다.

 

도구는 callable 파이썬 객체로 선언되어 있으면 된다.

다만 텍스트를 사용하는 LLM을 사용하므로 입력과 출력 모두 문자열로 구성되어야 한다.

그러면 앞서 살펴본 파서에서 함수의 이름을 얻게 되고 함께 얻은 함수의 입력을 에이전트가 실행해서 결과값을 LLM에게 알려준다.

 

직접 예시를 한번 보자.

 

def savefile_tool(file_name, file_contents:str) -> str:
    """Save (append) script as a file with file name and file contents which is a code.
    This tool need two inputs like {action_input: {file_name:str , file_contents:str}}.
    """
    
    try:
        with open(file_name, 'w+') as f:
            f.write(file_contents + "\n")

        return f"file saved : {file_name}"
    except Exception as e:
        return f"Error: {e}"


def readfile_tool(file_name: str) -> str:
    """Read script as a file with file name and file contents which is a code"""

    try:
        with open(file_name, "r+") as f:
            file_contents = f.read()

        return f"file_contents : {file_contents}"
    except Exception as e:
        return f"Error: {e}"

파일을 쓰고 읽는 부분이다.

 

에러가 발생하면 파이썬이 종료되는 것이 아닌 LLM이 처리할수 있도록 스트링 형태로 반환해 준다.

이렇게 처리하면 사람이 중간에 개입할 필요 없이 LLM이 스스로 많은 일을 해낼 수 있게 된다.

 

from custom_tools.tools import (
    terminal_tool,
    search_url_tool,
    request_url_tool,
    readfile_tool,
    savefile_tool,
)
from langchain.tools import StructuredTool

tools = [
    StructuredTool.from_function(terminal_tool),
    StructuredTool.from_function(search_url_tool),
    StructuredTool.from_function(request_url_tool),
    StructuredTool.from_function(savefile_tool),
    StructuredTool.from_function(readfile_tool),
    StructuredTool.from_function(request_url_tool),
]

대부분의 툴은 하나의 입력을 받게 되지만

어떤 툴은 반드시 두개 이상의 입력값을 받아야 하는 경우가 있다.

그런 경우를 위해서 Json 형태의 출력을 강제하고 그것에 맞는 파서를 도입했었다.

또한 도구를 랩핑할때도 StructuredTool을 사용해야만 한다.

 

https://blog.langchain.dev/structured-tools/

 

Structured Tools

TL;DR: we're introducing a new abstraction to allow for usage of more complex tools. While previous tools took in a single string input, new tools can take in an arbitrary number of inputs of arbitrary types. We are also introducing a new agent class that

blog.langchain.dev

위의 글을 읽어보길 바란다.

 

코딩 봇을 만들기 위해서는

1. 터미널 명령을 실행할 수 있는 서브프로세스 실행 도구

2. 파일을 저장할 수 있는 파일 저장 도구

3. 파일을 읽을 수 있는 파일 읽기 도구

이 세가지만 있으면 충분하다.

 

혹시 에러 처리를 더 잘 하게 하고싶다면 구글 검색 기능 등을 넣어주면 더 좋다.

 

반응형

댓글