chat gpt 활용법

[챗GPT API와 외부도구 연계] chat_completion&gradio

주니코니 2023. 8. 21. 14:03

"아래 코드는 현시점에서 현직에서 유용하고 센스있는 코드" -마이크로소프트 김태영 강사님
 
해당 본문은 아래 사이트의 코드 내용을 요약했습니다.

챗GPT API와 외부도구 연계

이 노트북은 GPT 모델의 능력을 확장하기 위해 외부 함수와 함께 Chat Completions API를 사용하는 방법에 대해 다룹니다. functions는 Chat Completion API에서 선택적으로 사용할 수 있는 매개변수로, 함수 사

tykimos.github.io

+ chat completion(문장 완성 api)에 대하여

OpenAI Platform

Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.

platform.openai.com


chat_completion란? : OpenAI API를 사용하여 대화형 완성 요청을 수행

딱 한가지만 기억하자!
message 넘길 때 function 호출도 해준다
=> api 호출을 두번 호출하는 셈(비용이 어마어마..하지만 실질적으로는 가격이 싸서 비용이 크지 않다)
=> 하단 코드 'functions = functions' 
 

[실습] - 위 사이트 코드 내용 

messages.append({"role": "user", "content": "I'm in Seoul."})
#대화 내용(messages 리스트)에 여러분의 위치 정보가 포함되게 됩니다.
chat_response = chat_completion_request(
    messages, functions=functions
)
# 대화의 응답을 가져옵니다. 함수에는 현재까지의 대화 내용(messages)과 날씨에 관한 함수의 설명서(functions)를 전달하게 됩니다.
assistant_message = chat_response.json()["choices"][0]["message"]
messages.append(assistant_message)
assistant_message

내가 있는 위치의 날씨를 알려주는 챗봇을 만든다고 가정해보자.
그런데 정작 코드에는(위 사이트) 위치의 경도-위도 정보가 없다.
그래서 gpt에 물어봤다.

위치정보(위도,경도)에 대해 말을 하지 않았는데 어떻게 Seoul이 어느 나라의 어느 곳인지 알지? 

좋은 질문이에요! 
이 코드에서는 실제로 "Seoul"이 서울, 대한민국을 의미한다는 구체적인 정보를 제공하고 있지 않습니다. 
그러나 인공지능은 훈련 데이터에 따라 "Seoul"이 대한민국의 수도라는 것을 알 수 있습니다.

OpenAI의 GPT 같은 모델은 수많은 텍스트 데이터를 기반으로 훈련되기 때문에, "Seoul"이 어디를 의미하는지,
어떤 나라의 수도인지 등의 기본적인 정보는 알고 있습니다. 
따라서 사용자가 "Seoul"이라고만 말해도 그것이 대한민국의 서울을 의미한다고 추측할 수 있어요.

하지만 항상 정확하게 알아맞히는 것은 아니기 때문에, 
실제 서비스에서는 사용자로부터 더 구체적인 위치 정보를 요청하거나, 여러 가능성 중에서 선택하도록 유도하는 것이 좋습니다.

결과 ㅎㅎ
교수님 잠시 헤매시는 사이에…!
우리반에서 어쩌면? 내가 제일 먼저 했다 음하아항ㅎ나해ㅏ앻ㄴㅇㅎ

 
위 활용된 날씨 오픈 AI(무료)

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 
+ gradio install해서 챗봇 만들면 끝!

!pip install gradio
import gradio as gr
#아래 코드는 챗봇이 매우 똑똑하다~~~!(위 수정본)
def respond(user_message, chat_history, state_message_history):  # 채팅봇의 응답을 처리하는 함수를 정의합니다.

    if len(state_message_history) == 0: #state_message_history의 길이가 0인지 확인합니다. 길이가 0이면 이는 첫 번째 메시지임을 의미합니다.
        state_message_history.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})

    state_message_history.append({"role": "user", "content": user_message})

    chat_response = chat_completion_request(
        state_message_history, functions=functions
    )

    assistant_message = chat_response.json()["choices"][0]["message"]

    response_message = assistant_message

     # Step 2: check if GPT wanted to call a function
    if response_message.get("function_call"):
        # Step 3: call the function
        # Note: the JSON response may not always be valid; be sure to handle errors
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # only one function in this example, but you can have multiple
        # 1. 함수 이름 획득
        function_name = response_message["function_call"]["name"]
        # 2. 함수 이름으로 실제 함수 주소 획득
        fuction_to_call = available_functions[function_name]

        # 3. 인자 획득
        function_args = json.loads(response_message["function_call"]["arguments"])

        # 4. 함수 호출 및 결과 획득 (함수 이름과 인자를 사용하여)
        function_response = fuction_to_call(
            location=function_args.get("location"),
            unit=function_args.get("unit"),
        )

        print(function_response)

        # Step 4: send the info on the function call and function response to GPT
        # AI가 전달해준 함수 호출 정보
        state_message_history.append(response_message)  # extend conversation with assistant's reply
        # 시스템이 함수 호출 후 결과 정보
        state_message_history.append(
            {
                "role": "function",
                "name": function_name,
                "content": function_response,
            }
        )  # extend conversation with function response

        # 종합 메시지로 ai 메시지 요청
        second_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0613",
            messages=state_message_history,
        )  # get a new response from GPT where it can see the function response

        state_message_history.append(second_response["choices"][0]["message"])
        print(second_response)
        bot_message = second_response["choices"][0]["message"]['content']
    else:
        state_message_history.append(assistant_message)
        bot_message = assistant_message['content']

    chat_history.append((user_message, bot_message))  # 채팅 기록에 사용자의 메시지와 봇의 응답을 추가합니다.

    return "", chat_history, state_message_history  # 수정된 채팅 기록을 반환합니다.

with gr.Blocks() as demo:  # gr.Blocks()를 사용하여 인터페이스를 생성합니다.

    state_message_history = gr.State([])

    chatbot = gr.Chatbot(label="채팅창")  # '채팅창'이라는 레이블을 가진 채팅봇 컴포넌트를 생성합니다.
    msg = gr.Textbox(label="입력")  # '입력'이라는 레이블을 가진 텍스트박스를 생성합니다.
    clear = gr.Button("초기화")  # '초기화'라는 레이블을 가진 버튼을 생성합니다.

    msg.submit(respond, [msg, chatbot, state_message_history], [msg, chatbot, state_message_history])  # 텍스트박스에 메시지를 입력하고 제출하면 respond 함수가 호출되도록 합니다.
    clear.click(lambda: None, None, chatbot, queue=False)  # '초기화' 버튼을 클릭하면 채팅 기록을 초기화합니다.

demo.launch(debug=False)  # 인터페이스를 실행합니다. 실행하면 사용자는 '입력' 텍스트박스에 메시지를 작성하고 제출할 수 있으며, '초기화' 버튼을 통해 채팅 기록을 초기화 할 수 있습니다.