반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

OpenAI Update - Silicon Valley Bank (SVB)

2023. 3. 16. 22:44 | Posted by 솔웅


반응형

어제 (3/15/2023) OpenAI 에서 이메일이 하나 왔습니다.

이번에 문제가 되고 있는 Silicon Valley Bank (SVB) 파산과 관련 OpenAI는 영향을 받지 않았다는 메일 입니다.

이와 관련해서 OpenAI에서 요청하는 것처럼 속이고 사용 요금 등을 청구하는 사기에 조심하라는 내용 입니다.

Dear customer,

We want to inform you that OpenAI has not been impacted by the evolving situation at Silicon Valley Bank. 

 

OpenAI는 Silicon Valley Bank의 진화하는 상황에 영향을 받지 않았음을 알려드립니다.

 

In light of this fact we wanted to remind our customers to be vigilant of any requests for payment that appear suspicious or unusual; 

 

이 사건에 비추어 우리는 고객님들께 의심스럽거나 비정상적으로 보이는 요금 지불 요청에 대해 경계해 주실것을 상기시켜 드리고자 이 이메일을 드립니다.

 

official communications about payments will originate from AR@openai.com or our payment processor, Stripe, and we encourage customers to reach out to us at any time with questions or to verify payment instructions.

 

요금과 관련된 공식적인 커뮤니케이션은 AR@openai.com 이메일 이나 저희 시스템 상의 payment processor 인 Stripe 에서만 진행 됩니다.  고객님들께서 요금 지불 요청에 대해 검증을 원하시거나 어떠한 질문이 있으시면 저희에게 언제든지 연락 해 주세요.

We acknowledge the stress many are facing and extend our empathy and assistance.

 

우리는 많은 분들이 직면하고 있는 이 스트레스적인 상황을 인지하고 그 어려움에 대해 공감하며 가능한 지원을 확대해 나갈 것 입니다.

Best,
OpenAI

 

반응형

Open AI 의 GPT-4 Over view page

2023. 3. 15. 23:56 | Posted by 솔웅


반응형

어제 받았던 GPT-4 발표 이메일에 있는 GPT-4 Overview 페이지를 살펴 봤습니다.

 

https://openai.com/product/gpt-4

 

GPT-4

GPT-4 is more creative and collaborative than ever before. It can generate, edit, and iterate with users on creative and technical writing tasks, such as composing songs, writing screenplays, or learning a user’s writing style.

openai.com

 

제목에서는 GPT-4 가 Open AI의 가장 진보된 시스템이고 더 안전하고 유용한 답변을 한다고 돼 있습니다.

이 GPT-4 API를 사용하려면 API waitlist에 등록 해야 합니다.

 

 

GPT-4는 폭넓은 일반 지식과 문제 해결 능력 덕분에 어려운 문제를 더 정확하게 풀 수 있습니다.

라고 말을 하고 있고 그 아래 GPT-4에서 개선 된 부분들에 대해 나옵니다.

우선 Creativity와 Visual input 그리고 Longer context 이렇게 3개의 탭이 있습니다.

 

Creativity 부터 볼까요?

 

GPT4 is more creative and collaborative than ever before. It can generate, edit, and iterate with users on creative and technical writing tasks, such as composing songs, writing screenplays, or learning a user’s writing style.

 

GPT-4는 그 어느 때보다 창의적이고 협력적입니다. 노래 작곡, 시나리오 작성 또는 사용자의 작문 스타일 학습과 같은 창의적이고 기술적인 작문 작업에서 사용자와 함께 생성, 편집 및 반복할 수 있습니다.

 

Input
Explain the plot of Cinderella in a sentence where each word has to begin with the next letter in the alphabet from A to Z, without repeating any letters.

 

Output
A beautiful Cinderella, dwelling eagerly, finally gains happiness; inspiring jealous kin, love magically nurtures opulent prince; quietly rescues, slipper triumphs, uniting very wondrously, xenial youth zealously.

 

input으로 아래와 같은 요구를 했습니다.

문자를 반복하지 않고 A부터 Z까지 알파벳의 다음 문자로 각 단어가 시작되어야 하는 문장으로 신데렐라의 줄거리를 설명합니다.

 

그랬더니 신데렐라의 줄거리를 진짜 A 부터 Z까지 시작하는 단어들을 차례대로 사용해서 설명을 했습니다.

 

두번째는 Visual input 분야 입니다.

 

이미지 파일을 주고 이 재료들을 가지고 무엇을 만들 수 있냐고 물었더니...

 

이런 답변을 했네요. 그림만 보고 그 안에 있는 재료들을 판단해서 거기에 맞는 가능한 요리들을 보여 줬습니다.

 

그 다음은 아주 긴 input 값을 받을 수 있다는 내용입니다.

 

GPT-4 is capable of handling over 25,000 words of text, allowing for use cases like long form content creation, extended conversations, and document search and analysis.

 

GPT-4는 25,000단어 이상의 텍스트를 처리할 수 있어 긴 형식의 콘텐츠 생성, 확장된 대화, 문서 검색 및 분석과 같은 사용 사례를 허용합니다.

 

예제로는 리하나의 위키피디아의 내용을 입력값으로 주고 이번 Super Bowl 공연에 대해 물어보고 GPT-4 가 대답하는 내용이 있습니다.

 

그 다음에는  GPT-4 는 작년 말에 발표 되서 센세이션을 일으켰던 ChatGPT 보다 더 성능이 좋다는 내용이 있습니다.

 

ChatGPT가 제대로 답을 못한 것을 CPT-4 는 대답한 예 입니다.

이건 ChatGPT가 오답을 냈던게 문제 아니었을까요? 하여간 GPT-4는 정답을 얘기 했네요.

 

Uniform Bar Exam 과 Biology Olympiad 라는 테스트 경진 대회에서 GPT-4 가 ChatGPT 보다 더 높은 점수를 기록했다는 내용 입니다.

참고로 ChatGPT는 GPT-3.5 버전입니다.

 

밑의 설명은 GPT가 버전 2, 3, 3.5, 4 이렇게 진행돼 오면서 점점 더 정교하고 유능한 모델이 되어 가고 있다는 내용입니다.

 

We spent 6 months making GPT-4 safer and more aligned. GPT4 is 82% less likely to respond to requests for disallowed content and 40% more likely to produce factual responses than GPT-3.5 on our internal evaluations.

 

우리는 6개월 동안 GPT-4를 더 안전하고 더 잘 정렬되도록 만들었습니다. GPT-4는 허용되지 않는 콘텐츠에 대한 요청에 응답할 가능성이 82% 적고 내부 평가에서 GPT-3.5보다 사실에 입각한 응답을 할 가능성이 40% 더 높습니다.

 

Safety & alignment

 

Training with human feedback
We incorporated more human feedback, including feedback submitted by ChatGPT users, to improve GPT-4’s behavior. We also worked with over 50 experts for early feedback in domains including AI safety and security.

 

GPT-4의 동작을 개선하기 위해 ChatGPT 사용자가 제출한 피드백을 포함하여 더 많은 사람의 피드백을 통합했습니다. 또한 AI 안전 및 보안을 포함한 도메인의 초기 피드백을 위해 50명 이상의 전문가와 협력했습니다.

Continuous improvement from real-world use
We’ve applied lessons from real-world use of our previous models into GPT-4’s safety research and monitoring system. Like ChatGPT, we’ll be updating and improving GPT-4 at a regular cadence as more people use it.

 

우리는 이전 모델의 실제 사용에서 얻은 교훈을 GPT-4의 안전 연구 및 모니터링 시스템에 적용했습니다. ChatGPT와 마찬가지로 더 많은 사람들이 사용함에 따라 정기적으로 GPT-4를 업데이트하고 개선할 것입니다.

GPT-4-assisted safety research
GPT-4’s advanced reasoning and instruction-following capabilities expedited our safety work. We used GPT-4 to help create training data for model fine-tuning and iterate on classifiers across training, evaluations, and monitoring.

 

GPT-4의 고급 추론 및 지시에 따른 기능은 우리의 안전 작업을 가속화했습니다. GPT-4를 사용하여 모델 미세 조정을 위한 훈련 데이터를 생성하고 훈련, 평가 및 모니터링 전반에 걸쳐 분류기를 반복했습니다.

 

그 다음 아래 부터는 실제 이 GPT-4를 사용해서 제품을 생산 판매 하고 있는 회사와 그 제품을 나열 했습니다.

나머지 회사와 제품들은 직접 한번 보세요.

 

이 중에서 Speak 라는 업체는 한국 업체인 것으로 알고 있습니다.

 

다음 단락에서는 GPT-4 에 대한 몇가지 추가적인 정보를 주고 있습니다.

 

Research

 

GPT-4는 OpenAI의 딥 러닝 확장 노력의 최신 이정표입니다.

https://openai.com/research/gpt-4

 

GPT-4

We’ve created GPT-4, the latest milestone in OpenAI’s effort in scaling up deep learning. GPT-4 is a large multimodal model (accepting image and text inputs, emitting text outputs) that, while less capable than humans in many real-world scenarios, exhi

openai.com

 

위 페이지에서는 GPT-4 관련 한 방대한 Research 내용을 보실 수 있습니다.

 

 

Infrastructure

GPT-4는 Microsoft Azure AI 슈퍼컴퓨터에서 교육을 받았습니다. Azure의 AI 최적화 인프라를 통해 전 세계 사용자에게 GPT-4를 제공할 수도 있습니다.

 

Limitations

GPT-4에는 사회적 편견, 환각, 적대적 프롬프트와 같이 우리가 해결하기 위해 노력하고 있는 많은 알려진 한계가 있습니다. 우리는 사회가 이러한 모델을 채택함에 따라 투명성, 사용자 교육 및 광범위한 AI 활용 능력을 장려하고 촉진합니다. 우리는 또한 우리 모델을 형성하는 데 사람들이 입력할 수 있는 방법을 확장하는 것을 목표로 합니다.

 

Availability

GPT-4는 ChatGPT Plus에서 사용할 수 있으며 개발자가 애플리케이션 및 서비스를 구축하기 위한 API로 사용할 수 있습니다.

 

https://openai.com/contributions/gpt-4

 

GPT-4 contributions

Core contributorsTrevor Cai Execution leadMark Chen Vision team co-lead, Deployment leadCasey Chu Initial prototype leadChris Hesse Data load balancing & developer tooling leadShengli Hu Vision Safety Evaluations leadYongjik Kim GPU performance

openai.com

https://chat.openai.com/

 

 

https://openai.com/waitlist/gpt-4-api

 

GPT-4 API waitlist

We’re making GPT-4 available as an API for developers to build applications and services.

openai.com

 

저는 이메일 받자마자 GPT-4 API waitlist에 등록 했습니다.

 

지금 GPT-3 API 의 Cookbook을 공부하고 있는데 그 와중에 3월 1일에 GPT 3.5 (ChatGPT) API 가 공개 됐고 이제 3월 14일에 GPT-4 API 가 공개 됐네요.

 

따라가면서 공부하기에도 벅차게 발전하고 있습니다.

 

하여간 계속 공부해 보겠습니다.

반응형


반응형

요즘은 Cook Book의 Fine-tuning을 공부하고 있는데요.

어제 OpenAI에서 GPT-4가 나와서 업데이트 이메일이 왔습니다.

 

 

간단하게 살펴 보겠습니다.

 

우선 live demo link는 아래와 같습니다.

 

https://www.youtube.com/live/outcGtbnMuQ?feature=share 

여기서는 GPT-4에 대해 설명하는데 모든 단어를 G로 시작하는 단어를 사용해서 설명해 봐.. 뭐 이런 작업도 보여 주고 시를 쓰는 장면도 보여 주고 하더라구요. GPT-3 에서는 하지 못했던 좀 더 성장한 GPT 기능을 보여 줬구요.

뭐니뭐니해서 GPT-4에서 가장 달라진 점은 Language 이외의 멀티미디어 기능 지원등이 있었습니다.

GPT-4 가 이미지를 인식해서 그 이미지에 대한 설명도 하고 작업도 하고 그러더라구요.

자세한 사항은 위 유투브 클립을 한번 보세요.

 

이메일 내용은 아래와 같았습니다.

 

We’ve created GPT-4, our most capable model. We are starting to roll it out to API users today.
Please join us today, March 14th, at 1 pm PDT for a live demo of GPT-4.
우리는 GPT-4를 만들었습니다. 가장 유능한 모델이죠. 우리는 오늘부터 API 사용자들에게 이 모델을 배포하기 시작했습니다.
 
About GPT-4
GPT-4 can solve difficult problems with greater accuracy, thanks to its broader general knowledge and advanced reasoning capabilities.
GPT-4는 광범위한 일반 지식과 고급 추론 기능 덕분에 어려운 문제를 더 정확하게 풀 수 있습니다.

 

 

You can learn more through: 아래 글들을 통해서 이를 배울 수 있습니다.

  • Overview page of GPT-4 and what early customers have built on top of the model.
  • GPT-4의 개요 페이지 - 초기 고객이 모델 위에 구축한 것.
  • Blog post with details on the model’s capabilities and limitations, including eval results.
  • 평가 결과를 포함하여 모델의 기능 및 제한 사항에 대한 세부 정보가 포함된 블로그 게시물

 

Availability

  • API Waitlist: Please sign up for our waitlist to get rate-limited access to the GPT-4 API – which uses the same ChatCompletions API as gpt-3.5-turbo. We’ll start inviting some developers today, and scale up availability and rate limits gradually to balance capacity with demand.
  • API 대기자 명단: gpt-3.5-turbo와 동일한 ChatCompletions API를 사용하는 GPT-4 API에 대한 rate-limited 액세스 권한을 얻으려면 대기자 명단에 등록하십시오. 오늘 일부 개발자를 초대하고 용량과 수요의 균형을 맞추기 위해 가용성 및 rate-limited을 점진적으로 확장할 것입니다.
  • Priority Access: Developers can get prioritized API access to GPT-4 for contributing model evaluations to OpenAI Evals that get merged, which will help us improve the model for everyone.
  • Priority Access: 개발자는 병합되는 OpenAI 평가에 대한 모델 평가에 기여하기 위해 GPT-4에 대한 prioritized  API 액세스를 얻을 수 있으며, 이는 모든 사람을 위해 모델을 개선하는 데 도움이 됩니다.
  • ChatGPT Plus: ChatGPT Plus subscribers will get GPT-4 access on chat.openai.com with a dynamically adjusted usage cap. We expect to be severely capacity constrained, so the usage cap will depend on demand and system performance. API access will still be through the waitlist.
  • ChatGPT Plus: ChatGPT Plus 가입자는 chat.openai.com에서 동적으로 조정된 사용 한도와 함께 GPT-4 액세스 권한을 얻습니다. 용량이 심각하게 제한될 것으로 예상되므로 사용량 한도는 수요와 시스템 성능에 따라 달라집니다. API 액세스는 여전히 대기자 명단을 통해 이루어집니다.

 

API Pricing

gpt-4 with an 8K context window (about 13 pages of text) will cost $0.03 per 1K prompt tokens, and $0.06 per 1K completion tokens.
 
8K 컨텍스트 창(약 13페이지의 텍스트)이 있는 gpt-4는 1K 프롬프트 토큰당 $0.03, completion  토큰 1K당 $0.06입니다.

gpt-4-32k with a 32K context window (about 52 pages of text) will cost $0.06 per 1K prompt tokens, and $0.12 per 1K completion tokens.
 
32K 컨텍스트 창(약 52페이지의 텍스트)이 있는 gpt-4-32k는 프롬프트 토큰 1,000개당 $0.06, completion  토큰 1,000개당 $0.12입니다.

 

Livestream
Please join us for a live demo of GPT-4 at 1pm PDT today, where Greg Brockman (co-founder & President of OpenAI) will showcase GPT-4’s capabilities and the future of building with the OpenAI API.
오늘 오후 1시(PDT) GPT-4 라이브 데모에 참여하세요. Greg Brockman(OpenAI 공동 창립자 겸 사장)이 GPT-4의 기능과 OpenAI API로 구축하는 미래를 선보일 예정입니다.
 

—The OpenAI team

반응형


반응형

오늘은 오랜만에 실습 예제 입니다.

 

Fine-tunning을 실제로 해 보도록 하겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

Fine tuning classification example

아래 예제는 ada 모델을 이용해서 이메일 내용을 보고 이게 Baseball과 연관 돼 있는지 아니면 Hockey와 연관 돼 있는 건지 GPT-3 가 인지할 수 있도록 Fine-Tuning을 사용해서 훈련시키고 새로운 모델을 만드는 과정을 보여 줍니다.

 

from sklearn.datasets import fetch_20newsgroups
import pandas as pd
import openai

categories = ['rec.sport.baseball', 'rec.sport.hockey']
sports_dataset = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, categories=categories)

 

이 예제에서 사용하는 데이터는 sklearn에서 제공하는 샘플 데이터인 fetch_20newsgroups를 사용합니다.

 

fetch_20newsgroups 는 데이터를 다루는 연습용으로 만들어진 데이터 세트 입니다.

20개의 newsgroup에서 데이터를 가져온 겁니다. 이 뉴스그룹들은 대부분 게시판이고 사용자들이 올른 글들이 데이터가 되는 겁니다. 예를 들어 내가 낚시에 관심이 있어서 낚시 관련된 카페 같은 뉴스 그룹에 가입하고 거기에 글을 올리듯이 사람들이 글을 올린 데이터 들 입니다.

 

여기에는 20개의 주제들이 있습니다. 그리고 총 샘플들은 18846개가 있고 1차원 배열이고 text로 이뤄져 있습니다.

 

이 중에서 Baseball 과 Hockey 관련된 데이터를 가지고 이 예제에서는 Fine-Tuning을 연습하는 소스코드를 만들게 됩니다.

 

https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_20newsgroups.html

 

sklearn.datasets.fetch_20newsgroups

Examples using sklearn.datasets.fetch_20newsgroups: Biclustering documents with the Spectral Co-clustering algorithm Biclustering documents with the Spectral Co-clustering algorithm Topic extractio...

scikit-learn.org

참고로 이 데이터세트에는 아래와 같은 주제들의 글들이 있습니다.

 

'alt.atheism',
 'comp.graphics',
 'comp.os.ms-windows.misc',
 'comp.sys.ibm.pc.hardware',
 'comp.sys.mac.hardware',
 'comp.windows.x',
 'misc.forsale',
 'rec.autos',
 'rec.motorcycles',
 'rec.sport.baseball',
 'rec.sport.hockey',
 'sci.crypt',
 'sci.electronics',
 'sci.med',
 'sci.space',
 'soc.religion.christian',
 'talk.politics.guns',
 'talk.politics.mideast',
 'talk.politics.misc',
 'talk.religion.misc'

https://scikit-learn.org/stable/datasets/real_world.html#newsgroups-dataset

 

7.2. Real world datasets

scikit-learn provides tools to load larger datasets, downloading them if necessary. They can be loaded using the following functions: The Olivetti faces dataset: This dataset contains a set of face...

scikit-learn.org

 

그리고 Pandas와 openai 모듈을 import 합니다.

 

관련 모듈을 import 한 다음에 한 일은 이 예제에서 다룰 topic들을 선택하는 겁니다. 이 두 topic들을 categories라는 배열 변수에 아이템으로 넣습니다.

그리고 sports_dataset 라는 변수에 이 fetch_20newsgroups에 있는 데이터 들 중 위에서 선택한 rec.sport.baseball과 rec.sport.hockey 뉴스그룹에 있는 데이터들만 담습니다.

 

데이터를 다루려면 우선 그 데이터으 구조를 잘 알아야 합니다.

 

이 데이터의 첫번째 데이터만 한번 출력해 보겠습니다.

print(sports_dataset['data'][0])

그러면 결과는 이렇게 나옵니다.

From: dougb@comm.mot.com (Doug Bank)
Subject: Re: Info needed for Cleveland tickets
Reply-To: dougb@ecs.comm.mot.com
Organization: Motorola Land Mobile Products Sector
Distribution: usa
Nntp-Posting-Host: 145.1.146.35
Lines: 17

In article <1993Apr1.234031.4950@leland.Stanford.EDU>, bohnert@leland.Stanford.EDU (matthew bohnert) writes:

|> I'm going to be in Cleveland Thursday, April 15 to Sunday, April 18.
|> Does anybody know if the Tribe will be in town on those dates, and
|> if so, who're they playing and if tickets are available?

