콘텐츠로 이동

대화 히스토리 사용하기

필요한 모듈 설치하기

!pip install openai
!pip install gradio

Blocks에서 직접 대화의 히스토리를 저정하는 기능을 구현

import gradio as gr
from openai import OpenAI

client = OpenAI()

# 응답 생성 함수
def generate_response(prompt_text, history):

    # 사용자 프롬프트를 목록에 추가
    history.append({"role": "user", "content": prompt_text})

    completion = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=history,
    )

    response = completion.choices[0].message;

    # 응답 결과를 목록에 추가
    history.append({"role": "assistant", "content": response.content})

    return response.content, history


with gr.Blocks() as demo:
    gr.Markdown(
    """
    # 홍길동의 AI 화학 전문가
    화학에 대해 궁금한 사항이 있으면 질문해 주세요.
    """)

    with gr.Row():
        with gr.Column():

            # State 형식의 리스트를 선언
            history = gr.State([])

            input_text = gr.Textbox(label="프롬프트:")
            output_text = gr.Textbox(label="ChatGPT 결과", interactive=False)

            input_text.submit(generate_response, inputs=[input_text, history], outputs=[output_text, history])

demo.launch()