MACHINE LEARNING

OpenAI Assistant API 활용 예제 (Python Code) / ChatGPT

24_bean 2023. 11. 12. 16:31

지난 11월 06일 OpenAI는 DevDay를 통해 새로운 Assistant API를 공개하였습니다.

 

Assistant는 "Code Interpreter, Retrieval, Function calling" 과 같은 다양한 도구를 활용할 수 있습니다.

현재 베타 버전으로, 특정 Instruction과 model selection을 통해 사용자 정의 assistant를 생성할 수 있습니다.

 

Assistant를 활용하는 것은 다음과 같은 절차에 의해 구성됩니다.


1. 어시스턴트 생성
   - 어시스턴트에 대한 사용자 정의 지침 정의.
   - 모델 선택 및 Code Interpreter, Retrieval, Function calling과 같은 도구 활성화 여부 선택.

2. 대화 플로우
   - 사용자가 대화를 시작하면 Thread 생성.
   - 사용자의 질문에 따라 Thread에 Messages 추가.

3. 어시스턴트 실행
   - Thread에서 어시스턴트를 실행하여 응답 트리거.
   - API는 어시스턴트 구성에 따라 자동으로 관련 도구를 호출.

 

코드와 함께 조금 자세히 활용법을 알아보겠습니다.

 

https://devday.openai.com

 

OpenAI DevDay

New models and developer products announced at DevDay GPT-4 Turbo with 128K context and lower prices, the new Assistants API, GPT-4 with Vision, DALL·E 3 API, and more.

devday.openai.com

 


 

0. 전체 구성

 

OpenAI가 제안하는 전체 프로세스를 정리해보면 다음과 같습니다.

 

* Object

 

* Run life-cycle

 

* Run Step


1. 어시스턴트(Assistant) 생성

 

기존 OpenAI의 API를 활용하는 것과 같이 우선 API KEY를 환경 변수에 추가해야합니다.


* client 선언

client = OpenAI(api_key="YOUR_API_KEY")

 

* Assistant를 생성합니다.

 

아래의 코드 예시는 제가 작성한 임의의 예시입니다.

쉽게 생각하면, 모델에게 자아(?)를 부여하는 것입니다

 

ex)

너의 이름은 "CSV interpreter"야,

나는 너가 다음과 같이 행동하길 바래, "You are a CSV ~~~", 

너가 활용할 Tool은 "code_interpreter"야,

모델은 "gpt-4-1106-preview"를 사용하고,

file에 대한 정보는 "[file.id]"야

new_assistant = client.beta.assistants.create(
        name="CSV interpreter",
        instructions=f"You are a CSV interpreter.\
            \nI want you to give me a recommendation for visualization of the data.",
        tools=[{"type": "code_interpreter"}], # type: code_interpreter, retrieval, function
        model="gpt-4-1106-preview",
        file_ids=[file.id]
    )

 

file에 대한 입출력 또한 위와 같이 관리할 수 있습니다.

 

이 때 retrieval은 파일의 지속적인 접근을 다루는 내용이며 code interpreter와의 자세한 비교는 아래 표를 참조바랍니다.

 

 

* 참조: https://platform.openai.com/docs/assistants/tools/supported-files

 

OpenAI Platform

Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.

platform.openai.com

 


2. 쓰레드(Thread) 생성

 

대화를 위한 쓰레드를 생성합니다.

 

new_thread = client.beta.threads.create()
    message = client.beta.threads.messages.create(
        thread_id=new_thread.id,
        role="user",
        content="I need to visualize the data. Can you recommend me 4 plots that describe the data as much as possible?",
        )

 


3. 어시스턴트(Assistant) 실행

 

추가한 쓰레드에 대한 답변을 정의한 어시스턴트에게 요청합니다.

 

run = client.beta.threads.runs.create(
        thread_id=thread.id,
        assistant_id=assistant.id,
        # instructions="I want you to elaborate why you recommend these plots.", <- duplicate instructions
    )
while(run.status != "completed"):
    run = client.beta.threads.runs.retrieve(
        thread_id=thread.id,
        run_id=run.id
    )

    print("run.status: ", run.status)
    if run.status == "failed":
        raise Exception("The run failed with the message: " + run.error)

messages = client.beta.threads.messages.list(
    thread_id=thread.id,
)
return messages

 

 

* 이때 beta 버전의 API 답게 불편함이 꽤나 많습니다. 특히, While 문을 통해 지속적인 요청을 보내야한다는 점이 그 단점입니다.

해당 이슈에 대한 OpenAI 또한 문제를 인식하고 있는 듯 보입니다.

 

* 아래는 OpenAI의 답변 중 일부를 발췌했습니다.


ETC

사실 매번 코드를 작성하고 내가 원하는 작업이 정상적으로 동작하는 지 여부를 판단하는 것은 생각보다 직관적이지 못한 경우도 있고, 더욱 쉬운 방법이 있다면 굳이 해보지 않을 이유는 없죠?

 

직관적으로 내가 원하는 작업과 모델의 이용가능성을 Playground에서 확인해보시면 됩니다.

 

* Playground 활용 예시

 

https://platform.openai.com/playground?assistant=asst_uU2p7HUg96AC8NxjFhX4dR7X

 

OpenAI Platform

Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.

platform.openai.com

 

* 자세한 활용 방안은 아래에 링크를 참조해주세요.

https://platform.openai.com/docs/assistants/overview

 

OpenAI Platform

Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.

platform.openai.com