콘텐츠로 이동

Gradio에서 표로 표시하기

실행 준비

!pip install openai
!pip install gradio

Gradio에 표로 표시하기

import gradio as gr
from openai import OpenAI
import json
import pandas as pd

client = OpenAI()

# 쿼리를 실행하는 함수 정의
def product_inquiry(query):

    conn = sqlite3.connect('products.db')
    df = pd.read_sql_query(query, conn)

    return df


tools = [
  {
      "type": "function",
      "function": {
          "name": "product_inquiry",
          "description": "고객이 문의한 제품에 대한 문의사항을 처리하는 함수",
          "parameters": {
              "type": "object",
              "properties": {
                  "query": {
                     "type": "string",
                     "description": "고객이 문의한 내용에 대한 답변을 생성하기 위해 SQLite 기반으로 작성된 SQL 명령어",
                  },
              },
              "required": ["query"]
          },
      },
  },
]


# df 생성함수
def make_df(str):
    a = {'결과' : [str]}
    pd.DataFrame(a)  


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

    completion = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "요청사항을 분석한 후 다음의 상품정보 테이블에서 데이터를 조회하는 SQLite 기반의 SQL 명령어를 작성해줘."},
            {"role": "system", "content": "상품정보 테이블의 구성은 다음과 같아: create table products(prod_id integer primary key, prod_type text, prod_name text, prod_price integer, prod_count integer, desc text, ref text)"},
            {"role": "system", "content": "prod_name은 제품의 이름, prod_price는 제품의 가격, prod_count는 제품의 판매 가능한 재고 숫자를 의미해."},
            {"role": "system", "content": "생성된 SQL 쿼리를 product_inquiry 함수를 호출하여 넘겨줘."},
            {"role": "user", "content": prompt_text}
        ],
        tools=tools,
    )

    response = completion.choices[0].message;

    if response.tool_calls:
        tool_call = response.tool_calls[0]

        arguments = tool_call.function.arguments
        function_name = tool_call.function.name

        arguments_json = json.loads(arguments)

        if function_name == "product_inquiry":  
           query = arguments_json.get('query')

           #쿼리를 실행함
           df = product_inquiry(query)

           return df

        else:
           return make_df("정의되지 않은 함수입니다.")

    elif response.function_call:
        return make_df(response.function_call)

    else:
        return make_df(response.content)


# Gradio Blocks 인터페이스 설정
def chatgpt_interface():
    with gr.Blocks() as demo:
        gr.Markdown("### My ChatGPT")

        with gr.Row():
            with gr.Column():
                # 사용자 입력 텍스트 박스
                input_text = gr.Textbox(label="문의 사항을 입력해 주세요:")

                # 버튼 클릭 시 실행될 출력 필드
                output = gr.DataFrame(label="결과")

                # 버튼 클릭 시, ChatGPT 응답 생성
                input_text.submit(generate_response, inputs=input_text, outputs=output)

        demo.launch()

# ChatGPT 인터페이스 실행
chatgpt_interface()