콘텐츠로 이동

Gradio와 ChatGPT (히스토리)

필요한 모듈 설치하기

!pip install openai
!pip install gradio

Gradio와 ChatGPT를 합치는 가장 간단한 예시 - 대화 히스토리

from openai import OpenAI
import gradio as gr

client = OpenAI()

def predict(message, history):
    history_openai_format = []

    for human, assistant in history:
        history_openai_format.append({"role": "user", "content": human })
        history_openai_format.append({"role": "assistant", "content":assistant})

    history_openai_format.append({"role": "user", "content": message})

    response = client.chat.completions.create(model='gpt-4o-mini',
    messages= history_openai_format,
    temperature=1.0,
    stream=True)

    partial_message = ""
    for chunk in response:
        if chunk.choices[0].delta.content is not None:
              partial_message = partial_message + chunk.choices[0].delta.content
              yield partial_message

gr.ChatInterface(predict).launch()

설명

  • 우리가 보통 웹브라우저에서 ChatGPT를 사용하는 방식을 API로 구현한 예제입니다.
  • 대화 히스토리 기능과 스트림 기능이 모두 포함된 가장 복잡한 예제 중의 하나 입니다.