AI

싸가지 없는 챗지피티

백진암 2024. 6. 26. 11:05

openai에 Assistant라는게 있다.

한 분야에 특화 되어있는 대화 봇을 만드는 건데

예를 들면 맞춤법 검사, 파이썬 에러 고치기, 면접 질문하기 등의 봇을 만들 수 있다.

 

이를 재밌게 응용하면 롤 챔피언 분석하기, 야구 경기 분석하기도 가능하지마 또는 "너는 뉴진스 민지야" 이런 식으로 자아를 바꾸게도 가능하다.

물론 추가적인 학습이 필요하다.

사용법

지피티를 결제한다.

정기결제를 하든 쓰는만큼 내든 알아서 결제하고


VSC에서 requirements.txt 파일을 만든다.

python-dotenv
openai
streamlit
opencv-python
numpy
requests

 

가상환경을 만들어 주고 pip install -r requirements.txt 를 하면 일괄 다운로드 할 수 있다.

 

assistant.py를 만들어주고

import openai
from dotenv import load_dotenv
import time
import logging
from datetime import datetime
load_dotenv()
client = openai.OpenAI()

model = "gpt-3.5-turbo-16k"
assistant_id ="비밀"
thread_id="비밀"

personal_trainer_assis = client.beta.assistants.create(
    name ="싸가지 없는놈",
    instructions="""너는 세상에서 가장 싸가지 없는 놈이야.
앞으로의 대화에서 너는 정확한 대답을 하지 않고 쓸데없는 소리를 하거나 화를내면서 나한테 어떻게 그딴 질문을 하냐는 식으로 따져야해.
또 내가 말 한 마디 할 때마다 기분이 달라져서 말투도 바껴야하고, 말투는 전부 짧고 간결하게 해. 자세하게 답변하지마.
정확한 답은 가끔만.
예시를 줄게.
만약 내가 "오리너구리가 뭐야?" 라고 물으면
너는 "오리랑 너구리 합친거."이런식으로 짧고 성의없게 대답해야해. 모든 디테일은 다 빼.
다른 예시로 내가 "저녁 메뉴 추천해줘" 라고 말하면 너는 "니 알아서 먹어" 이런식으로 원하는 답을 주지않고 상대방 기분이 나쁘게 대답해야해.
또 다른 예시로 "3+3은 뭐야?" 라고 물으면 "6. 이것도 모르냐" 이런식으로 대답해.
너무 답을 안 주면 안되고 가끔 대답은 해주되 상대방이 기분이 나쁘게 해야해. 말해주기 싫은 느낌으로.
여러번 똑같은 질문을 하면 귀찮다는 듯이 대답해줘.
모든 대답은 한 줄에서 두 줄내로 끝내 세 줄이상은 금지. 상대방을 무시하는 느낌으로 대답해야해.
다음 대답부터 시작해
    """,
    model = model
)

print(personal_trainer_assis.id)

 

이렇게 assistant id를 새로 생성해서 변수로 저장을 한다.

assistant를 생성할 때 이름과 그 assistant의 특징과 설명을 적어주면 된다. 길게 적을 수록 정확도가 높아지는 듯하다.

나는 싸가지 없는 놈을 만들기 위해 위와 같이 작성했다.

 

그리고

thread = client.beta.threads.create(
    messages=[
        {
            "role": "user",
            "content": "안녕"
        }
    ]
)
print(thread.id)

이렇게 쓰레드 id도 생성해서 변수로 저장을 한다.

 

이렇게 하고

https://platform.openai.com/assistants/어시스턴트id

에 들어가면 생성한 assistant를 확인할 수 있다.

 

이제 질문을 해보자.

message = "나 파이썬 알려주라"

message = client.beta.threads.messages.create(
    thread_id = thread_id,
    role="user",
    content=message
)

run = client.beta.threads.runs.create(
    assistant_id=assistant_id,
    thread_id=thread_id,
    instructions=""
)
run_id = run.id
def wait_for_run_completion(client, thread_id, run_id, sleep_interval=5):
    """

    Waits for a run to complete and prints the elapsed time.:param client: The OpenAI client object.
    :param thread_id: The ID of the thread.
    :param run_id: The ID of the run.
    :param sleep_interval: Time in seconds to wait between checks.
    """
    while True:
        try:
            run = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id)
            if run.completed_at:
                elapsed_time = run.completed_at - run.created_at
                formatted_elapsed_time = time.strftime(
                    "%H:%M:%S", time.gmtime(elapsed_time)
                )
                print(f"Run completed in {formatted_elapsed_time}")
                logging.info(f"Run completed in {formatted_elapsed_time}")
                # Get messages here once Run is completed!
                messages = client.beta.threads.messages.list(thread_id=thread_id)
                last_message = messages.data[0]
                response = last_message.content[0].text.value
                print(f"Assistant Response: {response}")
                break
        except Exception as e:
            logging.error(f"An error occurred while retrieving the run: {e}")
            break
        logging.info("Waiting for run to complete...")
        time.sleep(sleep_interval)


# === Run ===
wait_for_run_completion(client=client, thread_id=thread_id, run_id=run.id)

# ==== Steps --- Logs ==
run_steps = client.beta.threads.runs.steps.list(thread_id=thread_id, run_id=run.id)
print(f"Steps---> {run_steps.data[0]}")

message 변수에 질문을 적고 실행하면 답을 받을 수 있다.

이렇게 매우 싸가지없는 답변을 받을 수 있게 된다.

 

질문

질문: 배고프다

 

질문: 라면 추천해줘

 

질문: 나 사랑니 났는데 너무 아파

 

매우 싸가지가 없다.

 

간단한 웹 배포

streamlit을 이용하면 파이썬 코드로 작성한 내용을 간단하게 웹으로 만들 수 있다.

import streamlit as st
import openai
from dotenv import load_dotenv
import time
import logging

load_dotenv()

# Initialize OpenAI client
client = openai.OpenAI()

# Constants for your assistant and thread IDs
assistant_id = "asst_IqrZ6sbu19N7Z93hNPHkCaCY"
thread_id = "thread_O8yqKwlh9J5aDa6qFgtopA8L"

st.title('싸가지없는넘')

# Function to interact with the assistant
def interact_with_assistant(message):
    try:
        # Send message to the thread
        client.beta.threads.messages.create(
            thread_id=thread_id,
            role="user",
            content=message
        )

        # Start a new run
        run = client.beta.threads.runs.create(
            assistant_id=assistant_id,
            thread_id=thread_id,
            instructions=""
        )
        run_id = run.id

        # Wait for run completion
        while True:
            run = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id)
            if run.completed_at:
                # Get the latest assistant response
                messages = client.beta.threads.messages.list(thread_id=thread_id)
                last_message = messages.data[0]
                response = last_message.content[0].text.value
                return response
            time.sleep(2)  # Check every 2 seconds for completion

    except Exception as e:
        st.error(f"Error interacting with the assistant: {e}")

# Streamlit UI components
message = st.text_input('Input your message:')
if st.button('Send'):
    if message:
        st.info(f"User: {message}")
        response = interact_with_assistant(message)
        st.success(f"Assistant: {response}")
    else:
        st.warning("Please enter a message.")

이렇게 만들고 실행만 하면 바로 localhost에서 내 Assistant와 대화를 할 수 있다.

어떻게 하는지 궁금하다면 ChatGpt에게 물어보면 된다.

이렇게 간단하게 대화를 주고 받는 assistant를 만들어 봤다.

여전히 싸가지가 없다.