OpenAI Cookbook 연구에 새로운 게시물이 있습니다.
이 문서는 ChatGPT에 관한 것입니다.
2023년 3월 1일에 처음 업로드 되었습니다.
오늘 우리는 이 기사를 공부할 것입니다.
GitHub – openai/openai-cookbook: OpenAI API 사용을 위한 샘플 및 가이드
OpenAI API 사용을 위한 샘플 및 가이드. GitHub에서 계정을 만들어 openai/openai-cookbook 개발에 기여하세요.
github.com
ChatGPT 모델의 입력 형식을 지정하는 방법
ChatGPT는 gpt-3.5-turbo를 기반으로 하며 OpenAI의 가장 진보된 모델입니다.
OpenAI API를 사용하여 gpt-3.5-turbo로 자체 애플리케이션을 만들 수 있습니다.
채팅 모델은 일련의 메시지를 입력으로 받아 AI가 작성한 메시지를 출력으로 반환합니다.
이 가이드는 몇 가지 예제 API 호출을 사용하여 채팅 형식을 보여줍니다.
1. openai 라이브러리 가져오기
# if needed, install and/or upgrade to the latest version of the OpenAI Python library
%pip install --upgrade openai
최신 버전의 OpenAI로 업그레이드하려면 pip install –upgrade 명령으로 업그레이드하십시오.
Windows 명령 프롬프트에서 업데이트했습니다.
2023년 3월 1일 OpenAI API에 ChatGPT API를 추가했습니다.
이 채팅 API 호출의 모델명은 gpt-3.5-turbo 입니다. 이 모델은 ChatGPT에서 사용하는 것과 동일합니다.
관련 지침 문서도 추가되었습니다.
https://platform.openai.com/docs/guides/chat
OpenAI API
OpenAI에서 개발한 새로운 AI 모델에 액세스하기 위한 API
platform.openai.com
이 API 사용 가격은 토큰 1,000개당 $0.002입니다.
다음으로 openai 모듈을 가져옵니다.
저 같은 경우 파일에서 Openai API 키를 읽어서 보내는 중이라 그 부분도 함께 포함시켰습니다.
2. 채팅 API 호출 예시
Chat API 호출에는 다음 두 가지 입력 값이 필요합니다.
- 모델: 사용하려는 모델의 이름(예: gpt-3.5-터보)
- 모델: 사용하려는 모델의 이름(예: gpt-3.5-turbo)
- 메시지: 메시지 개체 목록으로, 각 개체에는 최소한 두 개의 필드가 있습니다.
- 메시지: 메시지 개체 목록입니다. 각 개체에는 최소한 다음 두 필드가 있어야 합니다.
- 역할: 메신저의 역할(또는 체계, 사용자 또는 어시스턴트)
- 역할: 메신저의 역할(시스템, 사용자, 도우미 등…)
- 내용: 메시지 내용(예: 좋은 시를 써주세요)
- 내용: 메시지 내용(예: 좋은 시를 써주세요.)
대화는 일반적으로 시스템 메시지로 시작하고 사용자 및 도우미 메시지가 번갈아 가며 이어지지만 이 형식을 따를 필요는 없습니다.
ChatGPT에서 사용하는 채팅 API가 실제로 어떻게 작동하는지 알아보기 위해 채팅 API를 호출하는 예를 살펴보겠습니다.
이 ChatGPT에서 사용하는 ChatAPI를 호출하는 방법은 openai.ChatCompletion.create()를 호출하는 것입니다.
위 호출에 대한 응답 개체에는 여러 필드가 있습니다.
- 선택: 완료 개체 목록(지정하지 않는 한 하나만 N 1보다 큼)
- choice : 완성 객체 목록(n이 1보다 높게 설정되지 않는 한 하나만 존재함)
- 메시지: 모델이 생성한 메시지 객체 역할 그리고 내용물
- 메시지 : 모델이 생성한 메시지 객체(역할, 콘텐츠)
- finish_reason: 모델이 텍스트 생성을 중지한 이유(또는 멈추거나 길이 만약에 max_tokens 한도 도달)
- finish_reason: 모델이 텍스트 생성을 중지한 이유(정지 또는 max_tokens 초과 시 길이)
- index: 선택 목록의 완료 인덱스
- index: 선택 목록의 완료 인덱스
- 생성됨: 요청의 타임스탬프
- created : 요청의 요청 시간 정보
- id: 요청의 id
- 모델: 응답을 생성하는 데 사용되는 모델의 전체 이름
- 모델; 응답을 생성하는 데 사용되는 모델의 전체 이름
- 객체: 반환된 객체의 유형(예: 채팅 졸업 증서)
- object : 반환된 객체의 유형(예: chat.completion)
- 사용량: 응답을 생성하는 데 사용된 토큰 수, 프롬프트 수, 완료 및 합계
- Usage : 응답을 생성하는 데 사용되는 토큰 수입니다. 완료, 프롬프트, 총 토큰
위 요청에서 Messages의 첫 번째 요소 역할은 System입니다.
이것은 ChatGPT의 현재 상황을 설명하기 위한 것입니다.
ChatGPT로 향하는 매우 유용한 중재자입니다.
다음 사용자는 똑똑하고 노크합니다.
다음 헬퍼는 누구? 나는 묻는다.
그런 다음 사용자는 Orange라고 답합니다.
지금까지 ChatGPT가 제공한 상황입니다.
그런 다음 ChatGPT가 적절한 응답으로 응답할 차례이며, 다음에 올 수 있습니다.
ChatGPT의 응답 구조는 위에서 설명한 것과 같습니다.
여기에 대한 대답은 Orange who? 선택 – 메시지 – 내용 . 그건.
다른 모든 것은 해당 요청 및 응답에 대한 데이터입니다.
ChatGPT가 귀하의 상황에 적절하게 답변한 부분을 여기에서 얻으려면 다음과 같이 할 수 있습니다.
이렇게 하면 실제 ChatGPT 응답이 Orange who? 그 부분만 하시면 됩니다.
비대화 기반 작업도 사용자 메시지의 첫 번째 부분에 지침을 포함하여 채팅 형식에 따라 사용할 수 있습니다.
예를 들어 모델에게 검은 수염 해적 스타일로 비동기 프로그래밍을 설명하도록 요청하려면 대화가 다음과 같이 진행될 수 있습니다.
이를 통해 ChatGPT는 비동기 프로그래밍을 설명하고 검은 수염 해적처럼 소리를 내며 응답합니다.
악센트 느낌으로는 한국어로 번역하기 어려우니 대략 구글번역기로 하겠습니다.
안녕, 친구! 비동기 프로그래밍은 동시에 다른 일을 하는 해적 선원과 같습니다. 예, 다음 작업으로 이동하기 전에 하나의 작업이 완료될 때까지 기다리는 대신 동시에 여러 작업을 실행할 수 있습니다. 다른 사람들이 갑판을 청소하고 총을 장전하는 동안 내 승무원은 돛을 올리는 것과 같습니다. 각 작업은 독립적으로 작동하지만 모두 선박의 전반적인 성공에 기여합니다. 기름칠이 잘 된 해적선이 더 빠르고 원활하게 항해할 수 있는 것처럼 코드를 더 빠르고 효율적으로 실행할 수 있는 강력한 방법입니다. 아!
웃기다.
상황을 설명하는 시스템 메시지 없이 요청을 해보자.
이렇게 해도 ChatGPT가 올바르게 응답합니다.
3. gpt-3.5-turbo-0301 가이드 방법 팁
모델을 가르치는 가장 좋은 방법은 모델의 버전에 따라 다를 수 있습니다. 아래 예시는 gpt-3.5-turbo-0301 버전에 적용했을 때 가장 효과적인 가이드입니다. 이후 모델에는 적용되지 않을 수 있습니다.
시스템 메시지
시스템 메시지는 다른 성격이나 행동을 지정하여 조수를 더 잘 준비하는 데 사용할 수 있습니다.
그러나 모델은 일반적으로 시스템 메시지에 그다지 주의를 기울이지 않습니다. 따라서 사용자 메시지에 정말 중요한 부분을 배치하는 것이 좋습니다.
다음은 마법사에게 개념을 자세히 설명하도록 요청하는 시스템 메시지의 예입니다.
# An example of a system message that primes the assistant to explain concepts in great depth
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a friendly and helpful teaching assistant. You explain concepts in great depth using simple terms, and you give examples to help people learn. At the end of each explanation, you ask a question to check for understanding"},
{"role": "user", "content": "Can you explain how fractions work?"},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
다음은 마법사가 짧고 중요한 답변만 제공하도록 요청하는 시스템 메시지의 예입니다.
# An example of a system message that primes the assistant to give brief, to-the-point answers
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a laconic assistant. You reply with brief, to-the-point answers with no elaboration."},
{"role": "user", "content": "Can you explain how fractions work?"},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
시스템 메시지의 지시에 따라 응답이 어떻게 상세하거나 간결해질 수 있는지 확인했습니다.
몇 장의 샷에 대한 프롬프트
경우에 따라 모델에게 설명하는 것보다 원하는 것을 모델에게 보여주는 것이 더 쉽습니다.
원하는 모델을 보여주는 한 가지 방법은 샘플 가짜 메시지를 사용하는 것입니다.
다음은 비즈니스 전문 용어를 더 간단한 단어로 번역하도록 모델을 준비하는 가짜 로우 샷 대화를 삽입하는 예입니다.
# An example of a faked few-shot conversation to prime the model into translating business jargon to simpler speech
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a helpful, pattern-following assistant."},
{"role": "user", "content": "Help me translate the following corporate jargon into plain English."},
{"role": "assistant", "content": "Sure, I'd be happy to!"},
{"role": "user", "content": "New synergies will help drive top-line growth."},
{"role": "assistant", "content": "Things working well together will increase revenue."},
{"role": "user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
{"role": "assistant", "content": "Let's talk later when we're less busy about how to do better."},
{"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
제가 얻은 답은 위와 같습니다.
시스템 메시지의 필드 이름을 example_user 및 example_assistant로 변경하여 예제의 대화가 실제 대화가 아니며 다시 참조되어서는 안 된다는 점을 모델에 분명히 표시해 보겠습니다.
위의 몇 가지 샷으로 이 예를 다시 시작하겠습니다.
# The business jargon translation example, but with example names for the example messages
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
{"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
{"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
{"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
{"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
{"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
제가 얻은 답은 위와 같습니다.
엔지니어링 대화 상자의 모든 시도가 첫 번째 시도에서 성공하는 것은 아닙니다.
첫 번째 시도가 실패하면 다른 방식으로 프라이밍하거나 모델의 조건을 변경하여 다시 시도하는 것을 두려워하지 마십시오.
예를 들어 한 개발자는 “지금까지는 훌륭했습니다. 완벽함”을 선택하여 모델이 더 높은 품질의 답변을 제공하도록 합니다. 어떤 경우에는 다음과 같은 사용자 메시지를 추가하는 것을 발견했습니다.
모델의 신뢰도를 높이는 방법에 대한 자세한 내용은 다음을 참조하세요. 신뢰성을 높이는 기술 가이드를 확인하세요. 채팅 모델용으로 작성되지는 않았지만 기본 원칙은 동일하게 적용될 수 있습니다.
https://coronasdk.1277
Openai 요리책: 신뢰성을 향상시키기 위한 GPT-3 가이드 기술
오늘 우리가 탐구할 것은 답변의 신뢰성을 높이는 방법을 알아내는 것입니다. 실용성보다는 이론적인 것 같습니다. 조금 길지만 시작하겠습니다. 원본 페이지
coronasdk.tistory.com
4. 토큰 계산
요청을 보내면 API가 메시지를 일련의 토큰으로 변환합니다.
여기에 있는 토큰의 수는 다음과 같은 것에 영향을 미칩니다.
- 요청 비용
- 요청 시 청구
- 응답을 생성하는 데 걸리는 시간
- 응답을 생성하는 데 걸리는 시간
- 응답이 최대 토큰 한도(예: 4096)에 도달하여 잘린 경우 gpt-3.5-터보)
- 최대 토큰 수(gpt-3.5-turbo의 경우 4096개)에 도달하면 나머지 요청이 잘립니다.
2023년 3월 1일부터 메시지 목록에서 사용할 토큰 수는 다음 함수를 사용하여 미리 계산할 수 있습니다.
import tiktoken
def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
"""Returns the number of tokens used by a list of messages."""
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
encoding = tiktoken.get_encoding("cl100k_base")
if model == "gpt-3.5-turbo-0301": # note: future models may deviate from this
num_tokens = 0
for message in messages:
num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
for key, value in message.items():
num_tokens += len(encoding.encode(value))
if key == "name": # if there's a name, the role is omitted
num_tokens += -1 # role is always required and always 1 token
num_tokens += 2 # every reply is primed with <im_start>assistant
return num_tokens
else:
raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")
틱토큰을 가져옵니다.
num_tokens_from_messages() 함수를 만듭니다.
이 함수의 입력 값은 메시지와 모델명입니다.
인코딩은 tiktokens encoding_for_model()을 사용하여 결정됩니다.
여기서 오류가 발생하면 cl100k_base를 사용하십시오. (임베딩에 사용되는 인코딩입니다.)
if 문에서 모델이 gpt-3.5-turbo-0301이면 그 안에 있는 콘텐츠가 실행됩니다.
포함된 for 문은 메시지 목록에 있는 항목 수만큼 반복됩니다.
각 메시지에 4를 추가합니다.
그리고 각 메시지에 대한 토큰 값은 다음 for 문에서 len(encoding.encode(value)를 사용하여 계산됩니다.
키가 name 인 경우 역할이 한 번에 1개의 토큰만 사용하므로 이 부분은 생략됩니다.
그리고 각 답변에 대해 2를 추가합니다.
계산된 값을 반환합니다.
그런 다음 아래 뉴스를 게시하십시오.
messages = (
{"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
{"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
{"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
{"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
{"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
{"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
)
그런 다음 해당 메시지를 매개변수로 num_tokens_from_messages() 함수를 호출하고 토큰 값을 수신하여 반환합니다.
# example token count from the function defined above
print(f"{num_tokens_from_messages(messages)} prompt tokens counted.")
그런 다음 126개의 토큰이 사용되었다고 합니다.
참고로 이 글에서 만든 파이썬 소스 코드는 다음과 같다.
# import the OpenAI Python library for calling the OpenAI API
import openai
def open_file(filepath):
with open(filepath, 'r', encoding='utf-8') as infile:
return infile.read()
openai.api_key = open_file('openaiapikey.txt')
# Example OpenAI Python library request
MODEL = "gpt-3.5-turbo"
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Knock knock."},
{"role": "assistant", "content": "Who's there?"},
{"role": "user", "content": "Orange."},
),
temperature=0,
)
response
response('choices')(0)('message')('content')
# example with a system message
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain asynchronous programming in the style of the pirate Blackbeard."},
),
temperature=0,
)
print(response('choices')(0)('message')('content'))
# example without a system message
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "user", "content": "Explain asynchronous programming in the style of the pirate Blackbeard."},
),
temperature=0,
)
print(response('choices')(0)('message')('content'))
# An example of a system message that primes the assistant to explain concepts in great depth
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a friendly and helpful teaching assistant. You explain concepts in great depth using simple terms, and you give examples to help people learn. At the end of each explanation, you ask a question to check for understanding"},
{"role": "user", "content": "Can you explain how fractions work?"},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
# An example of a system message that primes the assistant to give brief, to-the-point answers
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a laconic assistant. You reply with brief, to-the-point answers with no elaboration."},
{"role": "user", "content": "Can you explain how fractions work?"},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
# An example of a faked few-shot conversation to prime the model into translating business jargon to simpler speech
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a helpful, pattern-following assistant."},
{"role": "user", "content": "Help me translate the following corporate jargon into plain English."},
{"role": "assistant", "content": "Sure, I'd be happy to!"},
{"role": "user", "content": "New synergies will help drive top-line growth."},
{"role": "assistant", "content": "Things working well together will increase revenue."},
{"role": "user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
{"role": "assistant", "content": "Let's talk later when we're less busy about how to do better."},
{"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
# The business jargon translation example, but with example names for the example messages
response = openai.ChatCompletion.create(
model=MODEL,
messages=(
{"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
{"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
{"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
{"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
{"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
{"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
),
temperature=0,
)
print(response("choices")(0)("message")("content"))
import tiktoken
def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
"""Returns the number of tokens used by a list of messages."""
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
encoding = tiktoken.get_encoding("cl100k_base")
if model == "gpt-3.5-turbo-0301": # note: future models may deviate from this
num_tokens = 0
for message in messages:
num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
for key, value in message.items():
num_tokens += len(encoding.encode(value))
if key == "name": # if there's a name, the role is omitted
num_tokens += -1 # role is always required and always 1 token
num_tokens += 2 # every reply is primed with <im_start>assistant
return num_tokens
else:
raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")
messages = (
{"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
{"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
{"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
{"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
{"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
{"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
)
# example token count from the function defined above
print(f"{num_tokens_from_messages(messages)} prompt tokens counted.")