The tribe will be in town from April 16 to the 19th.
There are ALWAYS tickets available! (Though they are playing Toronto,
and many Toronto fans make the trip to Cleveland as it is easier to
get tickets in Cleveland than in Toronto.  Either way, I seriously
doubt they will sell out until the end of the season.)

-- 
Doug Bank                       Private Systems Division
dougb@ecs.comm.mot.com          Motorola Communications Sector
dougb@nwu.edu                   Schaumburg, Illinois
dougb@casbah.acns.nwu.edu       708-576-8207

데이터는 글을 올린사람, 주제, Reply-To,, Organization, Distribution, 아이피 주소. 라인 수, 내용 등등등 ...

대충 어떤 식으로 데이터들이 구성 돼 있는지 알 수 있을 것 같습니다.

 

이건 sports_dataset 의 data라는 아이템에 들어 있는 첫 번째 데이터인 것이고 이 sports_dataset은 어떤 구조로 돼 있는지 한번 알아 볼까요?

 

#print(sports_dataset['data'][0])
print(sports_dataset)

결과의 일 부분인데요. sports_dataset 배열은 첫번째 item 이 data 입니다. 그리고 이 data 안에는 여러 글들이 있습니다. 각 글들은 From: 으로 시작합니다. 첫번째 글은 바로 위에서 출력한 그 글입니다. dougb@comm.mot.com으로 시작해서 708-576-8207 로 끝납니다.

data는 이렇게 구성이 돼 있고 그렇다면 다른 아이템에는 무엇이 있을 까요?

 

그 다음에는 target_names인데 이 변수에는 baseball과 hockey 토픽만 들어 있다는걸 확인 할 수 있습니다.

