ChatGPT API 사용하는 법 초간단 예제를 아래 순서로 포스팅 합니다.
내용이 유익하셨다면, 구독/댓글/좋아요 부탁드립니다.
- Simple Tutorial
- ChatGPT 와 연속적인 대화 만들기
- 사전 Prompt 적용하기
해당 포스팅은 2. ChatGPT 와 연속적인 대화 만들기 에 대한 글입니다.
5. ChatGPT 사용법 - 블로그 프롬프트 7가지 에서 제공한 Pre-defined 된 프롬프트를 적용하여, 코드로 구현할 차례이다.
아래는 블로그 글 작성 Prompt 를 적용하여 만들어진 결과이다.
적용하지 않았을 때와 너무 확연한 차이가 난다.
예상한대로 아웃라인을 작성해줬고, 이후 서문과 내용을 적어주는데, 마지막 문장이 끊겼다.
이는 API 요청을 통해 결과를 전달받을 경우 제한된 Token 수로 인한 것으로 추측된다.
response 에 'stop' 값이 제대로 담겨있는지 확인해 볼 필요가 있어 확인해보니,
finish_reason 이 기존 수행한 것처럼 stop 이 아닌 length 란 결과로 나왔고,
'usage' 를 확인하니, 설정한 Token 인 2048을 모두 소진한 것으로 확인되었다.
지정한 token 값이 2048 로 모두 결과를 출력하는데 사용됐고, 389 는 pre-prompt 와 prompt 의 값이다.
최대값인 4096으로 값을 세팅하게 되더라도, 이는 문제가 될 여지가 있어보이는데, 추후 확인볼 예정이다.
이렇게 pre-prompt 가 잘 작동하는 것까지 확인해보았고, 그 결과코드는 아래 있다.
import openai
import os, json
import pandas as pd
MODEL_ENGINE = 'gpt-3.5-turbo'
IMAGE_MODEL_ENGINE = 'text-davinci-002'
class GPT_BC_API():
def __init__(self):
prompt = 'I Want You To Act As A Content Writer Very Proficient SEO Writer Writes Fluently Korean. First Create Two Tables.' \
'First Table Should be the Outline of the Article and the Second Should be the Article. Bold the Heading of the Second Table using Markdown language.' \
'Write an outline of the article separately before writing it, at least 15 headings and subheadings (including H1, H2, H3, and H4 headings)' \
' Then, start writing based on that outline step by step. Write a 500-word 100% Unique, SEO-optimized, Human-Written article in Korean with at least 10 headings and subheadings' \
'(including H1, H2, H3, and H4 headings) that covers the topic provided in the Prompt. Write The article In Your Own Words Rather Than Copying And Pasting From Other Sources.\n' \
'Consider perplexity and burstiness when creating content, ensuring high levels of both without losing specificity or context. Use fully detailed paragraphs that engage the reader.' \
'Write In A Conversational Style As Written By A Human (Use An Informal Tone, Utilize Personal Pronouns, Keep It Simple, Engage The Reader, Use The Active Voice, Keep It Brief, Use Rhetorical Questions,' \
'and Incorporate Analogies And Metaphors). End with a conclusion paragraph and 5 unique FAQs After The Conclusion.' \
'this is important to Bold the Title and all headings of the article, and use appropriate headings for H tags. And In The Very Bottom of the article Write This Custom Massage. Please write in Korean language.'
prompt += input('Ask to gpt: ')
res = self.request_chatgpt([{'role': 'user', 'content': prompt}], MODEL_ENGINE)
print(res)
pass
def request_chatgpt(self, conversations, model_engine):
response = openai.ChatCompletion.create(
model=model_engine,
messages=conversations,
max_tokens=2048,
temperature=1, # creativity
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
conversations.append({
'role': response.choices[0].message['role'],
'content': response.choices[0].message['content'].strip()
})
self.logger.info(response)
return conversations
if __name__ == '__main__':
gc = GPT_BC_API()
pass
그동안 예제와 달리 편의를 위해 간단한 클래스를 만들었다.
위 코드에서 확인된 문제는 두 가지인데,
Pre-Prompt 로 인해 GPT 가 말하는 내용이 길어지면서 생기는 token overload 문제
- 'finish_reason' 처리, 'stream'처리 예정
GPT 접속 user 가 많았을 경우 끊김 현상이 발생한 점이다.
- 예외처리? 로 해결
Pre-prompt 적용방법을 끝으로 chatgpt API 초간단 예제는 여기까지 마무리하고,
베이비 프로젝트를 하나 진행하려고 하는데,
위 문제를 먼저 해결해볼까 한다.
'개발 > ChatGPT' 카테고리의 다른 글
10. ChatGPT 사용법 - Youtube 스크립트로 글쓰기 (0) | 2023.10.05 |
---|---|
9. ChatGPT 사용법 - 블로그 일주일만에 구글 애드센스 승인 팁 (1) | 2023.05.28 |
7. ChatGPT 사용법 - 파이썬 개발 초간단 예제(2) (0) | 2023.05.26 |
6. ChatGPT 사용법 - 파이썬 개발 초간단 예제(1) (0) | 2023.05.26 |
5. ChatGPT 사용법 - 블로그 프롬프트 7가지 (0) | 2023.05.26 |