콘텐츠로 이동

이메일 발송 기능 추가

실행 준비

!pip install openai
!pip install gradio

이메일 발송함수 추가하기

import gradio as gr
from openai import OpenAI
import json

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

client = OpenAI()

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

    return customer_info


# 이메일을 발송하는 함수 정의
def send_email(receiver, subject, body):

    # 수신자 이메일
    receiver_email = receiver

    # 발신자 이메일
    sender_email = 'colabsample01@gmail.com'  # 발신자 이메일

    # 발신자 이메일 Gmail 앱 비밀번호 (일반 Gmail 비밀번호가 아님)
    password = 'qntl tkuf fujx cmfy'

    # MIME 객체 생성
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    # Gmail SMTP 서버에 연결하고 이메일 보내기
    # Gmail SMTP 서버 (smtp.gmail.com)와 포트 587을 사용
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()  # TLS 보안 연결
    server.login(sender_email, password)  # 로그인

    # 이메일 발송
    text = msg.as_string()
    server.sendmail(sender_email, receiver_email, text)

    # 서버 연결 종료
    server.quit()


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

        else:
           return "잘못된 함수입니다."

    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()

이메일 발송기능 완성하기

import gradio as gr
from openai import OpenAI
import json

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

client = OpenAI()

# 함수 정의
def customer_request(title, subject, cont):

    receiver = "hello@gmail.com"
    mail_title = f"(제목:{title} / 분야:{subject})"

    send_email(receiver, mail_title, cont)

    customer_info = "메일 수신자:" + receiver + "\n"
    customer_info += "제목:" + title + "\n"
    customer_info += "분야:" + subject + "\n"
    customer_info += "내용:" + cont + "\n"
    customer_info += "으로 메일이 발송되었습니다."

    return customer_info


# 이메일을 발송하는 함수 정의
def send_email(receiver, subject, body):

    # 수신자 이메일
    receiver_email = receiver

    # 발신자 이메일
    sender_email = 'colabsample01@gmail.com'  # 발신자 이메일

    # 발신자 이메일 Gmail 앱 비밀번호 (일반 Gmail 비밀번호가 아님)
    password = 'qntl tkuf fujx cmfy'

    # MIME 객체 생성
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    # Gmail SMTP 서버에 연결하고 이메일 보내기
    # Gmail SMTP 서버 (smtp.gmail.com)와 포트 587을 사용
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()  # TLS 보안 연결
    server.login(sender_email, password)  # 로그인

    # 이메일 발송
    text = msg.as_string()
    server.sendmail(sender_email, receiver_email, text)

    # 서버 연결 종료
    server.quit()


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

        else:
           return "잘못된 함수입니다."

    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()