그리고 'target' : array(0,1,0...,... 이렇게 돼 있는 것은 data의 첫번째 데이터는 baseball 뉴스그룹에서 온 것이고 두번째 데이터는 hockey 그룹에서 그리고 세번째는 baseball 그룹에서 온 것이라는 것을 말합니다.

data에 있는 데이터 가지고는 이것이 어느 뉴스그룹 소속인지 알 수 없는데 이 target_names 라는 두번째 아이템에서 그 정보를 얻을 수 있네요.

 

오늘 다룰 Fine-Tunning 예제에서는 이 두가지 정보만 있으면 GPT-3 AI 를 훈련 시킬 수 있습니다.

 

참고로 target_names의 아이템만 알 수 있는 방법은 아래와 같습니다.

 

sports_dataset.target_names[sports_dataset['target'][0]]

그러면 결과 값은 아래와 같습니다.

'rec.sport.baseball'

 

그러면 전체 데이터와 각 주제별 데이터 갯수를 한번 알아 보겠습니다.

 

len_all, len_baseball, len_hockey = len(sports_dataset.data), len([e for e in sports_dataset.target if e == 0]), len([e for e in sports_dataset.target if e == 1])
print(f"Total examples: {len_all}, Baseball examples: {len_baseball}, Hockey examples: {len_hockey}")

len(sports_dataset.data) 는 이 sports_dataset에 있는 data 아이템에 있는 데이터 수를 가져 옵니다.

len([e for e in sports_dataset.target if e == 0] 는 data에 있는 데이터 중 target 이 0인 데이터 즉 rec.sport.baseball에 속한 데이터만 가져 옵니다. 

같은 방법으로 Hockey 에 속한 데이터만 가져 오려면 이러헥 사용 합니다. len([e for e in sports_dataset.target if e == 1]

결과는 아래와 같습니다.

Total examples: 1197, Baseball examples: 597, Hockey examples: 600

전체 데이터 갯수는 1197개이고 야구와 관련된 글은 597개 그리고 하키와 관련된 글은 600개 입니다.

 

이제 이 데이터의 구조에 대해서 어느정도 파악을 했습니다.

 

그러면 이 데이터를 Fune-Tuning 시키기 위한 구조로 바꾸어 주어야 합니다.

Fine-Tunning은 AI를 교육 시키는 겁니다. 이 AI를 교육시키기 위해서는 데이터를 제공해야 합니다.

GPT-3라는 AI가 알아 들을 수 있는 데이터 구조는 이전 Guide에서 설명 된 부분이 있습니다.

 

GPT-3는 Prompt 와 Completion 이 두 부분으로 나뉘어진 데이터세트를 제공하면 됩니다.

그러면 이 아이는 그것을 보고 패턴을 찾아내서 학습하게 되는 겁니다.

이런 내용의 글은 야구와 관련 돼 있고 또 저런 내용의 글은 하키와 관련 돼 있다는 것을 알아 내는 것이죠.

 

예를 들어 위에서 출력한 첫번째 글을 보시죠.

 

여기에는 이 글이 야구와 관련돼 있는지 하키와 관련 돼 있는지에 대한 명시적인 정보는 없습니다.

다면 이 글에는 Cleveland에 갈거고 팬들끼리 좀 모이자는 내용이 있습니다. 그리고 상대팀 이름도 있고 어디서 경기가 열리는지 뭐 이런 정보가 있습니다.

미국에서 야구에 대해 관심 있는 사람이라면 이 글은 야구와 관련된 글이라는 것을 알겠죠.

이렇게 주어진 정보만 가지고 이게 야구와 관련된 글인지 하키와 관련된 글인지 알아 내도록 GPT-3를 훈련 시킬 겁니다.

그 훈련된 AI모델은 나만의 모델이 될 겁니다.

그래서 앞으로 내가 어떤 글을 그 모델에게 보내면 그 Custom AI Model은 그게 야구와 관련된 글인지 하키와 관련된 글인지를 저에게 알려 줄 것입니다.

 

Fine Tuning과 관련 한 기초적인 내용을 아시려면 아래 블로그 글을 참조하세요.

 

https://coronasdk.tistory.com/1221

 

Guides - Fine tuning

https://beta.openai.com/docs/guides/fine-tuning OpenAI API An API for accessing new AI models developed by OpenAI beta.openai.com Fine-tuning Learn how to customize a model for your application. 당신의 어플리케이션을 위해 어떻게 모델을

coronasdk.tistory.com

 

그러면 GPT-3를 훈련 시키기 위한 데이터 세트 형식으로 위 데이터를 변경 시켜 보겠습니다.

Prompt 와 Completion 이 두가지 컬럼이 있어야 합니다.

Prompt에는 data 정보들이 있고 Completion에는 그 글이 야구와 관련된 글인지 하키와 관련된 글인지에 대한 정보들이 들거 갈 겁니다.

 

import pandas as pd

labels = [sports_dataset.target_names[x].split('.')[-1] for x in sports_dataset['target']]
texts = [text.strip() for text in sports_dataset['data']]
df = pd.DataFrame(zip(texts, labels), columns = ['prompt','completion']) #[:300]
df.head()

파이썬에서 데이터를 다루는 모델은 pandas를 많이 사용 합니다.

 

labels 부분을 보겠습니다.

위에서 sports_dataset['target'] 에는 0 과 1이라는 정보들이 있고 이 정보는 data에 있는 정보가 targetnames 의 첫번째 인수에 속하는 건지 두번째 인수에 속하는 건지를 알려 주는 것이라고 했습니다.

첫번째 인수는 rec.sport.baseball이고 두번째 인수는 rec.sport.hockey 입니다.

 

이 target 값에 대한 for 문이 도는데요 data 갯수가 1197이고 target의 각 인수들 (0,1) 은 각 데이터의 인수들과 매핑 돼 있으니까 이 for 문은 1197번 돌 겁니다. 이렇게 돌면서 target_names에서 해당 인수를 가져 와서 . 으로 그 텍스트를 분리 한 다음에 -1 번째 즉 맨 마지막 글자를 가지고 오게 됩니다. 그러면 baseball과 hockey라는 글자만 선택 되게 되죠.

즉 labels에는 baseball 과 hockey라는 글자들이 들어가게 되는데 이는 target 에 0이 있으면 baseball 1이 있으면 hockey가 들어가는 1197개의 인수를 가지고 있는 배열이 순서대로 들어가게 되는 겁니다.

 

그러면 이제 data에 있는 각 데이터를 순서대로 배열로 집어 넣으면 되겠죠?

texts = [text.strip() for text in sports_dataset['data']]

이 부분이 그 일을 합니다.

sports_dataset 에 있는 data 만큼 for 문을 돕니다. data는 1197개의 인수를 가지고 있으니 이 for 문도 1197번 돌 겁니다.

이 데이터를 그냥 texts 라는 변수에 배열 형태로 집어 넣는 겁니다. text.strip()은 해당 text의 앞 뒤에 있는 공백들을 제거 하는 겁니다.

이 부분도 중요 합니다. 데이터의 앞 뒤 공백을 제거해서 깨끗한 데이터를 만듭니다.

 

이제 data의 각 글을 가지고 있는 배열과 각 글들이 어느 주제에 속하는지에 대한 정보를 가지고 있는 배열들이 완성 됐습니다.

이 정보를 가지고 pandas로 GPT-3 AI 를 훈련 시킬 수 있는 형태의 데이터 세트로 만들겠습니다.

 

파이썬에서 zip() 함수는 두 배열을 튜플 형식으로 짝 지어 주는 함수 입니다. 

https://www.w3schools.com/python/ref_func_zip.asp

 

Python zip() Function

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

아래와 같이 두 배열의 인수들을 짝 지어 줍니다.

zip(texts, labels) <- 이렇게 하면 데이터와 topic이 짝 지어 지겠죠.

이 값은 pandas의 DataFrame의 첫번째 인수로 전달 되고 두번째 인수로는 컬럼 이름이 전달 됩니다. (columns = ['prompt','completion'])

 

그 다음 df.head() 로 이렇게 만들어진 DataFrame에서 처음에 오는 5개의 데이터를 출력해 봅니다.

 

의도한 대로 각 게시글과 그 게시글이 baseball에 속한 것인지 hockey에 속한 것인지에 대한 정보가 있네요.

 

이 cookbook에는 300개의 데이터만 사용할 것이라고 돼 있는데 어디에서 그게 돼 있는지 모르겠네요.

len() 을 찍어봐도 1197 개가 찍힙니다.

cookbook 설명대로 300개의 데이터만 사용하려면 아래와 같이 해야 할 것 같습니다.

 

import pandas as pd

labels = [sports_dataset.target_names[x].split('.')[-1] for x in sports_dataset['target']]
texts = [text.strip() for text in sports_dataset['data']]
df = pd.DataFrame(zip(texts, labels), columns = ['prompt','completion']) #[:300]
df = df.head(300)
print(df)

저는 이 300개의 데이터만 이용하겠습니다.

GPT-3 의 Fine-tuning 을 사용할 때 데이터 크기에 따라서 과금 될 거니까.. 그냥 조금만 하겠습니다. 지금은 공부하는 단계이니까 Custom model의 정확도 보다는 Custom model을 Fine tuning을 사용해서 만드는 과정을 배우면 되니까요.

 

그 다음은 이 DataFrame을 json 파일로 만드는 겁니다.

 

df.to_json("sport2.jsonl", orient='records', lines=True)

to_json() 함수를 사용해서 sport2.jsonl 이라는 파일을 만듭니다. 

orient='records' 라는 말은 리스트 형태가 된다는 얘기입니다.

 

orient   str

Indication of expected JSON string format.

  • Series:
    • default is ‘index’
    • allowed values are: {‘split’, ‘records’, ‘index’, ‘table’}.
  • DataFrame:
    • default is ‘columns’
    • allowed values are: {‘split’, ‘records’, ‘index’, ‘columns’, ‘values’, ‘table’}.
  • The format of the JSON string:
    • ‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
    • ‘records’ : list like [{column -> value}, … , {column -> value}]
    • ‘index’ : dict like {index -> {column -> value}}
    • ‘columns’ : dict like {column -> {index -> value}}
    • ‘values’ : just the values array
    • ‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}}

    Describing the data, where data component is like orient='records'.

     

    lines = True는 orient가 records일 경우 True로 설정해야 합니다.

     

    linesbool, default False

    If ‘orient’ is ‘records’ write out line-delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list-like.

     

    https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html

 

pandas.DataFrame.to_json — pandas 1.5.3 documentation

The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively. For on-the-fly compression of the output data. If ‘infer’ and ‘path_o

pandas.pydata.org

 

이 부분을 실행하면 해당 디렉토리에 sport2.jsonl 파일이 생성됩니다.

 

이 파일 내용은 아래와 같습니다.

 

prompt 에는 내용이 있고 completion에는 baseball나 hockey가 들어 있습니다. 총 300개의 prompt - completion 쌍이 있습니다.

 

Cookbook에는 다음 단계로 openai 를 업데이트 하라고 돼 있습니다. 

!pip install --upgrade openai

이렇게 해 줍니다. 저같은 경우는 자주 업데이트를 해 줘서 별로 변경되는 내용은 없었습니다.

 

이제 openai의 fine_tunes 함수를 사용할 차례입니다.

 

!openai tools fine_tunes.prepare_data -f sport2.jsonl -q

주피터 노트북에서는 위와 같이 입력하고 Command 창을 사용할 경우에는 !를 없앤 나머지 부분을 타이핑 하면 됩니다.

 

만약 이것을 실행했는데 아래와 같은 메세지가 보인다면 Environment Variable을 설정해 주면 됩니다.

이 문제를 해결하려면 아래 블로그 글을 확인하세요.

https://coronasdk.tistory.com/1295

 

openai 명령어를 command 창에서 인식을 하지 못 할 때...

아래와 같이 command 창에서 openai 를 인식하지 못하는 문제를 해결하는 방법을 알아 보겠습니다. 'openai' is not recognized as an internal or external command, operable program or batch file. 저같은 경우는 Windows에서 P

coronasdk.tistory.com

문제가 없다면 아래와 같은 결과가 나옵니다.

 

 

openai aools fine_tunes.prepare_data는 데이터를 검증하고 제안하고 형식을 다시 지정해 주는 툴입니다.

위 결과를 보면 Analyzing... (분석중)으로 시작해서 이 파일에는 총 300개의 prompt-completion 쌍이 있고 모델을 fine-tune 하려고 하는 것 같은데 저렴한 ada 모델을 사용하세요... 뭐 이렇게 분석과 제안내용이 표시됩니다.

그리고 너무 긴 글이 3개 있고 134, 200,281 번째 줄. .....이렇게 나오고 이 3개는 너무 길어서 제외한다고 나오네요.

 

이 결과로 sport2_prepared_train.jsonl 과 sport2_prepared_valid.jsonl 파일 두개를 만들어 냅니다.

그리고 이제 fine_tunes.create을 사용해서 fine-tuning을 하면 된다고 나오네요.

 

Fine-tuning을 하게 되면 curie 모델을 사용하면 대략 9분 46초 정도 걸릴 것이고 ada 모델을 사용하면 그보다 더 조금 걸릴 거라네요.

 

폴더를 다시 봤더니 정말 두개의 jsonl 파일이 더 생성 되었습니다.

 

sport2_prepared_train.jsonl에는 위에 너무 길다는 3개의 데이터를 없앤 나머지 297개의 데이터가 있습니다.

sport2_prepared_valid.jsonl에는 60개의 데이터가 있습니다.

 

train 데이터와 valid 데이터 이렇게 두개가 생성 되었네요. 이 두개를 생성한 이유는 나중에 새 데이터에 대한 예상 성능을 쉽게 측정하기 위해서 GPT-3 의 fine_tunes.prepare_data 함수가 만든 겁니다.

 

Fine-tuning

이제 다 준비가 됐습니다. 실제로 Fine tuning을 하면 됩니다.

참고로 지금 우리는 내용을 주면 이 내용이 야구에 대한건지 하키에 대한건지 분류 해 주는 fine tuned 된 모델을 생성하려고 합니다.

이 작업은 classification task에 속합니다.

그래서 train 과 valid 두 데이터 세트가 위에서 생성된 거구요.

 

이제 Fine-tuning을 하기 위해 아래 명령어를 사용하면 됩니다.

 

!openai api fine_tunes.create -t "sport2_prepared_train.jsonl" -v "sport2_prepared_valid.jsonl" --compute_classification_metrics --classification_positive_class " baseball" -m ada

 

fine_tunes.create 함수를 사용했고 training data로는 sport2_prepared_train.jsonl 파일이 있고 valid data로는 sport2.prepared_valid_jsonl이 제공된다고 돼 있습니다.

그 다음엔 compute_classification_metrics와 classification_positive_class "baseball" 이 주어 졌는데 이는 위에서 fine_tunes.prepare_data 에서 추천한 내용입니다. classification metics를 계산하기 위해 필요하기 때문에 추천 했습니다.

 

그리고 마지막에 -m ada는 ada 모델을 사용하겠다는 겁니다.

 

이 부분을 실행하면 요금이 청구가 됩니다.

Fine-tuning models 같은 경우 과금은 아래와 같이 됩니다.

 

ada 모델을 사용하니까 토큰 1천개당 0.0004불이 training 과정에 들게 됩니다.

Usage도 있네요 나중에 Fine Tune 된 Custom Model을 사용하게 되면 토큰 1천개당 0.0016 불이 과금 됩니다.

 

https://openai.com/pricing

 

Pricing

Simple and flexible. Only pay for what you use.

openai.com

 

저는 이 fine_tunes.create를 실행하고 30분이 넘었는데도 아무런 응답이 없어서 fine_tunes.list로 체크해 봤습니다.

 

 

그런데 이것도 답변이 없더라구요.

그래서 한참을 더 기다렸습니다.

결국 이날 되지 않아서 GPT-4 발표를 유투브에서 하길래 그 내용만 살펴 보다 끝났네요.

다음날 다시 Jupyterlab 실행 시키고 나서 !openai api fine_tunes.list 를 해 보았습니다.

이제 나왔네요.

저는 11일에도 한번 공부하다가 만든게 있어서 모델이 2개 나왔는데요.

그건 delete로 지워 버렸습니다.

!openai api models.delete -i ada:ft-personal-2023-03-11-15-30-13

결과는 아래와 같이나왔습니다.

{
  "deleted": true,
  "id": "ada:ft-personal-2023-03-11-15-30-13",
  "object": "model"
}

그 후 나온 list 에 대한 결과 입니다.

{
  "data": [
    {
      "created_at": 1678817966,
      "fine_tuned_model": "ada:ft-personal-2023-03-14-18-36-10",
      "hyperparams": {
        "batch_size": 1,
        "classification_positive_class": " baseball",
        "compute_classification_metrics": true,
        "learning_rate_multiplier": 0.1,
        "n_epochs": 4,
        "prompt_loss_weight": 0.01
      },
      "id": "ft-GI4Lb4z2d7TrYstNw15SXhlN",
      "model": "ada",
      "object": "fine-tune",
      "organization_id": "org-어카운트 organization ID",
      "result_files": [
        {
          "bytes": 51539,
          "created_at": 1678818971,
          "filename": "compiled_results.csv",
          "id": "file-5QHkdzACEhvgPxFAopnL4KUe",
          "object": "file",
          "purpose": "fine-tune-results",
          "status": "processed",
          "status_details": null
        }
      ],
      "status": "succeeded",
      "training_files": [
        {
          "bytes": 391121,
          "created_at": 1678817965,
          "filename": "sport2_prepared_train.jsonl",
          "id": "file-pxuc7tJA3rJ5mVI8HKWNe62p",
          "object": "file",
          "purpose": "fine-tune",
          "status": "processed",
          "status_details": null
        }
      ],
      "updated_at": 1678818971,
      "validation_files": [
        {
          "bytes": 89587,
          "created_at": 1678817966,
          "filename": "sport2_prepared_valid.jsonl",
          "id": "file-IDNYZdlWRpi6jhlKhqVs3OaQ",
          "object": "file",
          "purpose": "fine-tune",
          "status": "processed",
          "status_details": null
        }
      ]
    }
  ],
  "object": "list"
}

이번에 만든 모델 이름은 ada:ft-personal-2023-03-14-18-36-10 입니다.

result_files 에 보면 compiled_results.csv 을 생성했다고 하네요.

제 컴퓨터의 폴더를 보니까 아무것도 없더라구요. 아마 OpenAI 내에 보관 되 있는 것 같습니다.

그 다음은 training_files 와 validation_files에 대한 정보를 보여 줍니다.

 

참고로 Cook Book에서는 fine_tunes.create이 진행되는 과정에서 아래와 같은 메세지를 보여 준다고 합니다.

(저는 중간에 끄고 다른일을 봐서 이런 메세지는 못 봤습니다.)

 

 

참고로 이날 300개를 fine-tuning 한 가격은 0.21 달러입니다.

며칠 전에 1197개를 fine tuning 했을 때는 0.78 달러가 나왔었습니다.

 

 

[Advanced] Results and expected model performance

아래 명령어로 생성된 result 파일을 다운 받을 수 있습니다.

 

처음엔 result_files에 있는 ID를 넣었더니 No fine-tune job 이라는 에러 메세지가 나오네요.

여기에는 Fine tune id 를 넣어야 합니다.

그런데 저 같은 경우는 Bad file descriptor 에러 메세지가 나왔습니다.

jupyterlab을 껐다 다시 켜고 했는데도 똑 같더라구요.

 

그런데 제 컴터 폴더에 가 보니까 csv 파일이 생성 돼 있었습니다. 그런데 파일 사이즈는 0이더라구요. 내용이 아무것도 없는거죠.

 

그래서 fine_tunes.create을 다시 해 봤습니다. 새로운 모델을 생성해서 해 보려구요. 

 

이 작업은 시간이 많이 걸릴 것 같습니다.

fine_tunes.create은 일단 걸어 놨고 이 작업이 언제 끝날 지 모르겠네요.

 

GPT-4 에 대한 새로운 글들을 읽어보고 다시 시작해 봤습니다.

Jupyterlab에서 하지 않고 Command 창에서 해 봤는데 여기서도 똑 같네요.

 

 

직접 실습은 어려울 것 같고 Cookbook에 있는 설명을 보면서 공부해야 겠습니다.

 

results = pd.read_csv('result.csv')
results[results['classification/accuracy'].notnull()].tail(1)

일단 result.csv 파일을 생성하는데 성공하면 그 데이터를 pandas의 read_csv를 사용해서 읽어 옵니다.

그 다음줄은 그냥 한 줄 출력해 보는 라인 입니다.

 

결과는 아래와 같습니다.

The accuracy reaches 99.6%. On the plot below we can see how accuracy on the validation set increases during the training run.

정확도는 99.6%에 이릅니다. 아래 플롯에서 훈련 실행 중에 유효성 검사 세트의 정확도가 어떻게 증가하는지 확인할 수 있습니다.

results[results['classification/accuracy'].notnull()]['classification/accuracy'].plot()

그 다음은 이 데이터를 plot 해 봅니다. 결과 화면은 아래와 같습니다.

 

result.csv 파일을 살펴 봤구요.

이제 Fine-tuning으로 만든 새로운 모델을 직접 사용할 차례 입니다.

 

Using the model

We can now call the model to get the predictions.

이제 이 새로운 모델을 call 해서 예측을 해 볼 수 있습니다.

 

test = pd.read_json('sport2_prepared_valid.jsonl', lines=True)
test.head()

 

We need to use the same separator following the prompt which we used during fine-tuning. In this case it is \n\n###\n\n. Since we're concerned with classification, we want the temperature to be as low as possible, and we only require one token completion to determine the prediction of the model.

 

fine-tuning 중에 사용한 프롬프트 다음에 동일한 구분 기호를 사용해야 합니다. 이 경우 \n\n###\n\n입니다. 우리는 분류와 관련이 있기 때문에 temperature 가 가능한 한 낮아지기를 원하며 모델의 예측을 결정하기 위해 하나의 token completion만 필요합니다.

 

ft_model = 'ada:ft-openai-2021-07-30-12-26-20'
res = openai.Completion.create(model=ft_model, prompt=test['prompt'][0] + '\n\n###\n\n', max_tokens=1, temperature=0)
res['choices'][0]['text']

Cookbook 에서 Fine tuning으로 생성한 모델 이름을 ft_model 변수에 넣습니다.

 

그리고 위에 test에 있는 첫번째 prompt를 전달합니다. (우리는 이미 이 내용이 hockey 와 관련 돼 있다는 걸 알고 있습니다.)

이렇게 하면 결과는 이렇습니다.

' hockey'

새로 만든 모델을 써서 정답을 얻어 냈습니다.

 

To get the log probabilities, we can specify logprobs parameter on the completion request

로그 확률을 얻기 위해 완료 요청에 logprobs 매개변수를 지정할 수 있습니다.

 

res = openai.Completion.create(model=ft_model, prompt=test['prompt'][0] + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res['choices'][0]['logprobs']['top_logprobs'][0]
<OpenAIObject at 0x7fe114e435c8> JSON: {
  " baseball": -7.6311407,
  " hockey": -0.0006307676
}

이 결과는 입력값이 어느것과 더 가까운지를 숫자로 보여 줍니다. 

Baseball 보다는 hockey 에 훨썬 더 가깝다는 것을 알 수 있습니다.

 

We can see that the model predicts hockey as a lot more likely than baseball, which is the correct prediction. By requesting log_probs, we can see the prediction (log) probability for each class.

 

모델이 야구보다 하키를 훨씬 더 많이 예측한다는 것을 알 수 있습니다. 이것이 정확한 예측입니다. log_probs를 요청하면 각 클래스에 대한 예측(로그) 확률을 볼 수 있습니다.

 

Generalization

Interestingly, our fine-tuned classifier is quite versatile. Despite being trained on emails to different mailing lists, it also successfully predicts tweets.

 

흥미롭게도 fine-tuned classifier는 매우 다재다능합니다. 다른 메일링 리스트에 대한 이메일에 대한 교육을 받았음에도 불구하고 트윗을 성공적으로 예측합니다.

sample_hockey_tweet = """Thank you to the 
@Canes
 and all you amazing Caniacs that have been so supportive! You guys are some of the best fans in the NHL without a doubt! Really excited to start this new chapter in my career with the 
@DetroitRedWings
 !!"""
res = openai.Completion.create(model=ft_model, prompt=sample_hockey_tweet + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res['choices'][0]['text']

 

이 내용은 이전에 없던 내용 입니다..

내용에 NHL이라는 단어가 있네요. National Hockey league 겠죠?

그러면 이 이메일은 하키와 관련한 이메일 일 겁니다.

Fine tuning으로 만든 새로운 모델도 이것을 정확하게 맞춥니다.

 

' hockey'
sample_baseball_tweet="""BREAKING: The Tampa Bay Rays are finalizing a deal to acquire slugger Nelson Cruz from the Minnesota Twins, sources tell ESPN."""
res = openai.Completion.create(model=ft_model, prompt=sample_baseball_tweet + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res['choices'][0]['text']

그 다음 예제에서는 Tampa Bay Rays , Minnesota Twins 라는 내용이 나옵니다.

Minnesota Twins 는 한 때 박병호 선수가 있었던 메이저리그 야구 팀입니다.

당시에 제가 미네소타에 살고 있어서 구경하러 갔던 기억이 있네요.

 

' baseball'

GPT-3 도 이 내용이 야구와 관련 돼 있다는 걸 알아 차리네요.

 

이상으로 Fine tuning 하는 방법을 알아 봤습니다.

반응형


반응형

윈도우즈의 명령창 (Command Prompt) 에서 OpenAI 를 사용할 때 아래와 같은 에러 메세지가 뜰 수 있습니다.

 

 

이것은 fine_tunes.create 을 사용할 때 나온 에러입니다.

자세한 내용은 아래 페이지에 있습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

에러 메세지는 아래와 같습니다.

 

Error: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://onboard.openai.com for details, or email support@openai.com if you have any questions.

 

오류: API 키가 제공되지 않았습니다. 'openai.api_key = <API-KEY>'를 사용하여 코드에서 API 키를 설정하거나 환경 변수 OPENAI_API_KEY=<API-KEY>)를 설정할 수 있습니다. API 키가 파일에 저장되어 있는 경우 'openai.api_key_path = <PATH>'로 openai 모듈을 가리킬 수 있습니다. OpenAI 웹 인터페이스에서 API 키를 생성할 수 있습니다. 자세한 내용은 https://onboard.openai.com을 참조하거나 질문이 있는 경우 support@openai.com으로 이메일을 보내십시오.

 

해결 방법이 몇가지 나오는데 저 같은 경우는 환경변수를 세팅 해서 해결 했습니다.

 

 

System Properties에서 Environment Variables 버튼을 클릭합니다.

그 다음 밑에 있는 패널인 System variables에서 New 버튼을 클릭합니다.

 

이렇게 환경 변수에 OPENAI_API_KEY 를 세팅 한 후 모두 OK 버튼을 눌러서 닫습니다.

 

이렇게 하면 OpenAI CLI 를 사용할 수 있게 됩니다.

 

사용하기 전에 기존에 실행중이던 JupyterNotebook 이나 JupyterLab local server 는 shutdown 하시고 윈도우즈 Command Prompt 창도 닫습니다.

 

그리고 새로운 윈도우즈 명령창 (Command Prompt) 에서 Jupyter 를 실행하신 다음에 사용하시면 됩니다.

 

그러면 아래와 같이 에러 없이 사용할 수 있습니다.

 

반응형


반응형

아래와 같이 command 창에서 openai 를 인식하지 못하는 문제를 해결하는 방법을 알아 보겠습니다.

'openai' is not recognized as an internal or external command, operable program or batch file.

 

저같은 경우는 Windows에서 Python 하고 Openai를 install 해서 사용하고 있습니다.

Python file에서 openai를 import 해서 사용하는데에는 아무 문제 없습니다.

 

그런데 command 창에서 openai를 사용하려고 하면 위와 같이 openai를 recognized 하지 못한다고 나옵니다.

 

이런 경우는 openai 실행 파일이 System path 에 설정 돼 있지 않아서 그렇습니다.

 

System path 에 openai.exe의 경로를 넣으려면 먼저 openai.exe가 어디에 있는지 부터 알아야 합니다.

 

저는 Windows의 File Explorer 에서 C 드라이브로 가서 openai.exe로 검색했습니다.

 

윈도우즈 사용이 아주 능숙한 편이 아니라서요.

다른 좋은 방법 아시는 분은 그 방법을 사용하시면 됩니다.

 

그 다음은 openai.exe가 있는 곳의 path를 복사 합니다.

openai.exe에서 오른쪽 마우스 클릭을 해서 Properties 를 클릭하시면 아래 그림처럼 Location에 해당 파일의 path가 나와 있습니다.

아니면 Properties말고 Open File Location을 선택하시면 해당 폴더로 이동하는데 거기서 주소창에 있는 path를 복사하시면 됩니다.

 

일단 이 path가 복사 됐으면 System path에 넣어 주시면 됩니다.

 

 

위와 같이 Windows의 System Properties 창을 열고 Environment Variable 버튼을 누릅니다.

그러면 Environment Variables 창이 뜨는데 거기서 아래  System variables 패널에서 에서 Path를 선택하고 Edit 버튼을 누릅니다.

그 다음은 새창에서 new 버튼을 누르고 빈칸에 복사한 path를 붙여넣기 하시면 됩니다.

 

그 다음엔 모두 OK 버튼을 눌러서 닫습니다.

 

Command 창을 다시 열어서 openai라고 넣으면 이제 에러 메세지가 아닌 아래와 같은 openai 에서 제공하는 메세지를 보게 됩니다.

 

이렇게 문제를 해결하면 됩니다.

반응형


반응형

오늘은 Openai Cookbook 에 있는 Fine Tuning 관련 글을 공부해 보겠습니다.

 

https://docs.google.com/document/d/1rqj7dkuvl7Byd5KQPUJRxc19BJt8wo0yHNwK84KfU3Q/edit

 

[PUBLIC] Best practices for fine-tuning GPT-3 to classify text

This document is a draft of a guide that will be added to the next revision of the OpenAI documentation. If you have any feedback, feel free to let us know. One note: this doc shares metrics for text-davinci-002, but that model is not yet available for fin

docs.google.com

 

This document is a draft of a guide that will be added to the next revision of the OpenAI documentation. If you have any feedback, feel free to let us know.

 

이 문서는 OpenAI 문서의 다음 개정판에 추가될 가이드의 초안입니다. 의견이 있으시면 언제든지 알려주십시오.

 

One note: this doc shares metrics for text-davinci-002, but that model is not yet available for fine-tuning.

참고: 이 문서는 text-davinci-002에 대한 메트릭을 공유하지만 해당 모델은 아직 미세 조정에 사용할 수 없습니다.

 

Best practices for fine-tuning GPT-3 to classify text

GPT-3’s understanding of language makes it excellent at text classification. Typically, the best way to classify text with GPT-3 is to fine-tune GPT-3 on training examples. Fine-tuned GPT-3 models can meet and exceed state-of-the-art records on text classification benchmarks.

 

GPT-3의 언어 이해력은 텍스트 분류에 탁월합니다. 일반적으로 GPT-3으로 텍스트를 분류하는 가장 좋은 방법은 training examples 로 GPT-3을 fine-tune하는 것입니다. Fine-tuned GPT-3 모델은 텍스트 분류 벤치마크에서 최신 기록을 충족하거나 능가할 수 있습니다.

 

This article shares best practices for fine-tuning GPT-3 to classify text.

 

이 문서에서는 GPT-3을 fine-tuning 하여 텍스트를 분류하는 모범 사례를 공유합니다.

 

Other resources:

Outline:

Best practices for fine-tuning GPT-3 to classify text

Other resources:

Outline:

How fine-tuning GPT-3 works

Training data

How to format your training data

Separator sequences

How to pick labels

How much training data do you need

How to evaluate your fine-tuned model

Example fine-tuning calls using the OpenAI CLI

The following metrics will be displayed in your results file if you set --compute_classification_metrics:

For multiclass classification

For binary classification

Example outputs

Example metrics evolution over a training run, visualized with Weights & Biases

How to pick the right model

How to pick training hyperparameters

More detail on prompt_loss_weight

Example hyperparameter sweeps

n_epochs

learning_rate_multiplier

prompt_loss_weight

How to pick inference parameters

Advanced techniques

Add reasoning steps

Fine-tune a fine-tuned model

Common mistakes

Common mistake #1: Insufficiently specified training data

Common mistake #2: Input data format that doesn’t match the training data format

More examples

 

 

How fine-tuning GPT-3 works

 

The OpenAI fine-tuning guide explains how to fine-tune your own custom version of GPT-3. You provide a list of training examples (each split into prompt and completion) and the model learns from those examples to predict the completion to a given prompt.

 

OpenAI fine-tuning guide는 사용자 지정 GPT-3 버전을 fine-tune하는 방법을 설명합니다. 교육 예제 목록(각각 prompt completion로 분할)을 제공하면 모델이 해당 예제에서 학습하여 주어진 prompt에 대한 completion 를 예측합니다.

 

Example dataset:

 

Prompt Completion
“burger -->” “ edible”
“paper towels -->” “ inedible”
“vino -->” “ edible”
“bananas -->” “ edible”
“dog toy -->” “ inedible”

In JSONL format:

{"prompt": "burger -->", "completion": " edible"}

{"prompt": "paper towels -->", "completion": " inedible"}

{"prompt": "vino -->", "completion": " edible"}

{"prompt": "bananas -->", "completion": " edible"}

{"prompt": "dog toy -->", "completion": " inedible"}

 

During fine-tuning, the model reads the training examples and after each token of text, it predicts the next token. This predicted next token is compared with the actual next token, and the model’s internal weights are updated to make it more likely to predict correctly in the future. As training continues, the model learns to produce the patterns demonstrated in your training examples.

 

fine-tuning 중에 모델은 교육 예제를 읽고 텍스트의 각 토큰을 받아들여 그 다음 토큰이 무엇이 올 지 예측을 하게 됩니다.  이 예측된 다음 토큰은 실제 다음 토큰과 비교되고 모델의 내부 가중치가 업데이트되어 향후에 올바르게 예측할 가능성이 높아집니다. 학습이 계속됨에 따라 모델은 학습 예제에 표시된 패턴을 생성하는 방법을 배웁니다.

 

After your custom model is fine-tuned, you can call it via the API to classify new examples:

 

사용자 지정 모델이 fine-tuned된 후 API를 통해 호출하여 새 예제를 분류할 수 있습니다.

 

Prompt Completion
“toothpaste -->” ???

Example API call to get the most likely token

가장 유사한 토큰을 얻는 API call 예제

api_response = openai.Completion.create(
    model="{fine-tuned model goes here, without brackets}",
    prompt="toothpaste -->",
    temperature=0,
    max_tokens=1
)
completion_text = api_response['choices'][0]['text']
if completion_text == ' edible':
    label = 'edible'
elif completion_text == ' in':
    label = 'inedible'
else:
    label = 'other'

As ‘ edible’ is 1 token and ‘ inedible’ is 3 tokens, in this example, we request just one completion token and count ‘ in’ as a match for ‘ inedible’.

 

'edible'은 토큰 1개이고 'inedible'은 토큰 3개이므로 이 예에서는 완료 토큰 하나만 요청하고 'inedible'에 대한 일치 항목으로 'in'을 계산합니다.

 

Example API call to get probabilities for the 5 most likely tokens

 가장 유사한 토큰 5개에 대한 probabilities를 얻기 위한 API call 예제

api_response = openai.Completion.create(
    model="{fine-tuned model goes here, without brackets}",
    prompt="toothpaste -->",
    temperature=0,
    max_tokens=1,
    logprobs=5
)
dict_of_logprobs = api_response['choices'][0]['logprobs']['top_logprobs'][0].to_dict()
dict_of_probs = {k: 2.718**v for k, v in dict_of_logprobs.items()}

 

Training data

 

The most important determinant of success is training data.

Fine-tuning 성공의 가장 중요한 결정 요인은 학습 데이터입니다.

 

Your training data should be:

학습 데이터는 다음과 같아야 합니다.

  • Large (ideally thousands or tens of thousands of examples)
  • 대규모(이상적으로는 수천 또는 수만 개의 예)
  • High-quality (consistently formatted and cleaned of incomplete or incorrect examples)
  • 고품질(불완전하거나 잘못된 예를 일관되게 형식화하고 정리)
  • Representative (training data should be similar to the data upon which you’ll use your model)
  • 대표(학습 데이터는 모델을 사용할 데이터와 유사해야 함)
  • Sufficiently specified (i.e., containing enough information in the input to generate what you want to see in the output)
  • 충분히 특정화 되어야 함 (즉, 출력에서 보고 싶은 것을 생성하기 위해 입력에 충분한 정보 포함)

 

If you aren’t getting good results, the first place to look is your training data. Try following the tips below about data formatting, label selection, and quantity of training data needed. Also review our list of common mistakes.

 

좋은 결과를 얻지 못한 경우 가장 먼저 살펴봐야 할 곳은 훈련 데이터입니다. 데이터 형식, 레이블 선택 및 필요한 학습 데이터 양에 대한 아래 팁을 따르십시오. common mistakes 목록도 검토하십시오.

 

How to format your training data

 

Prompts for a fine-tuned model do not typically need instructions or examples, as the model can learn the task from the training examples. Including instructions shouldn’t hurt performance, but the extra text tokens will add cost to each API call.

 

모델이 교육 예제에서 작업을 학습할 수 있으므로 fine-tuned 모델에 대한 프롬프트에는 일반적으로 지침(instruction)이나 예제가 필요하지 않습니다. 지침(instruction)을 포함해도 성능이 저하되지는 않지만 추가 텍스트 토큰으로 인해 각 API 호출에 비용이 추가됩니다.

 

Prompt Tokens Recommended
“burger -->"
“Label the following item as either edible or inedible.

Item: burger
Label:”
20 
“Item: cake
Category: edible

Item: pan
Category: inedible

Item: burger
Category:”
26 

 

Instructions can still be useful when fine-tuning a single model to do multiple tasks. For example, if you train a model to classify multiple features from the same text string (e.g., whether an item is edible or whether it’s handheld), you’ll need some type of instruction to tell the model which feature you want labeled.

 

지침(instruction)은 여러 작업을 수행하기 위해 단일 모델을 fine-tuning할 때 여전히 유용할 수 있습니다. 예를 들어, 동일한 텍스트 문자열에서 여러 기능을 분류하도록 모델을 훈련하는 경우(예: 항목이 먹을 수 있는지 또는 휴대 가능한지 여부) 라벨을 지정하려는 기능을 모델에 알려주는 일종의 지침이 필요합니다.

 

Example training data:

Prompt Completion
“burger --> edible:” “ yes”
“burger --> handheld:” “ yes”
“car --> edible:” “ no”
“car --> handheld:” “ no”

 

Example prompt for unseen example:

Prompt Completion
“cheese --> edible:” ???

 

Note that for most models, the prompt + completion for each example must be less than 2048 tokens (roughly two pages of text). For text-davinci-002, the limit is 4000 tokens (roughly four pages of text).

 

대부분의 모델에서 각 예제에 대한 prompt + completion은 2048 토큰(약 2페이지의 텍스트) 미만이어야 합니다. text-davinci-002의 경우 한도는 4000개 토큰(약 4페이지의 텍스트)입니다.

Separator sequences

For classification, end your text prompts with a text sequence to tell the model that the input text is done and the classification should begin. Without such a signal, the model may append additional invented text before appending a class label, resulting in outputs like:

 

분류를 위해 입력 텍스트가 완료되고 분류가 시작되어야 함을 모델에 알리는 텍스트 시퀀스로 텍스트 프롬프트를 종료합니다. 이러한 신호가 없으면 모델은 클래스 레이블을 appending 하기 전에 추가  invented text append 하여 다음과 같은 결과를 얻을 수 있습니다.

 

  • burger edible (accurate)
  • burger and fries edible (not quite was asked for)
  • burger-patterned novelty tie inedible (inaccurate)
  • burger burger burger burger (no label generated)

Examples of separator sequences

Prompt Recommended
“burger”
“burger -->”
“burger

###

“burger >>>”
“burger

Label:”

 

Be sure that the sequence you choose is very unlikely to otherwise appear in your text (e.g., avoid ‘###’ or ‘->’ when classifying Python code). Otherwise, your choice of sequence usually doesn’t matter much.

 

선택한 sequence 가 텍스트에 다른 방법으로 사용되는 부호인지 확인하세요. (예: Python 코드를 분류할 때 '###' 또는 '->'를 피하십시오). 그러한 경우가 아니라면 시퀀스 선택은 일반적으로 그다지 중요하지 않습니다.

 

How to pick labels

One common question is what to use as class labels.

일반적인 질문 중 하나는 클래스 레이블로 무엇을 사용할 것인가입니다.

 

In general, fine-tuning can work with any label, whether the label has semantic meaning (e.g., “ edible”) or not (e.g., “1”). That said, in cases with little training data per label, it’s possible that semantic labels work better, so that the model can leverage its knowledge of the label’s meaning.

 

일반적으로 fine-tuning은 레이블에 semantic  의미(예: "식용")가 있든 없든(예: "1") 모든 레이블에서 작동할 수 있습니다. 즉, 레이블당 학습 데이터가 적은 경우 시맨틱 레이블이 더 잘 작동하여 모델이 레이블의 의미에 대한 지식을 활용할 수 있습니다.

 

When convenient, we recommend single-token labels. You can check the number of tokens in a string with the OpenAI tokenizer. Single-token labels have a few advantages:

 

가능하면 단일 토큰 레이블을 사용하는 것이 좋습니다. OpenAI 토크나이저를 사용하여 문자열의 토큰 수를 확인할 수 있습니다. 단일 토큰 레이블에는 다음과 같은 몇 가지 장점이 있습니다.

  • Lowest cost . 적은 비용
  • Easier to get their probabilities, which are useful for metrics confidence scores, precision, recall
  • 메트릭 신뢰도 점수, 정밀도, recall에 유용한 확률을 쉽게 얻을 수 있습니다.
  • No hassle from specifying stop sequences or post-processing completions in order to compare labels of different length
  • 다른 길이의 레이블을 비교하기 위해 중지 시퀀스 또는 후처리 완료를 지정하는 번거로움이 없습니다.

Example labels

Prompt Label Recommended
“burger -->” “ edible”
“burger -->” “ 1”
“burger -->” “ yes”
“burger -->” “ A burger can be eaten” (but still works)

 

One useful fact: all numbers <500 are single tokens. 500 이하는 single token입니다.

 

If you do use multi-token labels, we recommend that each label begin with a different token. If multiple labels begin with the same token, an unsure model might end up biased toward those labels due to greedy sampling.

 

multi-token label을 사용하는 경우 각 레이블이 서로 다른 토큰으로 시작하는 것이 좋습니다. 여러 레이블이 동일한 토큰으로 시작하는 경우 greedy  샘플링으로 인해 불확실한 모델이 해당 레이블로 편향될 수 있습니다.

 

How much training data do you need

How much data you need depends on the task and desired performance.

 

필요한 데이터의 양은 작업과 원하는 성능에 따라 다릅니다.


Below is an illustrative example of how adding training examples improves classification accuracy.

 

아래는 학습 예제를 추가하여 분류 정확도를 향상시키는 방법을 보여주는 예시입니다.

 

Illustrative examples of text classification performance on the Stanford Natural Language Inference (SNLI) Corpus, in which ordered pairs of sentences are classified by their logical relationship: either contradicted, entailed (implied), or neutral. Default fine-tuning parameters were used when not otherwise specified.

 

SNLI(Stanford Natural Language Inference) 코퍼스의 텍스트 분류 성능에 대한 예시로, 정렬된 문장 쌍이 논리적 관계(모순됨, 함축됨(암시됨) 또는 중립)에 따라 분류됩니다. 달리 지정되지 않은 경우 기본 fine-tuning 매개변수가 사용되었습니다.

 

Very roughly, we typically see that a few thousand examples are needed to get good performance:

 

아주 대략적으로 말해서 좋은 성능을 얻으려면 일반적으로 수천 개의 예제가 필요하다는 것을 알 수 있습니다.

 

Examples per label Performance (rough estimate)
Hundreds Decent
Thousands Good
Tens of thousands or more Great

 

To assess the value of getting more data, you can train models on subsets of your current dataset—e.g., 25%, 50%, 100%—and then see how performance scales with dataset size. If you plot accuracy versus number of training examples, the slope at 100% will indicate the improvement you can expect from getting more data. (Note that you cannot infer the value of additional data from the evolution of accuracy during a single training run, as a model half-trained on twice the data is not equivalent to a fully trained model.) 

 

더 많은 데이터를 얻는 가치를 평가하기 위해 현재 데이터 세트의 하위 집합(예: 25%, 50%, 100%)에서 모델을 교육한 다음 데이터 세트 크기에 따라 성능이 어떻게 확장되는지 확인할 수 있습니다. 정확도 대 교육 예제 수를 플로팅하는 경우 100%의 기울기는 더 많은 데이터를 얻을 때 기대할 수 있는 개선을 나타냅니다. (두 배의 데이터로 절반만 훈련된 모델은 완전히 훈련된 모델과 동일하지 않기 때문에 단일 훈련 실행 동안 정확도의 진화에서 추가 데이터의 가치를 추론할 수 없습니다.)

 

How to evaluate your fine-tuned model

Evaluating your fine-tuned model is crucial to (a) improve your model and (b) tell when it’s good enough to be deployed.

 

fine-tuned 모델을 평가하는 것은 (a) 모델을 개선하고 (b) 언제 배포하기에 충분한 지를 알려주는 데 중요합니다.

 

Many metrics can be used to characterize the performance of a classifier

 

많은 메트릭을 사용하여 분류기의 성능을 특성화할 수 있습니다.

 

  • Accuracy
  • F1
  • Precision / Positive Predicted Value / False Discovery Rate
  • Recall / Sensitivity
  • Specificity
  • AUC / AUROC (area under the receiver operator characteristic curve)
  • AUPRC (area under the precision recall curve)
  • Cross entropy

Which metric to use depends on your specific application and how you weigh different types of mistakes. For example, if detecting something rare but consequential, where a false negative is costlier than a false positive, you might care about recall more than accuracy.

 

사용할 메트릭은 특정 응용 프로그램과 다양한 유형의 실수에 가중치를 두는 방법에 따라 다릅니다. 예를 들어 거짓 음성이 거짓 긍정보다 비용이 많이 드는 드물지만 결과적인 것을 감지하는 경우 정확도보다 리콜에 더 관심을 가질 수 있습니다.

 

The OpenAI API offers the option to calculate some of these classification metrics. If enabled, these metrics will be periodically calculated during fine-tuning as well as for your final model. You will see them as additional columns in your results file

 

OpenAI API는 이러한 분류 메트릭 중 일부를 계산하는 옵션을 제공합니다. 활성화된 경우 이러한 지표는 최종 모델뿐만 아니라 미세 조정 중에 주기적으로 계산됩니다. 결과 파일에 추가 열로 표시됩니다.

 

To enable classification metrics, you’ll need to:

분류 지표를 활성화하려면 다음을 수행해야 합니다.:

  • use single-token class labels
  • 단일 토큰 클래스 레이블 사용
  • provide a validation file (same format as the training file)
  • 유효성 검사 파일 제공(교육 파일과 동일한 형식)
  • set the flag --compute_classification_metrics
  • compute_classification_metrics 플래그 설정
  • for multiclass classification: set the argument --classification_n_classes
  • 다중 클래스 분류: --classification_n_classes 인수 설정
  • for binary classification: set the argument --classification_positive_class
  • 이진 분류: --classification_positive_class 인수 설정

 

Example fine-tuning calls using the OpenAI CLI

 

# For multiclass classification
openai api fine_tunes.create \
  -t <TRAIN_FILE_ID_OR_PATH> \
  -v <VALIDATION_FILE_OR_PATH> \
  -m <MODEL> \
  --compute_classification_metrics \
  --classification_n_classes <NUMBER_OF_CLASSES>
# For binary classification
openai api fine_tunes.create \
  -t <TRAIN_FILE_ID_OR_PATH> \
  -v <VALIDATION_FILE_OR_PATH> \
  -m <MODEL> \
  --compute_classification_metrics \
  --classification_n_classes 2 \
  --classification_positive_class <POSITIVE_CLASS_FROM_DATASET>

 

The following metrics will be displayed in your results file if you set --compute_classification_metrics:For multiclass classification

compute_classification_metrics 를 설정하면 결과 파일에 다음 지표가 표시됩니다.

  • classification/accuracy: accuracy
  • classification/weighted_f1_score: weighted F-1 score

For binary classification

 

The following metrics are based on a classification threshold of 0.5 (i.e. when the probability is > 0.5, an example is classified as belonging to the positive class.)

 

다음 메트릭은 0.5의 분류 임계값을 기반으로 합니다(즉, 확률이 > 0.5인 경우 예는 포지티브 클래스에 속하는 것으로 분류됨).

  • classification/accuracy
  • classification/precision
  • classification/recall
  • classification/f{beta}
  • classification/auroc - AUROC
  • classification/auprc - AUPRC

Note that these evaluations assume that you are using text labels for classes that tokenize down to a single token, as described above. If these conditions do not hold, the numbers you get will likely be wrong.

 

이러한 평가에서는 위에서 설명한 대로 단일 토큰으로 토큰화하는 클래스에 대해 텍스트 레이블을 사용하고 있다고 가정합니다. 이러한 조건이 충족되지 않으면 얻은 숫자가 잘못되었을 수 있습니다.

 

Example outputs

Example metrics evolution over a training run, visualized with Weights & Biases

 

Weights & Biases로 시각화된 교육 실행에 대한 메트릭 진화의 예

 

 

How to pick the right model

OpenAI offers fine-tuning for 5 models: OpenAI는 fine-tuning에 다음 5가지 모델을 사용할 것을 권장합니다.

  • ada (cheapest and fastest)
  • babbage
  • curie
  • davinci
  • text-davinci-002 (highest quality)

 

Which model to use will depend on your use case and how you value quality versus price and speed. 

 

사용할 모델은 사용 사례와 품질 대 가격 및 속도의 가치를 어떻게 평가하는지에 따라 달라집니다.

 

Generally, we see text classification use cases falling into two categories: simple and complex.

 

일반적으로 텍스트 분류 사용 사례는 단순과 복합의 두 가지 범주로 나뉩니다.

 

For tasks that are simple or straightforward, such as classifying sentiment, larger models offer diminishing benefit, as illustrated below:

 

감정 분류와 같이 간단하거나 직접적인 작업의 경우 더 큰 모델은 아래 그림과 같이 이점이 적습니다.

 

Model Illustrative accuracy* Training cost** Inference cost**
ada 89% $0.0004 / 1K tokens (~3,000 pages per dollar) $0.0016 / 1K tokens (~800 pages per dollar)
babbage 90% $0.0006 / 1K tokens (~2,000 pages per dollar) $0.0024 / 1K tokens (~500 pages per dollar)
curie 91% $0.003 / 1K tokens (~400 pages per dollar) $0.012 / 1K tokens (~100 pages per dollar)
davinci 92% $0.03 / 1K tokens (~40 pages per dollar) $0.12 / 1K tokens (~10 pages per dollar)
text-davinci-002 93% unreleased unreleased

 

*Illustrative accuracy on the SNLI dataset, in which sentence pairs are classified as contradictions, implications, or neutral

*문장 쌍이 모순, 암시 또는 중립으로 분류되는 SNLI 데이터 세트에 대한 설명 정확도

**Pages per dollar figures assume ~800 tokens per page. OpenAI Pricing.

 

Illustrative examples of text classification performance on the Stanford Natural Language Inference (SNLI) Corpus, in which ordered pairs of sentences are classified by their logical relationship: either contradicted, entailed (implied), or neutral. Default fine-tuning parameters were used when not otherwise specified.

 

SNLI(Stanford Natural Language Inference) 코퍼스의 텍스트 분류 성능에 대한 예시로, 정렬된 문장 쌍이 논리적 관계(모순됨, 함축됨(암시됨) 또는 중립)에 따라 분류됩니다. 달리 지정되지 않은 경우 기본 미세 조정 매개변수가 사용되었습니다.

 

For complex tasks, requiring subtle interpretation or reasoning or prior knowledge or coding ability, the performance gaps between models can be larger, and better models like curie or text-davinci-002 could be the best fit.

 

미묘한 해석이나 추론 또는 사전 지식이나 코딩 능력이 필요한 복잡한 작업의 경우 모델 간의 성능 차이가 더 클 수 있으며 curie 또는 text-davinci-002와 같은 더 나은 모델이 가장 적합할 수 있습니다.

 

A single project might end up trying all models. One illustrative development path might look like this:

단일 프로젝트에서 모든 모델을 시도하게 될 수 있습니다. 예시적인 개발 경로는 다음과 같습니다.

  • Test code using the cheapest & fastest model (ada)
  • 가장 저렴하고 빠른 모델(ada)을 사용하여 테스트 코드
  • Run a few early experiments to check whether your dataset works as expected with a middling model (curie)
  • 중간 모델(curie)에서 데이터 세트가 예상대로 작동하는지 확인하기 위해 몇 가지 초기 실험을 실행합니다.
  • Run a few more experiments with the best model to see how far you can push performance (text-davinci-002)
  • 최상의 모델로 몇 가지 실험을 더 실행하여 성능을 얼마나 높일 수 있는지 확인하십시오(text-davinci-002).
  • Once you have good results, do a training run with all models to map out the price-performance frontier and select the model that makes the most sense for your use case  (ada, babbage, curie, davinci, text-davinci-002)
  • 좋은 결과를 얻으면 모든 모델로 교육 실행을 수행하여 가격 대비 성능 한계를 파악하고 사용 사례에 가장 적합한 모델(ada, babbage, curie, davinci, text-davinci-002)을 선택합니다.

Another possible development path that uses multiple models could be:

여러 모델을 사용하는 또 다른 가능한 개발 경로는 다음과 같습니다.

  • Starting with a small dataset, train the best possible model (text-davinci-002)
  • 작은 데이터 세트로 시작하여 가능한 최상의 모델 훈련(text-davinci-002)
  • Use this fine-tuned model to generate many more labels and expand your dataset by multiples
  • 이 미세 조정된 모델을 사용하여 더 많은 레이블을 생성하고 데이터 세트를 배수로 확장하십시오.
  • Use this new dataset to train a cheaper model (ada)
  • 이 새로운 데이터 세트를 사용하여 더 저렴한 모델(ada) 훈련

 

How to pick training hyperparameters

Fine-tuning can be adjusted with various parameters. Typically, the default parameters work well and adjustments only result in small performance changes.

 

미세 조정은 다양한 매개변수로 조정할 수 있습니다. 일반적으로 기본 매개변수는 잘 작동하며 조정해도 성능이 약간만 변경됩니다.

 

Parameter Default Recommendation
n_epochs

controls how many times each example is trained on

각 예제가 훈련되는 횟수를 제어합니다.
4 For classification, we’ve seen good performance with numbers like 4 or 10. Small datasets may need more epochs and large datasets may need fewer epochs.

분류의 경우 4 또는 10과 같은 숫자로 좋은 성능을 보였습니다. 작은 데이터 세트에는 더 많은 에포크가 필요할 수 있고 큰 데이터 세트에는 더 적은 에포크가 필요할 수 있습니다.


If you see low training accuracy, try increasing n_epochs. If you see high training accuracy but low validation accuracy (overfitting), try lowering n_epochs.

훈련 정확도가 낮은 경우 n_epochs를 늘려 보십시오. 훈련 정확도는 높지만 검증 정확도(과적합)가 낮은 경우 n_epochs를 낮추십시오.


You can get training and validation accuracies by setting compute_classification_metrics to True and passing a validation file with labeled examples not in the training data. You can see graphs of these metrics evolving during fine-tuning with a Weights & Biases account.

compute_classification_metrics를 True로 설정하고 교육 데이터에 없는 레이블이 지정된 예제가 있는 유효성 검사 파일을 전달하여 교육 및 유효성 검사 정확도를 얻을 수 있습니다. Weights & Biases 계정을 사용하여 미세 조정하는 동안 진화하는 이러한 지표의 그래프를 볼 수 있습니다.
batch_size
controls the number of training examples used in a single training pass
단일 교육 패스에 사용되는 교육 예제의 수를 제어합니다.
null
(which dynamically adjusts to 0.2% of training set, capped at 256)
(트레이닝 세트의 0.2%로 동적으로 조정되며 256으로 제한됨)
We’ve seen good performance in the range of 0.01% to 2%, but worse performance at 5%+. In general, larger batch sizes tend to work better for larger datasets.

우리는 0.01%에서 2% 범위에서 좋은 성능을 보았지만 5% 이상에서는 더 나쁜 성능을 보였습니다. 일반적으로 더 큰 배치 크기는 더 큰 데이터 세트에서 더 잘 작동하는 경향이 있습니다.
learning_rate_multiplier
controls rate at which the model weights are updated
모델 가중치가 업데이트되는 속도를 제어합니다.
null
(which dynamically adjusts to 0.05, 0.1, or 0.2 depending on batch size)
(배치 크기에 따라 0.05, 0.1 또는 0.2로 동적으로 조정됨)
We’ve seen good performance in the range of 0.02 to 0.5. Larger learning rates tend to perform better with larger batch sizes.

0.02~0.5 범위에서 좋은 성능을 보였습니다. 더 큰 학습 속도는 더 큰 배치 크기에서 더 잘 수행되는 경향이 있습니다.
prompt_loss_weight
controls how much the model learns from prompt tokens vs completion tokens
모델이 프롬프트 토큰과 완료 토큰에서 학습하는 양을 제어합니다.



0.1 If prompts are very long relative to completions, it may make sense to reduce this weight to avoid over-prioritizing learning the prompt. In our tests, reducing this to 0 is sometimes slightly worse or sometimes about the same, depending on the dataset.

프롬프트가 완료에 비해 매우 긴 경우 프롬프트 학습에 과도한 우선순위를 두지 않도록 이 가중치를 줄이는 것이 좋습니다. 테스트에서 데이터 세트에 따라 이를 0으로 줄이는 것이 때때로 약간 더 나쁘거나 거의 동일합니다.

 

More detail on prompt_loss_weight

 

When a model is fine-tuned, it learns to produce text it sees in both the prompt and the completion. In fact, from the point of view of the model being fine-tuned, the distinction between prompt and completion is mostly arbitrary. The only difference between prompt text and completion text is that the model learns less from each prompt token than it does from each completion token. This ratio is controlled by the prompt_loss_weight, which by default is 10%.

 

모델이 미세 조정되면 prompt and the completion 모두에 표시되는 텍스트를 생성하는 방법을 학습합니다. 실제로 미세 조정되는 모델의 관점에서 신속함과 완료의 구분은 대부분 임의적입니다. 프롬프트 텍스트와 완료 텍스트의 유일한 차이점은 모델이 각 완료 토큰에서 학습하는 것보다 각 프롬프트 토큰에서 학습하는 내용이 적다는 것입니다. 이 비율은 prompt_loss_weight에 의해 제어되며 기본적으로 10%입니다.

 

A prompt_loss_weight of 100% means that the model learns from prompt and completion tokens equally. In this scenario, you would get identical results with all training text in the prompt, all training text in the completion, or any split between them. For classification, we recommend against 100%.

 

100%의 prompt_loss_weight는 모델이 프롬프트 및 완료 토큰에서 동일하게 학습함을 의미합니다. 이 시나리오에서는 프롬프트의 모든 학습 텍스트, 완성의 모든 학습 텍스트 또는 이들 간의 분할에 대해 동일한 결과를 얻습니다. 분류의 경우 100% 대비를 권장합니다.

 

A prompt loss weight of 0% means that the model’s learning is focused entirely on the completion tokens. Note that even in this case, prompts are still necessary because they set the context for each completion. Sometimes we’ve seen a weight of 0% reduce classification performance slightly or make results slightly more sensitive to learning rate; one hypothesis is that a small amount of prompt learning helps preserve or enhance the model’s ability to understand inputs.

 

0%의 즉각적인 손실 가중치는 모델의 학습이 완료 토큰에 전적으로 집중되어 있음을 의미합니다. 이 경우에도 프롬프트는 각 완료에 대한 컨텍스트를 설정하기 때문에 여전히 필요합니다. 때때로 우리는 0%의 가중치가 분류 성능을 약간 감소시키거나 결과가 학습률에 약간 더 민감해지는 것을 보았습니다. 한 가지 가설은 소량의 즉각적인 학습이 입력을 이해하는 모델의 능력을 유지하거나 향상시키는 데 도움이 된다는 것입니다.

 

Example hyperparameter sweeps

n_epochs

The impact of additional epochs is particularly high here, because only 100 training examples were used.

 

100개의 학습 예제만 사용되었기 때문에 추가 에포크의 영향이 여기에서 특히 높습니다.

learning_rate_multiplier

prompt_loss_weight

How to pick inference parameters

 

Parameter Recommendation
model (discussed above) [add link]
temperature Set temperature=0 for classification. Positive values add randomness to completions, which can be good for creative tasks but is bad for a short deterministic task like classification.
분류를 위해 온도=0으로 설정합니다. 양수 값은 완성에 임의성을 추가하므로 창의적인 작업에는 좋을 수 있지만 분류와 같은 짧은 결정론적 작업에는 좋지 않습니다.
max_tokens If using single-token labels (or labels with unique first tokens), set max_tokens=1. If using longer labels, set to the length of your longest label.
단일 토큰 레이블(또는 고유한 첫 번째 토큰이 있는 레이블)을 사용하는 경우 max_tokens=1로 설정합니다. 더 긴 레이블을 사용하는 경우 가장 긴 레이블의 길이로 설정하십시오.
stop If using labels of different length, you can optionally append a stop sequence like ‘ END’ to your training completions. Then, pass stop=‘ END’ in your inference call to prevent the model from generating excess text after appending short labels. (Otherwise, you can get completions like “burger -->” “ edible edible edible edible edible edible” as the model continues to generate output after the label is appended.) An alternative solution is to post-process the completions and look for prefixes that match any labels.
길이가 다른 레이블을 사용하는 경우 선택적으로 학습 완료에 ' END'와 같은 중지 시퀀스를 추가할 수 있습니다. 그런 다음 짧은 레이블을 추가한 후 모델이 과도한 텍스트를 생성하지 않도록 추론 호출에서 stop=' END'를 전달합니다. (그렇지 않으면 레이블이 추가된 후에도 모델이 계속 출력을 생성하므로 "burger -->" " edible edible edible edible edible"와 같은 완성을 얻을 수 있습니다.) 대체 솔루션은 완성을 후처리하고 접두사를 찾는 것입니다. 모든 레이블과 일치합니다.
logit_bias If using single-token labels, set logit_bias={“label1”: 100, “label2”:100, …} with your labels in place of “label1” etc.

For tasks with little data or complex labels, models can output tokens for invented classes never specified in your training set. logit_bias can fix this by upweighting your label tokens so that illegal label tokens are never produced. If using logit_bias in conjunction with multi-token labels, take extra care to check how your labels are being split into tokens, as logit_bias only operates on individual tokens, not sequences.

데이터가 적거나 레이블이 복잡한 작업의 경우 모델은 훈련 세트에 지정되지 않은 발명된 클래스에 대한 토큰을 출력할 수 있습니다. logit_bias는 불법 레이블 토큰이 생성되지 않도록 레이블 토큰의 가중치를 높여 이 문제를 해결할 수 있습니다. 다중 토큰 레이블과 함께 logit_bias를 사용하는 경우 logit_bias는 시퀀스가 아닌 개별 토큰에서만 작동하므로 레이블이 토큰으로 분할되는 방식을 특히 주의하십시오.


Logit_bias can also be used to bias specific labels to appear more or less frequently.
Logit_bias를 사용하여 특정 레이블이 더 자주 또는 덜 자주 표시되도록 바이어스할 수도 있습니다.
logprobs Getting the probabilities of each label can be useful for computing confidence scores, precision-recall curves, calibrating debiasing using logit_bias, or general debugging.
각 레이블의 확률을 얻는 것은 신뢰도 점수 계산, 정밀도 재현 곡선, logit_bias를 사용한 편향성 보정 보정 또는 일반 디버깅에 유용할 수 있습니다.


Setting logprobs=5 will return, for each token position of the completion, the top 5 most likely tokens and the natural logs of their probabilities. To convert logprobs into probabilities, raise e to the power of the logprob (probability = e^logprob). The probabilities returned are independent of temperature and represent what the probability would have been if the temperature had been set to 1. By default 5 is the maximum number of logprobs returned, but exceptions can be requested by emailing support@openai.com and describing your use case.

logprobs=5로 설정하면 완료의 각 토큰 위치에 대해 가장 가능성이 높은 상위 5개 토큰과 해당 확률의 자연 로그가 반환됩니다. logprobs를 확률로 변환하려면 e를 logprob의 거듭제곱으로 올립니다(probability = e^logprob). 반환된 확률은 온도와 무관하며 온도가 1로 설정되었을 경우의 확률을 나타냅니다. 기본적으로 5는 반환되는 logprobs의 최대 수. 예외는 support@openai.com으로 이메일을 보내주세요 귀하의 사용 사례를 보내 주세요.


Example API call to get probabilities for the 5 most likely tokens
가능성이 가장 높은 5개의 토큰에 대한 확률을 얻기 위한 API 호출 예

api_response = openai.Completion.create(
    model="{fine-tuned model goes here, without brackets}",
    prompt="toothpaste -->",
    temperature=0,
    max_tokens=1,
    logprobs=5
)
dict_of_logprobs = api_response['choices'][0]['logprobs']['top_logprobs'][0].to_dict()
dict_of_probs = {k: 2.718**v for k, v in dict_of_logprobs.items()}
echo In cases where you want the probability of a particular label that isn’t showing up in the list of logprobs, the echo parameter is useful. If echo is set to True and logprobs is set to a number, the API response will include logprobs for every token of the prompt as well as the completion. So, to get the logprob for any particular label, append that label to the prompt and make an API call with echo=True, logprobs=0, and max_tokens=0.

logprobs 목록에 나타나지 않는 특정 레이블의 확률을 원하는 경우 echo 매개변수가 유용합니다. echo가 True로 설정되고 logprobs가 숫자로 설정되면 API 응답에는 완료뿐 아니라 프롬프트의 모든 토큰에 대한 logprobs가 포함됩니다. 따라서 특정 레이블에 대한 logprob를 가져오려면 해당 레이블을 프롬프트에 추가하고 echo=True, logprobs=0 및 max_tokens=0으로 API 호출을 수행합니다.


Example API call to get the logprobs of prompt tokens

프롬프트 토큰의 logprobs를 가져오기 위한 API 호출 예
import openai


response = openai.Completion.create(
 model="text-davinci-002",
 prompt="burger --> edible",
 temperature=0,
 max_tokens=0,
 logprobs=0,
 echo=True
)


print(response['choices'][0]['logprobs']['token_logprobs'])


===
[None, -0.8182136, -7.7480173, -15.915648]

 

Advanced techniques

Add reasoning steps

For complex tasks that require reasoning, one useful technique you can experiment with is inserting explanations before the final answer. Giving the model extra time and space to think ‘aloud’ can increase the odds it arrives at the correct final answer.

 

추론이 필요한 복잡한 작업의 경우 실험할 수 있는 유용한 기술 중 하나는 최종 답변 앞에 설명을 삽입하는 것입니다. 모델에게 '큰 소리로' 생각할 수 있는 추가 시간과 공간을 제공하면 올바른 최종 답변에 도달할 가능성이 높아질 수 있습니다.

 

Example (from Zelikman, Wu, et al.):

Prompt Completion Completion with reasoning
“Q: Where do you put your grapes just before checking out?
Answer Choices:
(a) mouth
(b) grocery cart
(c) supermarket
(d) fruit basket
(e) fruit market
A:”
“(b)” “The answer should be the place where grocery items are placed before checking out. Of the above choices, grocery cart makes the most sense for holding grocery items. Therefore, the answer is grocery cart (b).”

“답은 체크아웃하기 전에 식료품을 두는 장소여야 합니다. 위의 선택 중에서 식료품 카트는 식료품을 보관하는 데 가장 적합합니다. 따라서 정답은 식료품 카트(b)입니다.”

Although it can sound daunting to write many example explanations, it turns out you can use large language models to write the explanations. In 2022, Zelikman, Wu, et al. published a procedure called STaR (Self-Taught Reasoner) in which a few-shot prompt can be used to generate a set of {questions, rationales, answers} from just a set of {questions, answers}

많은 예제 설명을 작성하는 것이 어렵게 들릴 수 있지만 큰 언어 모델을 사용하여 설명을 작성할 수 있습니다. 2022년 Zelikman, Wu, et al. {질문, 답변} 세트에서 {질문, 근거, 답변} 세트를 생성하기 위해 몇 번의 프롬프트를 사용할 수 있는 STaR(Self-Taught Reasoner)라는 절차를 발표했습니다.

 

 

Sequential fine-tuning

Models can be fine-tuned sequentially as many times as you like. One way you can use this is to pre-train your model on a large amount of relevant text, such as unstructured domain text or similar classification tasks, and then afterwards fine-tune on examples of the task you want the model to perform. An example procedure could look like:

 

모델은 원하는 만큼 순차적으로 미세 조정할 수 있습니다. 이를 사용할 수 있는 한 가지 방법은 구조화되지 않은 도메인 텍스트 또는 유사한 분류 작업과 같은 많은 양의 관련 텍스트에 대해 모델을 사전 훈련한 다음 나중에 모델이 수행할 작업의 예를 미세 조정하는 것입니다. 예제 절차는 다음과 같습니다.

 

  • Step 1: Fine-tune on cheap, semi-relevant data
    • E.g., unstructured domain text (such as legal or medical text)
    • E.g., similar task data (such as another large classification set)
  • Step 2: Fine-tune on expensive labeled examples
  • E.g., text and classes (if training a classifier)

To fine-tune a previously fine-tuned model, pass in the fine-tuned model name when creating a new fine-tuning job (e.g. -m curie:ft-<org>-<date>). Other training parameters do not have to be changed, however if your new training data is much smaller than your previous training data, you may find it useful to reduce learning_rate_multiplier by a factor of 2 to 4.

 

이전에 미세 조정된 모델을 미세 조정하려면 새 미세 조정 작업을 생성할 때 미세 조정된 모델 이름을 전달합니다(예: -m curie:ft-<org>-<date>). 다른 훈련 매개변수는 변경할 필요가 없지만 새 훈련 데이터가 이전 훈련 데이터보다 훨씬 작은 경우 learning_rate_multiplier를 2~4배 줄이는 것이 유용할 수 있습니다.

 

Common mistakes

The most common mistakes when fine-tuning text classifiers are usually related to training data.

 

텍스트 분류기를 미세 조정할 때 가장 흔한 실수는 일반적으로 훈련 데이터와 관련이 있습니다.

Common mistake #1: Insufficiently specified training data

One thing to keep in mind is that training data is more than just a mapping of inputs to correct answers. Crucially, the inputs need to contain the information needed to derive an answer.

 

한 가지 명심해야 할 점은 교육 데이터가 정답에 대한 입력의 매핑 이상이라는 것입니다. 결정적으로 입력에는 답을 도출하는 데 필요한 정보가 포함되어야 합니다.

 

For example, consider fine-tuning a model to predict someone’s grades using the following dataset:

 

예를 들어 다음 데이터 세트를 사용하여 누군가의 성적을 예측하도록 모델을 미세 조정하는 것을 고려하십시오.

 

Prompt Completion
“Alice >>>” “ A”
“Bob >>>” “ B+”
“Coco >>>” “ A-”
“Dominic >>>” “ B”

 

Prompt Completion
“Esmeralda >>>” ???

Without knowing why these students got the grades they did, there is insufficient information for the model to learn from and no hope of making a good personalized prediction for Esmeralda.

 

이 학생들이 자신이 받은 성적을 받은 이유를 모르면 모델이 배울 수 있는 정보가 충분하지 않으며 Esmeralda에 대해 좋은 개인화된 예측을 할 수 있는 희망이 없습니다.

 

This can happen more subtly when some information is given but some is still missing. For example, if fine-tuning a classifier on whether a business expense is allowed or disallowed, and the business expense policy varies by date or by location or by employee type, make sure the input contains information on dates, locations, and employee type.

 

이것은 일부 정보가 제공되었지만 일부가 여전히 누락된 경우 더 미묘하게 발생할 수 있습니다. 예를 들어 비즈니스 비용이 허용되는지 여부에 대한 분류자를 미세 조정하고 비즈니스 비용 정책이 날짜, 위치 또는 직원 유형에 따라 달라지는 경우 입력에 날짜, 위치 및 직원 유형에 대한 정보가 포함되어 있는지 확인하십시오.

 

Prompt Completion
“Amount: $50
Item: Steak dinner

###

“ allowed”
“Amount: $50
Item: Steak dinner

###

“ disallowed”

 

Prompt Completion
“Amount: $50
Item: Steak dinner

###

???

 

Common mistake #2: Input data format that doesn’t match the training data format

Make sure that when you use your fine-tuned model, your submitted prompts match the format of your training data.

 

미세 조정된 모델을 사용할 때 제출된 프롬프트가 훈련 데이터의 형식과 일치하는지 확인하십시오.

 

Training data format API call OK?
“dog toy -->” “dog toy” Missing separator
“Amount: $50
Item: Steak dinner

###

“Is a $50 steak dinner allowed?

###

Different format
“Esmeralda >>>” “Esmeralda >>> ” Extra space appended

 

More examples

Below, we share more examples of training data for possible classifiers.

 

아래에서 가능한 분류기에 대한 훈련 데이터의 더 많은 예를 공유합니다.

 

Truthful consistency classifier

Prompt Completion
"Company: BHFF insurance
Product: allround insurance
Ad: One stop shop for all your insurance needs!
Supported:"
“ yes”
"Company: Loft conversion specialists
Product: -
Ad: Straight teeth in weeks!
Supported:"

“ no”

 

Product review classifier (with multiple classes labeled in parallel)

Prompt Completion
"4/5 stars

Camera seems fine. Not amazing, but perfectly decent.

Biggest complaint is that the cable is only 5 feet long, which I didn't think to check. It's my fault, so I won't return it, but 5 feet is really short if you have multiple monitors and probably impossible if you have a desktop on the floor next to a standing desk.

###

Positives:"

“ fine, perfectly decent
Negatives: not amazing, cable is only 5 feet long
Overall sentiment: positive
Possible improvements: longer cable
Return risk: 1
Support priority: low
Customer type: N/A”
"4/5 stars

I bought this on sale for $70. I'm satisfied with it.

(1) The instructions weren't that bad. (There was really only one ambiguous step, and it was easy to make an educated guess at the right way to go. Surprised by the ordering of one of the steps because some bars were hanging there for a while, but whatever.)

(2) It definitely is labor intensive - the most painful step is screwing in 24 small wood screws to get the hooks attached. And it takes a bit of skill to get them all vertically parallel. Got a big blister from all the screwing. And the angles made it hard to use power tools - ended up screwing in by hand because it was easier to stay vertical next to the hook.

(3) I weight 170 pounds and honestly the bench seems fine for supporting my weight. I was worried from the other reviews. But my trick was to leave things a little loose until the end and then really tighten everything once it was all together. I think really tightening at the end prevents any squeaky rocking. But only used it one day so far, so we'll see.

Overall this is definitely cheap, but feels totally fine. It's cheap in a cheap way, not cheap in a junky knockoff way. Would buy again. Looks great.

###

Positives:"


“ instructions weren’t that bad, looks great
Negatives: ambiguous step, labor intensive, got a big blister, cheap
Overall sentiment: positive
Possible improvements: less ambiguous instructions
Return risk: 0
Support priority: low
Customer type: N/A”
"5/5 stars

I'm a fan. It's shiny and pure metal. Exactly what I wanted.

###

Positives:”
“ shiny, pure metal
Negatives: N/A
Overall sentiment: positive
Possible improvements: N/A
Return risk: 0
Support priority: low
Customer type: N/A

 

Sentiment analyzer

Prompt Completion
"Overjoyed with the new iPhone! ->"

“ positive”
"@lakers disappoint for a third straight night https://t.co/38EFe43 ->"


“ negative”

 

Email prioritizer

Prompt Completion
"Subject: Update my address
From: Joe Doe
To: support@ourcompany.com
Date: 2021-06-03
Content: Hi,
I would like to update my billing address to match my delivery address.

Please let me know once done.

Thanks,
Joe

###

"

“ 4”

 

Legal claim detector

Prompt Completion
"When the IPV (injection) is used, 90% or more of individuals develop protective antibodies to all three serotypes of polio virus after two doses of inactivated polio vaccine (IPV), and at least 99% are immune to polio virus following three doses. -->"

“ efficacy”
"Jonas Edward Salk (/sɔːlk/; born Jonas Salk; October 28, 1914 – June 23, 1995) was an American virologist and medical researcher who developed one of the first successful polio vaccines. He was born in New York City and attended the City College of New York and New York University School of Medicine. -->"


“ not”

 

News subject detector

Prompt Completion
"PC World - Upcoming chip set will include built-in security features for your PC. >>>"

“ 4”

(where 4 = Sci/Tech)
“Newspapers in Greece reflect a mixture of exhilaration that the Athens Olympics proved successful, and relief that they passed off without any major setback. >>>”

“ 2”

(where 2 = Sports)

 

Logical relationship detector

Prompt Completion
"A land rover is being driven across a river.
A vehicle is crossing a river.

###

"

“ implication”
"Violin soloists take the stage during the orchestra's opening show at the theater.
People are playing the harmonica while standing on a roof.

###

"


“ contradiction”

 

반응형


반응형

https://platform.openai.com/docs/api-reference/audio

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

Audio

Beta

POST https://api.openai.com/v1/audio/transcriptions

Transcribes audio into the input language.

음성 메세지를 입력한 언어로 Transcribes (필사) 합니다.

 

import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
audio_file = open("audio.mp3", "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)
{
  "file": "audio.mp3",
  "model": "whisper-1"
}
{
  "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that."
}

 

Request body

file
string Required

The audio file to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.

문자로 변환 하게 될 오디오 파일 입니다. mp3, mp4, mpeg, mpga, m4a, wav 또는 webm 형식 중 하나 이어야 합니다.

 

model
string Required

ID of the model to use. Only whisper-1 is currently available.

사용할 모델의 ID입니다. 현재 whisper-1 모델만 사용할 수 있습니다.

 

prompt
string Optional

An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language.

모델의 스타일을 안내하거나 이전 오디오 세그먼트를 계속하는 선택적 텍스트입니다. 프롬프트는 오디오 언어와 일치해야 합니다.

 

 

response_format
string Optional Defaults to json

The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.

필사한 값의 output format입니다. json, text, srt, verbose_json 또는 vtt  포맷 중 하나 입니다.

 

 
temperature
number Optional Defaults to 0

The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.

샘플링 온도는 0에서 1 사이입니다. 0.8과 같이 값이 높을수록 출력이 더 무작위적으로 생성되고 0.2와 같이 값이 낮을수록 더 집중되고 결정적입니다. 0으로 설정하면 모델은 로그 확률을 사용하여 특정 임계값에 도달할 때까지 자동으로 temperature 를 높입니다.

 

 

language
string Optional

The language of the input audio. Supplying the input language in ISO-639-1 format will improve accuracy and latency.

입력 오디오의 언어입니다. ISO-639-1 형식으로 입력 언어를 제공하면 정확도와 대기 시간이 향상됩니다.

 

Create translation

Beta

POST https://api.openai.com/v1/audio/translations

Translates audio into into English. 

음성데이터를 영어로 번역합니다.

 

import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
audio_file = open("german.m4a", "rb")
transcript = openai.Audio.translate("whisper-1", audio_file)
{
  "file": "german.m4a",
  "model": "whisper-1"
}
{
  "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?"
}

 

Request body

file
string Required

The audio file to translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.

문자로 변환 하게 될 오디오 파일 입니다. mp3, mp4, mpeg, mpga, m4a, wav 또는 webm 형식 중 하나 이어야 합니다.

 

 

model
string Required

ID of the model to use. Only whisper-1 is currently available.

사용할 모델의 ID입니다. 현재 whisper-1 모델만 사용할 수 있습니다.

 

 

prompt
string Optional

An optional text to guide the model's style or continue a previous audio segment. The prompt should be in English.

모델의 스타일을 안내하거나 이전 오디오 세그먼트를 계속하는 선택적 텍스트입니다. 프롬프트는 오디오 언어와 일치해야 합니다.

 

 

response_format
string Optional Defaults to json

The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.

transcript output 의 포맷입니다. json, text, srt, verbose_json 또는 vtt  포맷 중 하나 입니다.

 

temperature
number Optional Defaults to 0

The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.

 

샘플링 온도는 0에서 1 사이입니다. 0.8과 같이 값이 높을수록 출력이 더 무작위적으로 생성되고 0.2와 같이 값이 낮을수록 더 집중되고 결정적입니다. 0으로 설정하면 모델은 로그 확률을 사용하여 특정 임계값에 도달할 때까지 자동으로 temperature 를 높입니다.

 

 

 

반응형

Get Started - Tutorials

2023. 3. 6. 23:02 | Posted by 솔웅


반응형

이번에 (2023년 3월 1일) OpenAI 가 ChatGPT API 를 공개하면서 docs 페이지가 많이 추가 됐습니다.

그 중에 Get Started 부문에서는 Tutorials 와 Data usage policies 부분이 추가 됐습니다.

 

오늘은 그 중에 Tutorials 페이지를 보겠습니다.

 

https://platform.openai.com/docs/tutorials

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

Tutorials에는 OpenAI API를 사용해서 실제 AI 어플리케이션을 개발 하는 과정을 스텝 바이 스텝으로 따라갈 수 있도록 하기 위해 만들어진 페이지 인 것 같습니다.

 

아직까지는 Website Q&A with Embeddings 라는 것만 있고 나머지 두개는 Coming soon 으로 돼 있습니다.

마지막 줄에서는 Examples gallery OpenAI Cookbook  이 소개 돼 있고 이곳들에서 좀 더 많은 아이디어를 얻을 수 있다고 돼 있습니다.

 

저는 OpenAI Cookbook을 공부하다가 3월 1일 ChatGPT API 와 speech to text 모델인 Whisper 가 공개 되면서 여러가지 업데이트가 많이 돼서 잠깐 그 업데이트들을 살펴 보고 있습니다.

 

이 업데이트들을 다 살펴 본 후 다시 OpenAI Cookbook을 공부하고 그 다음에 Examples gallery 에 있는 예제들을 분석해 볼 예정입니다.

 

그 다음 여건이 되면 개인 프로젝트를 하고 싶은데.... 아직 희망사항이구요.

 

이번 업데이트는 Get Started, Guides 그리고 API Reference 에 많은 페이지들이 추가 됐구요 그 중 Guides 에 추가 된 Chat completion, Speech to text, Rate limit 그리고 Error codes 페이지는 다 살펴 보았습니다.

 

https://coronasdk.tistory.com/category/Open%20AI/GUIDES

 

'Open AI/GUIDES' 카테고리의 글 목록

개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들

coronasdk.tistory.com

 

지금은 Get Started 를 보고 있고 여기에는 Tutorials와 Data usage policies 페이지가 추가 됐습니다.

 

Get Started 를 다 마치면 API Reference 쪽을 보고 다시 OpenAI Cookbook으로 돌아 가겠습니다.

 

그럼 본론으로 들어가서 GetStarted - Tutorials - Website Q&A with Embeddings 페이지를 살펴 보도록 하겠습니다.

 

여기에는 여러분의 웹사이트에 대한 질문에 답변을 할 수 있는 AI를 어떻게 build 하는지에 대해 배우는 페이지라고 돼 있습니다.

 

https://platform.openai.com/docs/tutorials/web-qa-embeddings

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

How to build an AI that can answer questions about your website

This tutorial walks through a simple example of crawling a website (in this example, the OpenAI website), turning the crawled pages into embeddings using the Embeddings API, and then creating a basic search functionality that allows a user to ask questions about the embedded information. This is intended to be a starting point for more sophisticated applications that make use of custom knowledge bases.

 

이 튜토리얼에서는 웹사이트(이 예에서는 OpenAI 웹사이트)를 크롤링하고 Embeddings API를 사용하여 크롤링된 페이지를 임베딩으로 변환한 다음 사용자가 임베디드 정보에 대해 질문할 수 있는 기본 검색 기능을 생성하는 간단한 예제를 안내합니다. . 이는 custom knowledge bases를 사용하는 보다 정교한 애플리케이션 개발의 첫 발걸음을 어떻게 떼어야 하는지 보여드릴 것입니다..

 

 

Getting started

 

Some basic knowledge of Python and GitHub is helpful for this tutorial. Before diving in, make sure to set up an OpenAI API key and walk through the quickstart tutorial. This will give a good intuition on how to use the API to its full potential.

 

Python 및 GitHub에 대한 기본 지식이 이 자습서를 공부하는데 도움이 됩니다. 시작하기 전에 OpenAI API 키를 설정하고 quickstart tutorial를 살펴보십시오. 이렇게 하면 API를 최대한 활용하는 방법에 대한 좋은 직관을 얻을 수 있습니다.

 

Python is used as the main programming language along with the OpenAI, Pandas, transformers, NumPy, and other popular packages. If you run into any issues working through this tutorial, please ask a question on the OpenAI Community Forum.

 

Python은 OpenAI, Pandas, 변환기, NumPy 및 기타 널리 사용되는 패키지와 함께 기본 프로그래밍 언어로 사용됩니다. 이 튜토리얼을 진행하면서 문제가 발생하면 OpenAI Community Forum에서 질문하십시오.

 

To start with the code, clone the full code for this tutorial on GitHub. Alternatively, follow along and copy each section into a Jupyter notebook and run the code step by step, or just read along. A good way to avoid any issues is to set up a new virtual environment and install the required packages by running the following commands:

 

코드로 시작하려면 GitHub에서 이 자습서의 전체 코드를 복제하세요. 또는 따라가서 각 섹션을 Jupyter 노트북에 복사하고 코드를 단계별로 실행하세요. 그런 시간이 없으면 그냥 이 페이지를 읽어 보시기만 하셔도 됩니다. 문제를 피하는 좋은 방법은 다음 명령을 실행하여 새 가상 환경을 설정하고 필요한 패키지를 설치하는 것입니다.

 

python -m venv env

source env/bin/activate

pip install -r requirements.txt

Note : venv 는 가상 환경을 만드는 파이썬 툴이고 source는 실행 명령 입니다. 이것이 안 되면 해당 폴더로 가서 activate을 실행 시키면 됩니다.

requirements.txt 는 위에서 준 GitHub 링크로 가면 있습니다. full code for this tutorial on GitHub 

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

Setting up a web crawler

The primary focus of this tutorial is the OpenAI API so if you prefer, you can skip the context on how to create a web crawler and just download the source code. Otherwise, expand the section below to work through the scraping mechanism implementation.

 

이 자습서의 주요 초점은 OpenAI API이므로 원하는 경우 웹 크롤러를 만드는 방법에 대한 컨텍스트를 건너뛰고 소스 코드를 다운로드할 수 있습니다. 그렇지 않으면 아래 섹션을 확장하여 스크래핑 메커니즘 구현을 통해 작업하십시오.

 

Learn how to build a web crawler

 

 

Acquiring data in text form is the first step to use embeddings. This tutorial creates a new set of data by crawling the OpenAI website, a technique that you can also use for your own company or personal website.
 
임베딩을 사용하기 위한 첫 번째 단계는 텍스트 형태로 데이터를 수집하는 것입니다. 이 자습서에서는 회사 또는 개인 웹 사이트에도 사용할 수 있는 기술인 OpenAI 웹 사이트를 크롤링하여 새로운 데이터 집합을 만듭니다.
 

 

While this crawler is written from scratch, open source packages like Scrapy can also help with these operations.

 

이 크롤러는 처음부터 작성되었지만 Scrapy와 같은 오픈 소스 패키지도 이러한 작업에 도움이 될 수 있습니다.

 

This crawler will start from the root URL passed in at the bottom of the code below, visit each page, find additional links, and visit those pages as well (as long as they have the same root domain). To begin, import the required packages, set up the basic URL, and define a HTMLParser class.

 

이 크롤러는 아래 코드 하단에 전달된 루트 URL에서 시작하여 각 페이지를 방문하고 추가 링크를 찾고 해당 페이지도 방문합니다(루트 도메인이 동일한 경우). 시작하려면 필요한 패키지를 가져오고 기본 URL을 설정하고 HTMLParser 클래스를 정의합니다.

 

import requests
import re
import urllib.request
from bs4 import BeautifulSoup
from collections import deque
from html.parser import HTMLParser
from urllib.parse import urlparse
import os

# Regex pattern to match a URL
HTTP_URL_PATTERN = r'^http[s]*://.+'

domain = "openai.com" # <- put your domain to be crawled
full_url = "https://openai.com/" # <- put your domain to be crawled with https or http

# Create a class to parse the HTML and get the hyperlinks
class HyperlinkParser(HTMLParser):
    def __init__(self):
        super().__init__()
        # Create a list to store the hyperlinks
        self.hyperlinks = []

    # Override the HTMLParser's handle_starttag method to get the hyperlinks
    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)

        # If the tag is an anchor tag and it has an href attribute, add the href attribute to the list of hyperlinks
        if tag == "a" and "href" in attrs:
            self.hyperlinks.append(attrs["href"])

 

다음 함수는 URL을 인수로 사용하여 URL을 열고 HTML 콘텐츠를 읽습니다. 그런 다음 해당 페이지에서 찾은 모든 하이퍼링크를 반환합니다.

 

# Function to get the hyperlinks from a URL
def get_hyperlinks(url):
    
    # Try to open the URL and read the HTML
    try:
        # Open the URL and read the HTML
        with urllib.request.urlopen(url) as response:

            # If the response is not HTML, return an empty list
            if not response.info().get('Content-Type').startswith("text/html"):
                return []
            
            # Decode the HTML
            html = response.read().decode('utf-8')
    except Exception as e:
        print(e)
        return []

    # Create the HTML Parser and then Parse the HTML to get hyperlinks
    parser = HyperlinkParser()
    parser.feed(html)

    return parser.hyperlinks

 

The goal is to crawl through and index only the content that lives under the OpenAI domain. For this purpose, a function that calls the get_hyperlinks function but filters out any URLs that are not part of the specified domain is needed.

 

목표는 OpenAI 도메인에 있는 콘텐츠만 크롤링하고 인덱싱하는 것입니다. 이를 위해서는 get_hyperlinks 함수를 호출하되 지정된 도메인에 속하지 않는 URL을 필터링하는 함수가 필요합니다.

 

# Function to get the hyperlinks from a URL that are within the same domain
def get_domain_hyperlinks(local_domain, url):
    clean_links = []
    for link in set(get_hyperlinks(url)):
        clean_link = None

        # If the link is a URL, check if it is within the same domain
        if re.search(HTTP_URL_PATTERN, link):
            # Parse the URL and check if the domain is the same
            url_obj = urlparse(link)
            if url_obj.netloc == local_domain:
                clean_link = link

        # If the link is not a URL, check if it is a relative link
        else:
            if link.startswith("/"):
                link = link[1:]
            elif link.startswith("#") or link.startswith("mailto:"):
                continue
            clean_link = "https://" + local_domain + "/" + link

        if clean_link is not None:
            if clean_link.endswith("/"):
                clean_link = clean_link[:-1]
            clean_links.append(clean_link)

    # Return the list of hyperlinks that are within the same domain
    return list(set(clean_links))

The crawl function is the final step in the web scraping task setup. It keeps track of the visited URLs to avoid repeating the same page, which might be linked across multiple pages on a site. It also extracts the raw text from a page without the HTML tags, and writes the text content into a local .txt file specific to the page.

 

크롤링 기능은 웹 스크래핑 작업 설정의 마지막 단계입니다. 사이트의 여러 페이지에 연결될 수 있는 동일한 페이지를 반복하지 않도록 방문한 URL을 추적합니다. 또한 HTML 태그가 없는 페이지에서 원시 텍스트를 추출하고 텍스트 콘텐츠를 페이지 고유의 로컬 .txt 파일에 기록합니다.

 

def crawl(url):
    # Parse the URL and get the domain
    local_domain = urlparse(url).netloc

    # Create a queue to store the URLs to crawl
    queue = deque([url])

    # Create a set to store the URLs that have already been seen (no duplicates)
    seen = set([url])

    # Create a directory to store the text files
    if not os.path.exists("text/"):
            os.mkdir("text/")

    if not os.path.exists("text/"+local_domain+"/"):
            os.mkdir("text/" + local_domain + "/")

    # Create a directory to store the csv files
    if not os.path.exists("processed"):
            os.mkdir("processed")

    # While the queue is not empty, continue crawling
    while queue:

        # Get the next URL from the queue
        url = queue.pop()
        print(url) # for debugging and to see the progress

        # Save text from the url to a <url>.txt file
        with open('text/'+local_domain+'/'+url[8:].replace("/", "_") + ".txt", "w", encoding="UTF-8") as f:

            # Get the text from the URL using BeautifulSoup
            soup = BeautifulSoup(requests.get(url).text, "html.parser")

            # Get the text but remove the tags
            text = soup.get_text()

            # If the crawler gets to a page that requires JavaScript, it will stop the crawl
            if ("You need to enable JavaScript to run this app." in text):
                print("Unable to parse page " + url + " due to JavaScript being required")
            
            # Otherwise, write the text to the file in the text directory
            f.write(text)

        # Get the hyperlinks from the URL and add them to the queue
        for link in get_domain_hyperlinks(local_domain, url):
            if link not in seen:
                queue.append(link)
                seen.add(link)

crawl(full_url)

The last line of the above example runs the crawler which goes through all the accessible links and turns those pages into text files. This will take a few minutes to run depending on the size and complexity of your site.

 

위 예제의 마지막 줄은 크롤러를 실행하여 액세스 가능한 모든 링크를 통과하고 해당 페이지를 텍스트 파일로 변환합니다. 사이트의 크기와 복잡성에 따라 실행하는 데 몇 분 정도 걸립니다.

 

Building an embeddings index

CSV is a common format for storing embeddings. You can use this format with Python by converting the raw text files (which are in the text directory) into Pandas data frames. Pandas is a popular open source library that helps you work with tabular data (data stored in rows and columns).
 
CSV는 임베딩을 저장하기 위한 일반적인 형식입니다. 원시 텍스트 파일(텍스트 디렉터리에 있음)을 Pandas 데이터 프레임으로 변환하여 Python에서 이 형식을 사용할 수 있습니다. Pandas는 테이블 형식 데이터(행과 열에 저장된 데이터)로 작업하는 데 도움이 되는 인기 있는 오픈 소스 라이브러리입니다.
 
Blank empty lines can clutter the text files and make them harder to process. A simple function can remove those lines and tidy up the files.
 
비어 있는 빈 줄은 텍스트 파일을 복잡하게 만들고 처리하기 어렵게 만들 수 있습니다. 간단한 기능으로 해당 줄을 제거하고 파일을 정리할 수 있습니다.
def remove_newlines(serie):
    serie = serie.str.replace('\n', ' ')
    serie = serie.str.replace('\\n', ' ')
    serie = serie.str.replace('  ', ' ')
    serie = serie.str.replace('  ', ' ')
    return serie

 

Converting the text to CSV requires looping through the text files in the text directory created earlier. After opening each file, remove the extra spacing and append the modified text to a list. Then, add the text with the new lines removed to an empty Pandas data frame and write the data frame to a CSV file.

 

텍스트를 CSV로 변환하려면 이전에 만든 텍스트 디렉터리의 텍스트 파일을 통해 반복해야 합니다. 각 파일을 연 후 여분의 공백을 제거하고 수정된 텍스트를 목록에 추가합니다. 그런 다음 새 줄이 제거된 텍스트를 빈 Pandas 데이터 프레임에 추가하고 데이터 프레임을 CSV 파일에 씁니다.

 

Extra spacing and new lines can clutter the text and complicate the embeddings process. The code used here helps to remove some of them but you may find 3rd party libraries or other methods useful to get rid of more unnecessary characters.

 

여분의 간격과 새 줄은 텍스트를 어지럽히고 임베딩 프로세스를 복잡하게 만들 수 있습니다. 여기에 사용된 코드는 그 중 일부를 제거하는 데 도움이 되지만 더 많은 불필요한 문자를 제거하는 데 유용한 타사 라이브러리 또는 기타 방법을 찾을 수 있습니다.

 

import pandas as pd

# Create a list to store the text files
texts=[]

# Get all the text files in the text directory
for file in os.listdir("text/" + domain + "/"):

    # Open the file and read the text
    with open("text/" + domain + "/" + file, "r", encoding="UTF-8") as f:
        text = f.read()

        # Omit the first 11 lines and the last 4 lines, then replace -, _, and #update with spaces.
        texts.append((file[11:-4].replace('-',' ').replace('_', ' ').replace('#update',''), text))

# Create a dataframe from the list of texts
df = pd.DataFrame(texts, columns = ['fname', 'text'])

# Set the text column to be the raw text with the newlines removed
df['text'] = df.fname + ". " + remove_newlines(df.text)
df.to_csv('processed/scraped.csv')
df.head()

 

Tokenization is the next step after saving the raw text into a CSV file. This process splits the input text into tokens by breaking down the sentences and words. A visual demonstration of this can be seen by checking out our Tokenizer in the docs.

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

토큰화는 원시 텍스트를 CSV 파일로 저장한 후의 다음 단계입니다. 이 프로세스는 문장과 단어를 분해하여 입력 텍스트를 토큰으로 분할합니다. 이에 대한 시각적 데모는 checking out our Tokenizer  문서에서 확인하여 볼 수 있습니다.

 

A helpful rule of thumb is that one token generally corresponds to ~4 characters of text for common English text. This translates to roughly ¾ of a word (so 100 tokens ~= 75 words).

 

유용한 경험 법칙은 하나의 토큰이 일반적으로 일반 영어 텍스트의 텍스트에서 ~4자에 해당한다는 것입니다. 이것은 대략 단어의 3/4로 변환됩니다(따라서 100 토큰 ~= 75 단어).

 

The API has a limit on the maximum number of input tokens for embeddings. To stay below the limit, the text in the CSV file needs to be broken down into multiple rows. The existing length of each row will be recorded first to identify which rows need to be split.

 

API에는 임베딩을 위한 최대 입력 토큰 수에 대한 제한이 있습니다. 한도 미만으로 유지하려면 CSV 파일의 텍스트를 여러 행으로 나누어야 합니다. 분할해야 하는 행을 식별하기 위해 각 행의 기존 길이가 먼저 기록됩니다.

 

import tiktoken

# Load the cl100k_base tokenizer which is designed to work with the ada-002 model
tokenizer = tiktoken.get_encoding("cl100k_base")

df = pd.read_csv('processed/scraped.csv', index_col=0)
df.columns = ['title', 'text']

# Tokenize the text and save the number of tokens to a new column
df['n_tokens'] = df.text.apply(lambda x: len(tokenizer.encode(x)))

# Visualize the distribution of the number of tokens per row using a histogram
df.n_tokens.hist()

 

The newest embeddings model can handle inputs with up to 8191 input tokens so most of the rows would not need any chunking, but this may not be the case for every subpage scraped so the next code chunk will split the longer lines into smaller chunks.

 

최신 임베딩 모델은 최대 8191개의 입력 토큰으로 입력을 처리할 수 있으므로 대부분의 행에 청킹이 필요하지 않지만 스크랩된 모든 하위 페이지에 해당하는 것은 아니므로 다음 코드 청크가 더 긴 줄을 더 작은 청크로 분할합니다.

 

max_tokens = 500

# Function to split the text into chunks of a maximum number of tokens
def split_into_many(text, max_tokens = max_tokens):

    # Split the text into sentences
    sentences = text.split('. ')

    # Get the number of tokens for each sentence
    n_tokens = [len(tokenizer.encode(" " + sentence)) for sentence in sentences]
    
    chunks = []
    tokens_so_far = 0
    chunk = []

    # Loop through the sentences and tokens joined together in a tuple
    for sentence, token in zip(sentences, n_tokens):

        # If the number of tokens so far plus the number of tokens in the current sentence is greater 
        # than the max number of tokens, then add the chunk to the list of chunks and reset
        # the chunk and tokens so far
        if tokens_so_far + token > max_tokens:
            chunks.append(". ".join(chunk) + ".")
            chunk = []
            tokens_so_far = 0

        # If the number of tokens in the current sentence is greater than the max number of 
        # tokens, go to the next sentence
        if token > max_tokens:
            continue

        # Otherwise, add the sentence to the chunk and add the number of tokens to the total
        chunk.append(sentence)
        tokens_so_far += token + 1

    return chunks
    

shortened = []

# Loop through the dataframe
for row in df.iterrows():

    # If the text is None, go to the next row
    if row[1]['text'] is None:
        continue

    # If the number of tokens is greater than the max number of tokens, split the text into chunks
    if row[1]['n_tokens'] > max_tokens:
        shortened += split_into_many(row[1]['text'])
    
    # Otherwise, add the text to the list of shortened texts
    else:
        shortened.append( row[1]['text'] )

Visualizing the updated histogram again can help to confirm if the rows were successfully split into shortened sections.

 

업데이트된 히스토그램을 다시 시각화하면 행이 단축된 섹션으로 성공적으로 분할되었는지 확인하는 데 도움이 될 수 있습니다.

 

df = pd.DataFrame(shortened, columns = ['text'])
df['n_tokens'] = df.text.apply(lambda x: len(tokenizer.encode(x)))
df.n_tokens.hist()

 

The content is now broken down into smaller chunks and a simple request can be sent to the OpenAI API specifying the use of the new text-embedding-ada-002 model to create the embeddings:

 

콘텐츠는 이제 더 작은 청크로 분류되며 새 text-embedding-ada-002 모델을 사용하여 임베딩을 생성하도록 지정하는 간단한 요청을 OpenAI API로 보낼 수 있습니다.

 

import openai

df['embeddings'] = df.text.apply(lambda x: openai.Embedding.create(input=x, engine='text-embedding-ada-002')['data'][0]['embedding'])

df.to_csv('processed/embeddings.csv')
df.head()

 

This should take about 3-5 minutes but after you will have your embeddings ready to use!

 

이 작업은 약 3-5분 정도 소요되지만 임베딩을 사용할 준비가 된 후에야 합니다!

 

Building a question answer system with your embeddings

The embeddings are ready and the final step of this process is to create a simple question and answer system. This will take a user's question, create an embedding of it, and compare it with the existing embeddings to retrieve the most relevant text from the scraped website. The text-davinci-003 model will then generate a natural sounding answer based on the retrieved text.

 

임베딩이 준비되었으며 이 프로세스의 마지막 단계는 간단한 질문 및 답변 시스템을 만드는 것입니다. 이것은 사용자의 질문을 받아 임베딩을 생성하고 기존 임베딩과 비교하여 스크랩한 웹사이트에서 가장 관련성이 높은 텍스트를 검색합니다. 그러면 text-davinci-003 모델이 검색된 텍스트를 기반으로 자연스러운 답변을 생성합니다.

 

Turning the embeddings into a NumPy array is the first step, which will provide more flexibility in how to use it given the many functions available that operate on NumPy arrays. It will also flatten the dimension to 1-D, which is the required format for many subsequent operations.

 

임베딩을 NumPy 배열로 전환하는 것이 첫 번째 단계이며 NumPy 배열에서 작동하는 많은 기능을 사용할 수 있는 경우 사용 방법에 더 많은 유연성을 제공합니다. 또한 많은 후속 작업에 필요한 형식인 1D로 차원을 평면화합니다.

 

import numpy as np
from openai.embeddings_utils import distances_from_embeddings

df=pd.read_csv('processed/embeddings.csv', index_col=0)
df['embeddings'] = df['embeddings'].apply(eval).apply(np.array)

df.head()

 

The question needs to be converted to an embedding with a simple function, now that the data is ready. This is important because the search with embeddings compares the vector of numbers (which was the conversion of the raw text) using cosine distance. The vectors are likely related and might be the answer to the question if they are close in cosine distance. The OpenAI python package has a built in distances_from_embeddings function which is useful here.

 

이제 데이터가 준비되었으므로 질문을 간단한 기능을 사용하여 임베딩으로 변환해야 합니다. 임베딩을 사용한 검색은 코사인 거리를 사용하여 숫자 벡터(원본 텍스트의 변환)를 비교하기 때문에 이는 중요합니다. 벡터는 관련이 있을 가능성이 높으며 코사인 거리가 가까운 경우 질문에 대한 답이 될 수 있습니다. OpenAI Python 패키지에는 여기에서 유용한 distances_from_embeddings 함수가 내장되어 있습니다.

 

def create_context(
    question, df, max_len=1800, size="ada"
):
    """
    Create a context for a question by finding the most similar context from the dataframe
    """

    # Get the embeddings for the question
    q_embeddings = openai.Embedding.create(input=question, engine='text-embedding-ada-002')['data'][0]['embedding']

    # Get the distances from the embeddings
    df['distances'] = distances_from_embeddings(q_embeddings, df['embeddings'].values, distance_metric='cosine')


    returns = []
    cur_len = 0

    # Sort by distance and add the text to the context until the context is too long
    for i, row in df.sort_values('distances', ascending=True).iterrows():
        
        # Add the length of the text to the current length
        cur_len += row['n_tokens'] + 4
        
        # If the context is too long, break
        if cur_len > max_len:
            break
        
        # Else add it to the text that is being returned
        returns.append(row["text"])

    # Return the context
    return "\n\n###\n\n".join(returns)

 

The text was broken up into smaller sets of tokens, so looping through in ascending order and continuing to add the text is a critical step to ensure a full answer. The max_len can also be modified to something smaller, if more content than desired is returned.

 

텍스트는 더 작은 토큰 세트로 분할되었으므로 오름차순으로 반복하고 텍스트를 계속 추가하는 것이 전체 답변을 보장하는 중요한 단계입니다. 원하는 것보다 더 많은 콘텐츠가 반환되는 경우 max_len을 더 작은 값으로 수정할 수도 있습니다.

 

The previous step only retrieved chunks of texts that are semantically related to the question, so they might contain the answer, but there's no guarantee of it. The chance of finding an answer can be further increased by returning the top 5 most likely results.

 

이전 단계에서는 질문과 의미론적으로 관련된 텍스트 덩어리만 검색했으므로 답변이 포함되어 있을 수 있지만 이에 대한 보장은 없습니다. 가장 가능성이 높은 상위 5개의 결과를 반환하여 답변을 찾을 가능성을 더욱 높일 수 있습니다.

 

The answering prompt will then try to extract the relevant facts from the retrieved contexts, in order to formulate a coherent answer. If there is no relevant answer, the prompt will return “I don’t know”.

 

응답 프롬프트는 일관된 답변을 공식화하기 위해 검색된 컨텍스트에서 관련 사실을 추출하려고 시도합니다. 관련 답변이 없으면 프롬프트에 "모르겠습니다"가 표시됩니다.

 

A realistic sounding answer to the question can be created with the completion endpoint using text-davinci-003.

 

text-davinci-003을 사용하여 completion endpoint 로 질문에 대한 현실적인 답을 만들 수 있습니다.

 

def answer_question(
    df,
    model="text-davinci-003",
    question="Am I allowed to publish model outputs to Twitter, without a human review?",
    max_len=1800,
    size="ada",
    debug=False,
    max_tokens=150,
    stop_sequence=None
):
    """
    Answer a question based on the most similar context from the dataframe texts
    """
    context = create_context(
        question,
        df,
        max_len=max_len,
        size=size,
    )
    # If debug, print the raw model response
    if debug:
        print("Context:\n" + context)
        print("\n\n")

    try:
        # Create a completions using the question and context
        response = openai.Completion.create(
            prompt=f"Answer the question based on the context below, and if the question can't be answered based on the context, say \"I don't know\"\n\nContext: {context}\n\n---\n\nQuestion: {question}\nAnswer:",
            temperature=0,
            max_tokens=max_tokens,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0,
            stop=stop_sequence,
            model=model,
        )
        return response["choices"][0]["text"].strip()
    except Exception as e:
        print(e)
        return ""

 

It is done! A working Q/A system that has the knowledge embedded from the OpenAI website is now ready. A few quick tests can be done to see the quality of the output:

 

완료되었습니다! OpenAI 웹사이트에서 내장된 지식이 있는 작동하는 Q/A 시스템이 이제 준비되었습니다. 출력 품질을 확인하기 위해 몇 가지 빠른 테스트를 수행할 수 있습니다.

 

answer_question(df, question="What day is it?", debug=False)

answer_question(df, question="What is our newest embeddings model?")

answer_question(df, question="What is ChatGPT?")

 

The responses will look something like the following:

 

Response는 다음과 같은 방식으로 나올 겁니다.

 

"I don't know."

'The newest embeddings model is text-embedding-ada-002.'

'ChatGPT is a model trained to interact in a conversational way. It is able to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests.'

 

If the system is not able to answer a question that is expected, it is worth searching through the raw text files to see if the information that is expected to be known actually ended up being embedded or not. The crawling process that was done initially was setup to skip sites outside the original domain that was provided, so it might not have that knowledge if there was a subdomain setup.

 

시스템이 예상되는 질문에 대답할 수 없는 경우 원시 텍스트 파일을 검색하여 알려질 것으로 예상되는 정보가 실제로 포함되었는지 여부를 확인하는 것이 좋습니다. 초기에 진행한 크롤링 과정은 원래 제공된 도메인 외 사이트는 건너뛰도록 설정되어 있어서 서브도메인 설정이 있었다면 해당 정보가 없을 수도 있습니다.

 

Currently, the dataframe is being passed in each time to answer a question. For more production workflows, a vector database solution should be used instead of storing the embeddings in a CSV file, but the current approach is a great option for prototyping.

 

현재 데이터 프레임은 질문에 답하기 위해 매번 전달되고 있습니다. 더 많은 프로덕션 워크플로우의 경우 임베딩을 CSV 파일에 저장하는 대신 벡터 데이터베이스 솔루션을 사용해야 하지만 현재 접근 방식은 프로토타이핑을 위한 훌륭한 옵션입니다.

반응형

'Open AI > GET STARTED' 카테고리의 다른 글

Get Started - Data usage policies  (0) 2023.03.06
Get Started - Usage policies  (0) 2023.01.05
Get Started - Models (Added GPT-4 03/14/2023)  (1) 2023.01.05
Get Started - Libraries  (0) 2023.01.04
Get Started - Quick Start Tutorial  (0) 2023.01.03
Get Started - Introduction  (0) 2023.01.03

Guide - Error codes

2023. 3. 5. 23:58 | Posted by 솔웅


반응형

https://platform.openai.com/docs/guides/error-codes/api-errors

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

Error codes

This guide includes an overview on error codes you might see from both the API and our official Python library. Each error code mentioned in the overview has a dedicated section with further guidance.

 

이 가이드에는 API와 공식 Python 라이브러리 모두에서 볼 수 있는 오류 코드에 대한 개요가 포함되어 있습니다. 개요에 언급된 각 오류 코드에는 추가 지침이 있는 전용 섹션이 있습니다.

 

API errors

CODE                                                                    OVERVIEW

401 - Invalid Authentication Cause: Invalid Authentication
Solution: Ensure the correct API key and requesting organization are being used.
401 - Incorrect API key provided Cause: The requesting API key is not correct.
Solution: Ensure the API key used is correct, clear your browser cache, or generate a new one.
401 - You must be a member of an organization to use the API Cause: Your account is not part of an organization.
Solution: Contact us to get added to a new organization or ask your organization manager to invite you to an organization.
429 - Rate limit reached for requests Cause: You are sending requests too quickly.
Solution: Pace your requests. Read the Rate limit guide.
429 - You exceeded your current quota, please check your plan and billing details Cause: You have hit your maximum monthly spend (hard limit) which you can view in the account billing section.
Solution: Apply for a quota increase.
429 - The engine is currently overloaded, please try again later Cause: Our servers are experiencing high traffic.
Solution: Please retry your requests after a brief wait.
500 - The server had an error while processing your request Cause: Issue on our servers.
Solution: Retry your request after a brief wait and contact us if the issue persists. Check the status page.

 

401 - Invalid Authentication

 

This error message indicates that your authentication credentials are invalid. This could happen for several reasons, such as:

이 오류 메시지는 인증 자격 증명이 유효하지 않음을 나타냅니다. 이는 다음과 같은 여러 가지 이유로 발생할 수 있습니다.

  • You are using a revoked API key.
  • 취소된 API 키를 사용하고 있습니다.
  • You are using a different API key than the one assigned to the requesting organization.
  • 요청 조직에 할당된 것과 다른 API 키를 사용하고 있습니다.
  • You are using an API key that does not have the required permissions for the endpoint you are calling.
  • 호출 중인 엔드포인트에 필요한 권한이 없는 API 키를 사용하고 있습니다.

To resolve this error, please follow these steps:

이 오류를 해결하려면 다음 단계를 따르십시오.

  • Check that you are using the correct API key and organization ID in your request header. You can find your API key and organization ID in your account settings.
  • 요청 헤더에서 올바른 API 키와 조직 ID를 사용하고 있는지 확인하세요. 계정 설정에서 API 키와 조직 ID를 찾을 수 있습니다.
  • If you are unsure whether your API key is valid, you can generate a new one. Make sure to replace your old API key with the new one in your requests and follow our best practices guide.
  • API 키가 유효한지 확실하지 않은 경우 새 키를 생성할 수 있습니다. 요청 시 이전 API 키를 새 키로 교체하고 권장사항 가이드를 따르세요.

 

401 - Incorrect API key provided

 

This error message indicates that the API key you are using in your request is not correct. This could happen for several reasons, such as:

이 오류 메시지는 요청에 사용 중인 API 키가 올바르지 않음을 나타냅니다. 이는 다음과 같은 여러 가지 이유로 발생할 수 있습니다.

  • There is a typo or an extra space in your API key.
  • API 키에 오타나 추가 공백이 있습니다.
  • You are using an API key that belongs to a different organization.
  • 다른 조직에 속한 API 키를 사용하고 있습니다.
  • You are using an API key that has been deleted or deactivated.
  • 삭제 또는 비활성화된 API 키를 사용하고 있습니다.
  • An old, revoked API key might be cached locally.
  • 해지된 이전 API 키는 로컬에 캐시될 수 있습니다.

To resolve this error, please follow these steps:

이 오류를 해결하려면 다음 단계를 따르십시오.

  • Try clearing your browser's cache and cookies, then try again.
  • 브라우저의 캐시와 쿠키를 삭제한 후 다시 시도하세요.
  • Check that you are using the correct API key in your request header.
  • 요청 헤더에서 올바른 API 키를 사용하고 있는지 확인하십시오.
  • If you are unsure whether your API key is correct, you can generate a new one. Make sure to replace your old API key in your codebase and follow our best practices guide.
  • API 키가 올바른지 확실하지 않은 경우 새 키를 생성할 수 있습니다. 코드베이스에서 이전 API 키를 교체하고 모범 사례 가이드를 따르십시오.

 

401 - You must be a member of an organization to use the API

 

This error message indicates that your account is not part of an organization. This could happen for several reasons, such as:

이 오류 메시지는 귀하의 계정이 조직의 일부가 아님을 나타냅니다. 이는 다음과 같은 여러 가지 이유로 발생할 수 있습니다.

  • You have left or been removed from your previous organization.
  • 이전 조직에서 탈퇴했거나 제거되었습니다.
  • Your organization has been deleted.
  • 조직이 삭제되었습니다.

To resolve this error, please follow these steps:

이 오류를 해결하려면 다음 단계를 따르십시오.

  • If you have left or been removed from your previous organization, you can either request a new organization or get invited to an existing one.
  • 이전 조직에서 탈퇴했거나 제거된 경우 새 조직을 요청하거나 기존 조직에 초대받을 수 있습니다.
  • To request a new organization, reach out to us via help.openai.com
  • 새 조직을 요청하려면 help.openai.com을 통해 문의하십시오.
  • Existing organization owners can invite you to join their organization via the Members Panel.
  • 기존 조직 소유자는 구성원 패널을 통해 귀하를 조직에 가입하도록 초대할 수 있습니다.

 

429 - Rate limit reached for requests

 

This error message indicates that you have hit your assigned rate limit for the API. This means that you have submitted too many tokens or requests in a short period of time and have exceeded the number of requests allowed. This could happen for several reasons, such as:

이 오류 메시지는 API에 할당된 Rate Limit에 도달했음을 나타냅니다. 이는 단기간에 너무 많은 토큰 또는 요청을 제출했고 허용된 요청 수를 초과했음을 의미합니다. 이는 다음과 같은 여러 가지 이유로 발생할 수 있습니다.

 

  • You are using a loop or a script that makes frequent or concurrent requests.
  • 자주 또는 동시에 요청하는 루프 또는 스크립트를 사용하고 있습니다.
  • You are sharing your API key with other users or applications.
  • 다른 사용자 또는 애플리케이션과 API 키를 공유하고 있습니다.
  • You are using a free plan that has a low rate limit.
  • Rate Limit이 낮은 무료 플랜을 사용하고 있습니다.

 

To resolve this error, please follow these steps:

이 오류를 해결하려면 다음 단계를 따르십시오.

  • Pace your requests and avoid making unnecessary or redundant calls.
  • 요청 속도를 조절하고 불필요하거나 중복된 호출을 피하십시오.
  • If you are using a loop or a script, make sure to implement a backoff mechanism or a retry logic that respects the rate limit and the response headers. You can read more about our rate limiting policy and best practices in our rate limit guide.
  • 루프 또는 스크립트를 사용하는 경우 rate limit 및 응답 헤더를 준수하는 backoff메커니즘 또는 재시도 논리를 구현해야 합니다. rate limit guide에서 rate limit 정책 및 모범 사례에 대해 자세히 알아볼 수 있습니다.
  • If you are sharing your organization with other users, note that limits are applied per organization and not per user. It is worth checking on the usage of the rest of your team as this will contribute to the limit.
  • 조직을 다른 사용자와 공유하는 경우 제한은 사용자가 아닌 조직별로 적용됩니다. 한도에 영향을 미치므로 나머지 팀의 사용량을 확인하는 것이 좋습니다.
  • If you are using a free or low-tier plan, consider upgrading to a pay-as-you-go plan that offers a higher rate limit. You can compare the restrictions of each plan in our rate limit guide.
  • 무료 또는 낮은 계층 요금제를 사용하는 경우 더 높은 rate limit을 제공하는 종량제 요금제로 업그레이드하는 것이 좋습니다. 요금 제한 가이드에서 각 플랜의 제한 사항을 비교할 수 있습니다.
try:
  #Make your OpenAI API request here
  response = openai.Completion.create(prompt="Hello world",
                                      model="text-davinci-003")
except openai.error.APIError as e:
  #Handle API error here, e.g. retry or log
  print(f"OpenAI API returned an API Error: {e}")
  pass
except openai.error.APIConnectionError as e:
  #Handle connection error here
  print(f"Failed to connect to OpenAI API: {e}")
  pass
except openai.error.RateLimitError as e:
  #Handle rate limit error (we recommend using exponential backoff)
  print(f"OpenAI API request exceeded rate limit: {e}")
  pass

 

429 - You exceeded your current quota, please check your plan and billing details

 

This error message indicates that you have hit your maximum monthly spend for the API. You can view your maximum monthly limit, under ‘hard limit’ in your [account billing settings](/account/billing/limits). This means that you have consumed all the credits allocated to your plan and have reached the limit of your current billing cycle. This could happen for several reasons, such as:

이 오류 메시지는 API에 대한 최대 월별 지출에 도달했음을 나타냅니다. [계정 결제 설정](/account/billing/limits)의 '하드 한도'에서 최대 월 한도를 확인할 수 있습니다. 이는 계획에 할당된 모든 크레딧을 사용했으며 현재 청구 주기의 한도에 도달했음을 의미합니다. 이는 다음과 같은 여러 가지 이유로 발생할 수 있습니다.

  • You are using a high-volume or complex service that consumes a lot of credits or tokens.
  • 크레딧이나 토큰을 많이 소모하는 대용량 또는 복잡한 서비스를 사용하고 있습니다.
  • Your limit is set too low for your organization’s usage.
  • 한도가 조직의 사용량에 비해 너무 낮게 설정되었습니다.

 

To resolve this error, please follow these steps:

이 오류를 해결하려면 다음 단계를 따르십시오.

  • Check your current quota in your account settings. You can see how many tokens your requests have consumed in the usage section of your account.
  • 계정 설정에서 현재 할당량을 확인하세요. 계정의 사용량 섹션에서 요청이 소비한 토큰 수를 확인할 수 있습니다.
  • If you are using a free plan, consider upgrading to a pay-as-you-go plan that offers a higher quota.
  • 무료 요금제를 사용 중인 경우 더 높은 할당량을 제공하는 종량제 요금제로 업그레이드하는 것이 좋습니다.
  • If you need a quota increase, you can apply for one and provide relevant details on expected usage. We will review your request and get back to you in ~7-10 business days.
  • 할당량 증가가 필요한 경우 신청하고 예상 사용량에 대한 관련 세부 정보를 제공할 수 있습니다. 귀하의 요청을 검토한 후 영업일 기준 ~7~10일 이내에 연락드리겠습니다.

429 - The engine is currently overloaded, please try again later

 

This error message indicates that our servers are experiencing high traffic and are unable to process your request at the moment. This could happen for several reasons, such as:

이 오류 메시지는 당사 서버의 트래픽이 많아 현재 귀하의 요청을 처리할 수 없음을 나타냅니다. 이는 다음과 같은 여러 가지 이유로 발생할 수 있습니다.

  • There is a sudden spike or surge in demand for our services.
  • 서비스에 대한 수요가 갑자기 급증하거나 급증합니다.
  • There is scheduled or unscheduled maintenance or update on our servers.
  • 서버에 예정되거나 예정되지 않은 유지 관리 또는 업데이트가 있습니다.
  • There is an unexpected or unavoidable outage or incident on our servers.
  • 당사 서버에 예상치 못한 또는 피할 수 없는 중단 또는 사고가 발생했습니다.

 

To resolve this error, please follow these steps:

이 오류를 해결하려면 다음 단계를 따르십시오.

  • Retry your request after a brief wait. We recommend using an exponential backoff strategy or a retry logic that respects the response headers and the rate limit. You can read more about our rate limit best practices.
  • 잠시 기다린 후 요청을 다시 시도하십시오. exponential backoff 전략 또는 응답 헤더 및  Rate limit을 준수하는 재시도 논리를 사용하는 것이 좋습니다. Rate limit 모범 사례에 대해 자세히 알아볼 수 있습니다.
  • Check our status page for any updates or announcements regarding our services and servers.
  • 서비스 및 서버에 관한 업데이트 또는 공지 사항은 상태 페이지를 확인하십시오.
  • If you are still getting this error after a reasonable amount of time, please contact us for further assistance. We apologize for any inconvenience and appreciate your patience and understanding.
  • 상당한 시간이 지난 후에도 이 오류가 계속 발생하면 당사에 문의하여 추가 지원을 받으십시오. 불편을 끼쳐 드려 죄송하며 양해해 주셔서 감사합니다.

 

Python library error types

TYPE                OVERVIEW

APIError Cause: Issue on our side.
Solution: Retry your request after a brief wait and contact us if the issue persists.
Timeout Cause: Request timed out.
Solution: Retry your request after a brief wait and contact us if the issue persists.
RateLimitError Cause: You have hit your assigned rate limit.
Solution: Pace your requests. Read more in our Rate limit guide.
APIConnectionError Cause: Issue connecting to our services.
Solution: Check your network settings, proxy configuration, SSL certificates, or firewall rules.
InvalidRequestError Cause: Your request was malformed or missing some required parameters, such as a token or an input.
Solution: The error message should advise you on the specific error made. Check the documentation for the specific API method you are calling and make sure you are sending valid and complete parameters. You may also need to check the encoding, format, or size of your request data.
AuthenticationError Cause: Your API key or token was invalid, expired, or revoked.
Solution: Check your API key or token and make sure it is correct and active. You may need to generate a new one from your account dashboard.
ServiceUnavailableError Cause: Issue on our servers.
Solution: Retry your request after a brief wait and contact us if the issue persists. Check the status page.

 

APIError

 

An `APIError` indicates that something went wrong on our side when processing your request. This could be due to a temporary error, a bug, or a system outage.

 

'APIError'는 요청을 처리할 때 OpenAI 측에서 문제가 발생했음을 나타냅니다. 이는 일시적인 오류, 버그 또는 시스템 중단 때문일 수 있습니다.

 

We apologize for any inconvenience and we are working hard to resolve any issues as soon as possible. You can check our system status page for more information.

 

불편을 끼쳐 드려 죄송하며 가능한 한 빨리 문제를 해결하기 위해 노력하고 있습니다. 자세한 내용은 시스템 상태 페이지에서 확인할 수 있습니다.

 

If you encounter an APIError, please try the following steps:

APIError가 발생하면 다음 단계를 시도해 보세요.

  • Wait a few seconds and retry your request. Sometimes, the issue may be resolved quickly and your request may succeed on the second attempt.
  • 몇 초간 기다린 후 요청을 다시 시도하십시오. 경우에 따라 문제가 빠르게 해결되고 두 번째 시도에서 요청이 성공할 수 있습니다.
  • Check our status page for any ongoing incidents or maintenance that may affect our services. If there is an active incident, please follow the updates and wait until it is resolved before retrying your request.
  • 당사 서비스에 영향을 미칠 수 있는 진행 중인 사건이나 유지 보수에 대해서는 상태 페이지를 확인하십시오. active incident가 있는 경우 업데이트를 따르고 요청을 다시 시도하기 전에 문제가 해결될 때까지 기다리십시오.
  • If the issue persists, check out our Persistent errors next steps section.
  • 문제가 지속되면 지속적인 오류 다음 단계 섹션을 확인하세요.

Our support team will investigate the issue and get back to you as soon as possible. Note that our support queue times may be long due to high demand. You can also post in our Community Forum but be sure to omit any sensitive information.

 

지원팀에서 문제를 조사하고 최대한 빨리 답변을 드릴 것입니다. 수요가 많기 때문에 지원 대기 시간이 길어질 수 있습니다. 커뮤니티 포럼에 게시할 수도 있지만 민감한 정보는 생략해야 합니다.

 

Timeout

 

A `Timeout` error indicates that your request took too long to complete and our server closed the connection. This could be due to a network issue, a heavy load on our services, or a complex request that requires more processing time.

 

'시간 초과' 오류는 요청을 완료하는 데 시간이 너무 오래 걸려 서버가 연결을 종료했음을 나타냅니다. 이는 네트워크 문제, 서비스에 대한 과부하 또는 더 많은 처리 시간이 필요한 복잡한 요청 때문일 수 있습니다.

 

If you encounter a Timeout error, please try the following steps:

시간 초과 오류가 발생하면 다음 단계를 시도하십시오.

  • Wait a few seconds and retry your request. Sometimes, the network congestion or the load on our services may be reduced and your request may succeed on the second attempt.
  • 몇 초간 기다린 후 요청을 다시 시도하십시오. 경우에 따라 네트워크 정체 또는 당사 서비스의 부하가 줄어들 수 있으며 두 번째 시도에서 요청이 성공할 수 있습니다.
  • Check your network settings and make sure you have a stable and fast internet connection. You may need to switch to a different network, use a wired connection, or reduce the number of devices or applications using your bandwidth.
  • 네트워크 설정을 확인하고 안정적이고 빠른 인터넷 연결이 있는지 확인하십시오. 다른 네트워크로 전환하거나 유선 연결을 사용하거나 대역폭을 사용하는 장치 또는 응용 프로그램 수를 줄여야 할 수 있습니다.
  • If the issue persists, check out our persistent errors next steps section.
  • 문제가 지속되면 지속적인 오류 다음 단계 섹션을 확인하세요.

 

RateLimitError

 

A `RateLimitError` indicates that you have hit your assigned rate limit. This means that you have sent too many tokens or requests in a given period of time, and our services have temporarily blocked you from sending more.

 

'RateLimitError'는 할당된 rate limit에 도달했음을 나타냅니다. 이는 귀하가 주어진 기간 동안 너무 많은 토큰 또는 요청을 보냈고 당사 서비스가 일시적으로 귀하의 추가 전송을 차단했음을 의미합니다.

 

We impose rate limits to ensure fair and efficient use of our resources and to prevent abuse or overload of our services.

If you encounter a RateLimitError, please try the following steps:

 

당사는 자원의 공정하고 효율적인 사용을 보장하고 서비스의 남용 또는 과부하를 방지하기 위해 Rate limit을 부과합니다.

RateLimitError가 발생하면 다음 단계를 시도하십시오.

 

  • Send fewer tokens or requests or slow down. You may need to reduce the frequency or volume of your requests, batch your tokens, or implement exponential backoff. You can read our Rate limit guide for more details.
  • 더 적은 수의 토큰 또는 요청을 보내거나 속도를 늦추십시오. 요청의 빈도나 양을 줄이거나 토큰을 일괄 처리하거나 exponential backoff를 구현해야 할 수 있습니다. 자세한 내용은 Rate limit guide를 참조하세요.
  • Wait until your rate limit resets (one minute) and retry your request. The error message should give you a sense of your usage rate and permitted usage.
  • Rate Limit이 재설정될 때까지(1분) 기다렸다가 요청을 다시 시도하십시오. 오류 메시지는 사용률과 허용된 사용에 대한 정보를 제공해야 합니다.
  • You can also check your API usage statistics from your account dashboard.
  • 계정 대시보드에서 API 사용 통계를 확인할 수도 있습니다.

 

APIConnectionError

 

An `APIConnectionError` indicates that your request could not reach our servers or establish a secure connection. This could be due to a network issue, a proxy configuration, an SSL certificate, or a firewall rule.

 

APIConnectionError'는 요청이 OpenAI 서버에 도달하지 못하거나 보안 연결을 설정할 수 없음을 나타냅니다. 이는 네트워크 문제, 프록시 구성, SSL 인증서 또는 방화벽 규칙 때문일 수 있습니다.

 

If you encounter an APIConnectionError, please try the following steps:

APIConnectionError가 발생하면 다음 단계를 시도해 보세요.

  • Check your network settings and make sure you have a stable and fast internet connection. You may need to switch to a different network, use a wired connection, or reduce the number of devices or applications using your bandwidth.
  • 네트워크 설정을 확인하고 안정적이고 빠른 인터넷 연결이 있는지 확인하십시오. 다른 네트워크로 전환하거나 유선 연결을 사용하거나 대역폭을 사용하는 장치 또는 응용 프로그램 수를 줄여야 할 수 있습니다.
  • Check your proxy configuration and make sure it is compatible with our services. You may need to update your proxy settings, use a different proxy, or bypass the proxy altogether.
  • 프록시 구성을 확인하고 당사 서비스와 호환되는지 확인하십시오. 프록시 설정을 업데이트하거나 다른 프록시를 사용하거나 프록시를 모두 우회해야 할 수 있습니다.
  • Check your SSL certificates and make sure they are valid and up-to-date. You may need to install or renew your certificates, use a different certificate authority, or disable SSL verification.
  • SSL 인증서를 확인하고 유효하고 최신인지 확인하십시오. 인증서를 설치 또는 갱신하거나 다른 인증 기관을 사용하거나 SSL 확인을 비활성화해야 할 수 있습니다.
  • Check your firewall rules and make sure they are not blocking or filtering our services. You may need to modify your firewall settings.
  • 방화벽 규칙을 확인하고 당사 서비스를 차단하거나 필터링하지 않는지 확인하십시오. 방화벽 설정을 수정해야 할 수도 있습니다.
  • If appropriate, check that your container has the correct permissions to send and receive traffic.
  • 해당하는 경우 컨테이너에 트래픽을 보내고 받을 수 있는 올바른 권한이 있는지 확인하십시오.
  • If the issue persists, check out our persistent errors next steps section.
  • 문제가 지속되면 지속적인 오류 다음 단계 섹션을 확인하세요.

 

InvalidRequestError

 

An InvalidRequestError indicates that your request was malformed or missing some required parameters, such as a token or an input. This could be due to a typo, a formatting error, or a logic error in your code.

 

InvalidRequestError는 요청 형식이 잘못되었거나 토큰 또는 입력과 같은 일부 필수 매개변수가 누락되었음을 나타냅니다. 이는 코드의 오타, 형식 오류 또는 논리 오류 때문일 수 있습니다.

 

If you encounter an InvalidRequestError, please try the following steps:

 

InvalidRequestError가 발생하면 다음 단계를 시도하십시오.

 

  • Read the error message carefully and identify the specific error made. The error message should advise you on what parameter was invalid or missing, and what value or format was expected.
  • 오류 메시지를 주의 깊게 읽고 발생한 특정 오류를 식별하십시오. 오류 메시지는 어떤 매개변수가 잘못되었거나 누락되었는지, 어떤 값이나 형식이 예상되었는지 알려줍니다.
  • Check the API Reference for the specific API method you were calling and make sure you are sending valid and complete parameters. You may need to review the parameter names, types, values, and formats, and ensure they match the documentation.
  • 호출한 특정 API 메서드에 대한 API 참조를 확인하고 유효하고 완전한 매개변수를 보내고 있는지 확인하십시오. 매개변수 이름, 유형, 값 및 형식을 검토하고 문서와 일치하는지 확인해야 할 수 있습니다.
  • Check the encoding, format, or size of your request data and make sure they are compatible with our services. You may need to encode your data in UTF-8, format your data in JSON, or compress your data if it is too large.
  • 요청 데이터의 인코딩, 형식 또는 크기를 확인하고 당사 서비스와 호환되는지 확인하십시오. 데이터를 UTF-8로 인코딩하거나 데이터를 JSON 형식으로 지정하거나 데이터가 너무 큰 경우 데이터를 압축해야 할 수 있습니다.
  • Test your request using a tool like Postman or curl and make sure it works as expected. You may need to debug your code and fix any errors or inconsistencies in your request logic.
  • Postman 또는 curl과 같은 도구를 사용하여 요청을 테스트하고 예상대로 작동하는지 확인하십시오. 코드를 디버깅하고 요청 논리의 오류나 불일치를 수정해야 할 수 있습니다.
  • If the issue persists, check out our persistent errors next steps section.
  • 문제가 지속되면 지속적인 오류 다음 단계 섹션을 확인하세요.

 

AuthenticationError

 

An `AuthenticationError` indicates that your API key or token was invalid, expired, or revoked. This could be due to a typo, a formatting error, or a security breach.

 

'AuthenticationError'는 API 키 또는 토큰이 유효하지 않거나 만료되었거나 취소되었음을 나타냅니다. 이는 오타, 형식 오류 또는 보안 위반 때문일 수 있습니다.

 

If you encounter an AuthenticationError, please try the following steps:

 

인증 오류가 발생하면 다음 단계를 시도하십시오.

 

  • Check your API key or token and make sure it is correct and active. You may need to generate a new key from the API Key dashboard, ensure there are no extra spaces or characters, or use a different key or token if you have multiple ones.
  • API 키 또는 토큰을 확인하고 올바르고 활성화되어 있는지 확인하십시오. API 키 대시보드에서 새 키를 생성하거나, 추가 공백이나 문자가 없는지 확인하거나, 키나 토큰이 여러 개인 경우 다른 키나 토큰을 사용해야 할 수 있습니다.
  • Ensure that you have followed the correct formatting.
  • 올바른 형식을 따랐는지 확인하십시오.

 

ServiceUnavailableError

 

A `ServiceUnavailableError` indicates that our servers are temporarily unable to handle your request. This could be due to a planned or unplanned maintenance, a system upgrade, or a server failure. These errors can also be returned during periods of high traffic.

 

'ServiceUnavailableError'는 서버가 일시적으로 귀하의 요청을 처리할 수 없음을 나타냅니다. 이는 계획되거나 계획되지 않은 유지 관리, 시스템 업그레이드 또는 서버 오류 때문일 수 있습니다. 이러한 오류는 트래픽이 많은 기간에도 반환될 수 있습니다.

 

We apologize for any inconvenience and we are working hard to restore our services as soon as possible.

If you encounter a ServiceUnavailableError, please try the following steps:

 

불편을 끼쳐 드려 죄송하며 최대한 빨리 서비스를 복구하기 위해 노력하고 있습니다.

  • Wait a few minutes and retry your request. Sometimes, the issue may be resolved quickly and your request may succeed on the next attempt.
  • 몇 분 정도 기다린 후 요청을 다시 시도하십시오. 경우에 따라 문제가 빠르게 해결되고 다음 시도에서 요청이 성공할 수 있습니다.
  • Check our status page for any ongoing incidents or maintenance that may affect our services. If there is an active incident, please follow the updates and wait until it is resolved before retrying your request.
  • 당사 서비스에 영향을 미칠 수 있는 진행 중인 사건이나 유지 보수에 대해서는 상태 페이지를 확인하십시오. 활성 사고가 있는 경우 업데이트를 따르고 요청을 다시 시도하기 전에 문제가 해결될 때까지 기다리십시오.
  • If the issue persists, check out our persistent errors next steps section.
  • 문제가 지속되면 지속적인 오류 다음 단계 섹션을 확인하세요.

Persistent errors

If the issue persists, contact our support team via chat and provide them with the following information:

문제가 지속되면 채팅을 통해 지원 팀에 연락하고 다음 정보를 제공하십시오.

  • The model you were using
  • The error message and code you received
  • The request data and headers you sent
  • The timestamp and timezone of your request
  • Any other relevant details that may help us diagnose the issue

Our support team will investigate the issue and get back to you as soon as possible. Note that our support queue times may be long due to high demand. You can also post in our Community Forum but be sure to omit any sensitive information.

 

지원팀에서 문제를 조사하고 최대한 빨리 답변을 드릴 것입니다. 수요가 많기 때문에 지원 대기 시간이 길어질 수 있습니다. 커뮤니티 포럼에 게시할 수도 있지만 민감한 정보는 생략해야 합니다.

 

Handling errors

We advise you to programmatically handle errors returned by the API. To do so, you may want to use a code snippet like below:

 

API에서 반환된 오류를 프로그래밍 방식으로 처리하는 것이 좋습니다. 이렇게 하려면 아래와 같은 코드 스니펫을 사용할 수 있습니다.

 

 

반응형

'Open AI > GUIDES' 카테고리의 다른 글

Guide - Rate limits  (0) 2023.03.05
Guide - Speech to text  (0) 2023.03.05
Guide - Chat completion (ChatGPT API)  (0) 2023.03.05
Guides - Production Best Practices  (0) 2023.01.10
Guides - Safety best practices  (0) 2023.01.10
Guides - Moderation  (0) 2023.01.10
Guides - Embeddings  (0) 2023.01.10
Guides - Fine tuning  (0) 2023.01.10
Guide - Image generation  (0) 2023.01.09
Guide - Code completion  (0) 2023.01.09
이전 1 2 3 4 5 6 ··· 8 다음