사이트 내 검색:

TIL - 2023.09.03 - LangChain을 이용한 ChatGPT Code Interpreter 구현

03 Sep 2023

개요

Awesome LangChain의 news letter를 구독 중이었는데 LangChain을 이용한 ChatGPT Code Interpreter가 소개되었다.

https://github.com/shroominic/codeinterpreter-api

최초 commit 일자는 2023.07.10 이다. github star는 2023.09.03 기준으로 2.8k이고 꾸준히 올라가고 있다.

간단히 테스트해본 결과를 정리한다.

설치

Python 3.9에서 테스트하였다.

우선 다음과 같은 package를 설치한다.

pip install langchain[llms]
pip install codeboxapi

pip install codeinterpreterapi[all]

2023.09.03 기준 설치된 버전은 다음과 같다.

codeinterpreterapi==0.0.12
langchain==0.0.279
codeboxapi==0.0.19

codeboxapi는 codeinterpreter-api 개발자가 수익화를 위해 만든 프로젝트 같다. 간단히 test할 떄는 codeboxapi 유료 결제없이 사용 가능했다. (그렇지만 pip 설치 없이는 codeinterpreter-api가 실행되지 않았다)

python file 실행

아래 code는 codeinterpreter-api repository에서 제공하는 예제 파일을 아주 약간 수정한 파일이다. (수정 사항: API KEY 입력, model을 gpt-3.5로 변경)

from codeinterpreterapi import CodeInterpreterSession

import os
os.environ['OPENAI_API_KEY'] = 'OPENAI API KEY 입력'

async def main():
    # create a session
    session = CodeInterpreterSession(model="gpt-3.5-turbo", verbose=True)
    await session.astart()

    # generate a response based on user input
    response = await session.generate_response(
        "Plot the bitcoin chart of 2023 YTD"
    )

    # output the response (text + image)
    print("AI: ", response.content)
    for file in response.files:
        file.show_image()

    await session.astop()

if __name__ == "__main__":
    import asyncio
    # run the async function
    asyncio.run(main())

위 python file을 실행하면 bit coin 시세 chart가 그려진다 (그냥 terminal에서 실행해도 chart image를 띄워준다)

아래는 생성된 chart이다.

chart를 보면 알겠지만 모두 최신 데이터들이다. (yahoo finance에서 조회하는 듯 )

참고 1

rate limit가 걸린 무료 api token을 사용할 때는 에러가 종종 에러가 발생하는 것 같기도 하다.

jupyter notebook에서 실행하기

jupyter에서 실행시킬 때는 아래처럼 실행하면 된다.

from codeinterpreterapi import CodeInterpreterSession

import os
os.environ['OPENAI_API_KEY'] = 'OPENAI API KEY 입력'

# create a session
session = CodeInterpreterSession(model="gpt-3.5-turbo", verbose=True)

await session.astart()

# generate a response based on user input
response = await session.generate_response(
    "Plot the bitcoin chart of 2023 YTD"
)

# output the response (text + image)
print("AI: ", response.content)

for file in response.files:
    file.show_image()

csv file 분석하기

아래에 있는 code도 codeinterpreter-api의 README.md에 있는 code에 약간의 수정만 한 code.

from codeinterpreterapi import CodeInterpreterSession, File

import os
os.environ['OPENAI_API_KEY'] = 'OPENAI API KEY 입력'

async def main():
    # context manager for auto start/stop of the session
    async with CodeInterpreterSession(model="gpt-3.5-turbo", verbose=True) as session:
        # define the user request
        user_request = "Analyze this dataset and plot something interesting about it."
        files = [
            File.from_path("examples/assets/iris.csv"),
        ]

        # generate the response
        response = await session.generate_response(
            user_request, files=files
        )

        # output to the user
        print("AI: ", response.content)
        for file in response.files:
            file.show_image()


if __name__ == "__main__":
    import asyncio

    asyncio.run(main())

위의 코드를 실행하면 다음과 같은 이미지가 생성된다.

참고 2

위 코드를 최초로 실행하면 pip로 package 설치하느라 시간이 약간 걸린다. 이때 시간이 오래 걸리면 에러가 발생한다 (에러 메시지: “AI: Agent stopped due to iteration limit or time limit.”). 뭔가 LangChain 설정을 변경해야할 듯 하다.

streamlit을 이용한 웹 UI

우선 streamlit을 설치하자. (streamlit은 snowflake에서 만든 framework로서 요즘 streamlit을 이용하여 많은 demo app들이 개발되고 있다, 세상 참 좋아졌다)

pip install streamlit

설치된 버전은 streamlit==1.26.0였다.

UI는 pip로 설치되지 않기 때문에 source code를 checkout 해야한다.

$ git clone https://github.com/shroominic/codeinterpreter-api.git
$ cd codeinterpreter-api/

(openai api token을 입력하려면 frontend/app.py에 code를 입력하거나 .env 파일을 만든 후 OPENAI_API_KEY=xxxx 처럼 입력하면 된다)

이제 UI를 띄워보자.

$ streamlit run frontend/app.py

브라우저에 다음과 같은 화면이 뜬다. (자동으로 뜨지 않으면 http://localhost:8501/에 접속하면 될 듯하다)

간단히 질문을 해봤다. “kospi 200 지수 chart를 그려줘”

그랬더니 다음과 같은 chart가 그려졌다.