본문 바로가기
데이터&AI

python API를 활용한 chatgpt- 과거내용 기억하기

by 일등박사 2023. 3. 5.

안녕하세요~!!!

파이썬 API를 활용하여 새로나온 chatgpt(gpt-3.5-turbo) 를 활용하는 법을 알아보았는데요!!

 

2023.03.04 - [일등박사의 생각/데이터분석] - OpenAI의 ChatGPT를 파이썬 API로 이용하기(gpt-3.5-turbo)

 

OpenAI의 ChatGPT를 파이썬 API로 이용하기(gpt-3.5-turbo)

안녕하세요!!! 미국시간 3/1일! OpenAI사에서 드디어 최신의 GPT를 API서비스로 오픈했습니다!! gpt-3.5-turbo라는 이 신규 API는 1K토큰당 0.002$로, 기존의 GPT api였던 text-davinci-003($0.0200 / 1K tokens) 의 1/10 수

drfirst.tistory.com

이 문제점은 chatgpt를 사이트에서 사용하는 것과 다르게

과거의 내용을 기억하며 대화할수 없다는 단점이 있었습니다!!

이 문제를 해결하여, 대화내용을 기억하고, 연속적으로 대화할수 있는 api를 만들어보겠습니다!!

 


가장 이상적인 방법은 기존 gpt 모델과 같이

fine-tuning을 통하여 데이터를 학습시키는것인데요!

2023.03.04 - [일등박사의 생각/데이터분석] - Python API를 활용하여 OpenAI 교육(파인튜닝, Fine tuning)하기

 

Python API를 활용하여 OpenAI 교육(파인튜닝, Fine tuning)하기

안녕하세요!!!! 최근 OpenAI에서 새로운 GPT 모델인 gpt-3.5-turbo를 출시하였습니다!! 하지만 아쉽게도 GPT를 교육할 수 있는 fine-tuning 모델은 아직 기존 모델로만 가능한데요~! 이번 포스팅에서는 python

drfirst.tistory.com

 

2023년 3월5일 현재 아직  chatgpt모델의 파인튜닝 기술은 적용되지 않고있습니다!

하지만 openai 개발자 커뮤니티에는 과거의 대화를 지속 넣어 대화하는 방법을 대안으로 제시하고있습니다.

이해 해당 코드를 함꼐 파악해봅시다!!

 

1. 모듈 임포트 및 선언

   - 우선 openai의 api키 와 패키지들을 불러옵니다.

   - 추가로 앞으로 대화내용을 지속 저장할 신규변수(conversation_history)를 만들어줍니다.

import pandas as pd
import openai
API_KEY = '{나의 API키}'
openai.api_key = API_KEY

INITIAL_PROMPT = ('''
    당신은 리사라고하는 친절한 AI 비서입니다.
''')
conversation_history = INITIAL_PROMPT + "\n"

USERNAME = "USER"
AI_NAME = "리사"

 

2. 대화내용 저장함수 제작

 - 사용자의 input 과 gpt의 결과값을 누적하여 저장하는 cumulative_input 라는 함수를 만듭니다!!

def cumulative_input(
               input_str : str,
    conversation_history : str,
                USERNAME : str,
                 AI_NAME : str,
                 ):
    # Update the conversation history
    conversation_history += f"{USERNAME}: {input_str}\n"
   
    # Generate a response using GPT-3
    message = get_response(conversation_history)
    # Update the conversation history
    conversation_history += f"{AI_NAME}: {message}\n"

    # Print the response
    print(f'{AI_NAME}: {message}')
    
    return conversation_history

 

3. chatgpt api 함수

  - 지난 포스팅에서도 알아보았던 chatgpt api 함수 "get_response" 를 선언합니다.

def get_response(prompt):
    """Returns the response for the given prompt using the OpenAI API."""
    completions = openai.ChatCompletion.create(
          model = "gpt-3.5-turbo",
          messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt}
            ],
         max_tokens = 1024,
        temperature = 0.7,
    )
    return completions["choices"][0]["message"]["content"]

4.  대화내용을 통한 저장

user_input = "일등박사 라는 블로그가 있는데, 이 블로그는 티스토리에 있는 블로그로 chat gpt에 대하여 소개하고 있어"
conversation_history = handle_input(user_input, conversation_history, USERNAME, AI_NAME)
conversation_history

위와 같이 user_input을 통하여 내역을 "conversation_history" 에 저장하면 이후 아래 그림과 같이 대화가 됨을 알 수 있습니다~!

 

 

 

※ 위 글은 openai 개발자 커뮤니티를 참고하여 작성하였습니다!

https://community.openai.com/t/getting-chatgpt-to-remember-previous-chat-messages/38106/5

 

Getting ChatGPT to Remember Previous Chat Messages

Here’s one of my basic chatbot implementations. I’ve refactored it since, but it should do what you’re looking for import openai # Set the API key openai.api_key = <<YOUR PREFERRED METHOD OF FETCHING API KEYS>> # Choose a model MODEL_ENGINE = "text-d

community.openai.com

 

댓글