message에 role:user와 role:assistant에 대화를 누적해가며 계속 호출하면되는데
대화방 컨텍스트에 따른 대화이력 저장방식이 필요함으로
여기서는 단순 1회성 호출만 소개한다.
import os
import openai
import datetime
openai.api_key = os.getenv("OPENAI_API_KEY") #부여 받은 api key, 이걸 기준으로 과금된다.
로컬에 환경변수에 저장된 key를 가져오도록 해놨다.
#openai.organization = "org-cT1P어쩌고L" #api key의 계정-조직의 id,
#지금처럼 주석으로 막아놓듯이 선언을 따로 안하면 open ai에 세팅된 디폴트 organizaion을 사용한다.
inputPrompt = "자기 소개서 잘 쓰는법 알려줘" # reqeust 문장
model = "gpt-3.5-turbo" # 모델선택 gpt-4, gpt-4-0314, gpt-4-32k, gpt-4-32k-0314, gpt-3.5-turbo, gpt-3.5-turbo-0301
# massage는 복수형 array인데, user와 assistant의 대화 히스토리를 통째로 보내서
요청할수 있는 구조이다. 여기선 1회성 호출만 하도록 role user의 명렁 1개만 넣어 호출한다
completion = openai.ChatCompletion.create(
model=model,
temperature=0,
messages=[
{"role": "user", "content": inputPrompt}
]
)
result = completion.choices[0]
# 결과는 복수개를 돌려준다, 이중에 최상단 1개값만 가져온다
#print (result)
# 결과값은 obect로 되어있다. 주석처리하여 따로 보지않도록 해놨고 보고싶으면 주석해제하면됨
print (result.message.content)
# 결과값에서 assistant 응답메세지만 가져온다
print(datetime.datetime.now())
# 그냥 현재 시간 표시용
*openai.api_key는 open ai에서 발급받아 사용하며, 유료 호출이다. gpt-3.5의 경우 매우 저렴하기에 딱히 별 이슈가 없다.
*api_key는 local에 저장된 환경변수를 가져다 쓰는 방식이 스탠다드다, 윈도우는 환경변수로 key를 넣는게 매우 쉽고, MAC은 터미널로 좀 까다로운 작업이 필요함, 잘 모르겠으면 그냥 open ai의 api key 를 그대로 = 뒤에다가 string으로 붙여서 써도 된다.
다만 이럴경우 스크립트를 온라인으로 그대로 공유할때 api key가 공개됨으로 남이 막 쓸수있다. 유료라서 과금이 되니 문제가됨
message의 role user의 content에 명령어를 넣고,
결과는 completion이 복수형으로 나오는데, 이중에 만앞에꺼면 뽑아서 message.content를 출력하면 된다.
python-telegram-bot 이란 놈을 설치해야 한다. (걍 telegram이 아님)
cmd/터미널 명령 예시
pip3 install python-telegram-bot
그다음
아래의 텔레그램 봇 스크립트와
callgpt4라고 gpt를 호출하는 모듈 스크립트가 필요하다
import logging
import callgpt4 #내가 만든 gpt4호출 모듈
from telegram import __version__ as TG_VER
token = "63525숫자647:AAFnJM어쩌고 당신이 만든 대화방의 토큰"
try:
from telegram import __version_info__
except ImportError:
__version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
if __version_info__ < (20, 0, 0, "alpha", 1):
raise RuntimeError(
f"This example is not compatible with your current PTB version {TG_VER}. To view the "
f"{TG_VER} version of this example, "
f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
)
from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context.
# /start로 대화방을 가동시키는 경우 봇의 첫 메세지
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_html(
rf"안 {user.mention_html()}!, 나는 chatgpt 메신저야",
reply_markup=ForceReply(selective=True),
)
#입력된 메세지로, modgpt4 (gpt4 api를 호출하여 답변을 얻은 모듈) 모듈을 사용
async def gpt(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""gpt모듈을 호출하는것."""
print (update.message.text)
await update.message.reply_text("......") #gpt4 모듈이 응답을 준비하는동한 메세지로 ......을 보냄
userPrompt = update.message.text
gptresult = callgpt4.Command(userPrompt)
await update.message.reply_text(gptresult) #gpt4모듈의 답변을 메세지로 보냄
#위의 함수들을 종합하여 텔레그램에 커맨드와 답변을 처리하는 영역
def main() -> None:
"""Start the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token(token).build()
# on different commands - answer in Telegram # /start등 /어쩌고로 지정된 액션을 받아들여, 해당 함수(start)를 호출 동작실행 시키는 커맨드 핸들러
application.add_handler(CommandHandler("start", start))
# on non command i.e message - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, gpt)) #텔레그램 user messager를 받아 해당 함수(gpt)에 메세지 input을 넣을수 있는 메세지 핸들러
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
* 일단 텔레그램 메신저에서 Bot을 만들고, 텔레그램 Bot 대화방을 생성한뒤 해당 대화방 토큰을 얻어야 한다.