콘텐츠로 이동

DB에 저장하기

실행 준비

!pip install openai
!pip install gradio

SQLite에 저장하기 위한 기본 템플릿

import gradio as gr
from openai import OpenAI
import json

import sqlite3

client = OpenAI()

# 함수 정의
def customer_request(title, subject, cont):
    customer_info = "제목:" + title + "\n"
    customer_info += "분야:" + subject + "\n"
    customer_info += "내용:" + cont

    return customer_info


# DB에 저장하는 함수 정의    
def save_to_db(title, subject, body):
    gr.Info("CSV로 저장하였습니다.")


tools = [
  {
      "type": "function",
      "function": {
          "name": "customer_request",
          "description": "고객이 문의한 요청사항을 처리하는 함수",
          "parameters": {
              "type": "object",
              "properties": {
                  "title": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 생성한 제목",
                  },
                  "subject": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 '기술지원', '영업', '생산' 중에서 한 가지로 분류한 결과",
                  },
                  "cont": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 생성한 자세한 내용",
                  },
              },
              "required": ["title", "subject", "cont"]
          },
      },
  },
]


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

    completion = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "고객이 '기술지원', '영업', '생산'과 관련된 문의를 한 경우, customer_request 함수를 호출해줘."},
            {"role": "system", "content": "'기술지원', '영업', '생산' 외에 다른 문의을 받았을 경우, '기술지원', '영업', '생산' 정보만을 답변할 수 있다고 해줘."},
            {"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 == "customer_request": 
           title = arguments_json.get('title')
           subject = arguments_json.get('subject')
           cont = arguments_json.get('cont')

           res = customer_request(title, subject, cont)

           return res

    elif response.function_call:
        return response.function_call

    else:
        return 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="문의 사항을 입력해 주세요:")

                # ChatGPT의 응답 출력 텍스트 박스
                output_text = gr.Textbox(label="AI 응답 결과", interactive=False)

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

        demo.launch()

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

SQLite에 저장하는 함수 완성하기

import gradio as gr
from openai import OpenAI
import json

import sqlite3

client = OpenAI()

# 함수 정의
def customer_request(title, subject, cont):
    customer_info = "제목:" + title + "\n"
    customer_info += "분야:" + subject + "\n"
    customer_info += "내용:" + cont

    return customer_info


# DB에 저장하는 함수 정의    
def save_to_db(title, subject, body):

    # SQLite 데이터베이스에 연결 (파일이 없다면 자동으로 생성됨)
    conn = sqlite3.connect('customer.db')  # 'customer.db'는 데이터베이스 파일 이름
    cursor = conn.cursor()  # 커서 객체 생성

    # 데이터 삽입
    cursor.execute('''
        INSERT INTO as_list (title, subject, content)
        VALUES (?, ?, ?)
    ''', (title, subject, body))  # 파라미터화된 방식으로 값 전달


    # 변경사항 저장 (커밋)
    conn.commit()

    # 데이터베이스 연결 종료
    conn.close()

    gr.Info("CSV로 저장하였습니다.")


tools = [
  {
      "type": "function",
      "function": {
          "name": "customer_request",
          "description": "고객이 문의한 요청사항을 처리하는 함수",
          "parameters": {
              "type": "object",
              "properties": {
                  "title": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 생성한 제목",
                  },
                  "subject": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 '기술지원', '영업', '생산' 중에서 한 가지로 분류한 결과",
                  },
                  "cont": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 생성한 자세한 내용",
                  },
              },
              "required": ["title", "subject", "cont"]
          },
      },
  },
]



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

    completion = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "고객이 '기술지원', '영업', '생산'과 관련된 문의를 한 경우, customer_request 함수를 호출해줘."},
            {"role": "system", "content": "'기술지원', '영업', '생산' 외에 다른 문의을 받았을 경우, '기술지원', '영업', '생산' 정보만을 답변할 수 있다고 해줘."},
            {"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 == "customer_request": 
           title = arguments_json.get('title')
           subject = arguments_json.get('subject')
           cont = arguments_json.get('cont')

           res = customer_request(title, subject, cont)

           return res

    elif response.function_call:
        return response.function_call

    else:
        return 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="문의 사항을 입력해 주세요:")

                # ChatGPT의 응답 출력 텍스트 박스
                output_text = gr.Textbox(label="AI 응답 결과", interactive=False)

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

        demo.launch()

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

SQLite에 저장하는 전체 기능 완성하기

import gradio as gr
from openai import OpenAI
import json

import sqlite3

client = OpenAI()

# 함수 정의
def customer_request(title, subject, cont):
    customer_info = "제목:" + title + "\n"
    customer_info += "분야:" + subject + "\n"
    customer_info += "내용:" + cont

    #DB 서버 저장
    save_to_db(title, subject, cont)

    return customer_info


# DB에 저장하는 함수 정의
def save_to_db(title, subject, body):

    # SQLite 데이터베이스에 연결 (파일이 없다면 자동으로 생성됨)
    conn = sqlite3.connect('customer.db')  # 'customer.db'는 데이터베이스 파일 이름
    cursor = conn.cursor()  # 커서 객체 생성

    # 데이터 삽입
    cursor.execute('''
        INSERT INTO as_list (title, subject, content)
        VALUES (?, ?, ?)
    ''', (title, subject, body))  # 파라미터화된 방식으로 값 전달


    # 변경사항 저장 (커밋)
    conn.commit()

    # 데이터베이스 연결 종료
    conn.close()

    gr.Info("CSV로 저장하였습니다.")


tools = [
  {
      "type": "function",
      "function": {
          "name": "customer_request",
          "description": "고객이 문의한 요청사항을 처리하는 함수",
          "parameters": {
              "type": "object",
              "properties": {
                  "title": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 생성한 제목",
                  },
                  "subject": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 '기술지원', '영업', '생산' 중에서 한 가지로 분류한 결과",
                  },
                  "cont": {
                     "type": "string",
                     "description": "ChatGPT가 고객의 요청사항을 분석한 후 생성한 자세한 내용",
                  },
              },
              "required": ["title", "subject", "cont"]
          },
      },
  },
]


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

    completion = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "고객이 '기술지원', '영업', '생산'과 관련된 문의를 한 경우, customer_request 함수를 호출해줘."},
            {"role": "system", "content": "'기술지원', '영업', '생산' 외에 다른 문의을 받았을 경우, '기술지원', '영업', '생산' 정보만을 답변할 수 있다고 해줘."},
            {"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 == "customer_request": 
           title = arguments_json.get('title')
           subject = arguments_json.get('subject')
           cont = arguments_json.get('cont')

           res = customer_request(title, subject, cont)

           return res

    elif response.function_call:
        return response.function_call

    else:
        return 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="문의 사항을 입력해 주세요:")

                # ChatGPT의 응답 출력 텍스트 박스
                output_text = gr.Textbox(label="AI 응답 결과", interactive=False)

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

        demo.launch()

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