콘텐츠로 이동

함수 호출하기

실행 준비

!pip install openai
!pip install gradio

응답값 확인하기1

import gradio as gr
from openai import OpenAI
import json

client = OpenAI()

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

    return customer_info

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)

        return f"{arguments} / {function_name}"

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

응답값 확인하기2

import gradio as gr
from openai import OpenAI
import json

client = OpenAI()

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

    return customer_info

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

           return f"{title} / {subject} / {cont}"

        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

client = OpenAI()

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

    return customer_info

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