콘텐츠로 이동

스트림 + 대화 연동하기

필요한 모듈 설치하기

!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,       
        temperature=1.0,
        stream=True
    )

    partial_message = ""

    for chunk in completion:
        if chunk.choices[0].delta.content is not None:
              partial_message = partial_message + chunk.choices[0].delta.content
              yield partial_message, history

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

    return partial_message, 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()