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

최근에 받은 트랙백

글 보관함

Introduction - PlugIn flow

2023. 3. 25. 11:27 | Posted by 솔웅


반응형

https://platform.openai.com/docs/plugins/introduction

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

Chat Plugins 

Limited Alpha

Learn how to build a plugin that allows ChatGPT to intelligently call your API.

 

ChatGPT가 API를 지능적으로 call 할 수 있도록 하는 플러그인을 빌드하는 방법을 알아보세요.

 

Introduction

OpenAI plugins connect ChatGPT to third-party applications. These plugins enable ChatGPT to interact with APIs defined by developers, enhancing ChatGPT's capabilities and allowing it to perform a wide range of actions.

 

OpenAI 플러그인은 ChatGPT를 타사 애플리케이션에 연결합니다. 이러한 플러그인을 통해 ChatGPT는 개발자가 정의한 API와 상호 작용하여 ChatGPT의 기능을 향상하고 광범위한 작업을 수행할 수 있습니다.

 

  • Plugins can allow ChatGPT to do things like:
  • 플러그인을 통해 ChatGPT는 다음과 같은 작업을 수행할 수 있습니다.
  • Retrieve real-time information; e.g., sports scores, stock prices, the latest news, etc.
  • 실시간 정보 검색 예: 스포츠 점수, 주가, 최신 뉴스 등
  • Retrieve knowledge-base information; e.g., company docs, personal notes, etc.
  • 지식 기반 정보를 검색합니다. 예: 회사 문서, 개인 메모 등
  • Perform actions on behalf of the user; e.g., booking a flight, ordering food, etc.
  • 사용자를 대신하여 작업을 수행합니다. 예: 비행기 예약, 음식 주문 등

 

Plugins are in a limited alpha and may not yet be accessible to you. Please join the waitlist to get access. During the alpha, we will be working closely with users and developers to iterate on the plugin system, which may evolve significantly.

 

플러그인은 제한된 알파 상태이며 아직 액세스할 수 없을겁니다. 액세스하려면 대기자 명단에 등록하십시오. 알파 기간 동안 우리는 사용자 및 개발자와 긴밀히 협력하여 크게 발전할 수 있는 플러그인 시스템을 반복할 것입니다.

 

Plugin developers expose one or more API endpoints, accompanied by a standardized manifest file and an OpenAPI specification. These define the plugin's functionality, allowing ChatGPT to consume the files and make calls to the developer-defined APIs.

 

플러그인 개발자는 표준화된 매니페스트 파일 및 OpenAPI 사양과 함께 하나 이상의 API 엔드포인트를 노출합니다. 이들은 플러그인의 기능을 정의하여 ChatGPT가 파일을 사용하고 개발자 정의 API를 호출할 수 있도록 합니다.

 

The AI model acts as an intelligent API caller. Given an API spec and a natural-language description of when to use the API, the model proactively calls the API to perform actions. For instance, if a user asks, "Where should I stay in Paris for a couple nights?", the model may choose to call a hotel reservation plugin API, receive the API response, and generate a user-facing answer combining the API data and its natural language capabilities.

 

AI 모델은 지능형 API 호출자 역할을 합니다. API 사양과 API 사용 시기에 대한 자연어 설명이 주어지면 모델은 사전에 API를 호출하여 작업을 수행합니다. 예를 들어 사용자가 "파리에서 며칠 밤을 묵어야 합니까?"라고 묻는 경우 모델은 호텔 예약 플러그인 API를 호출하고 API 응답을 수신하고 API 데이터를 결합한 사용자 대면 답변을 생성하도록 선택할 수 있습니다. 그리고 ChatGPT의 자연 언어 기능으로 이를 처리 할 것입니다.

 

Over time, we anticipate the system will evolve to accommodate more advanced use cases.

 

시간이 지남에 따라 시스템이 고급 사용 사례를 수용하도록 발전할 것으로 예상합니다.

 

Plugin flow

To build a plugin, it is important to understand the end-to-end flow.

 

플러그인을 구축하려면 end-to-end 흐름을 이해하는 것이 중요합니다.

 

  1. Create a manifest file and host it at yourdomain.com/.well-known/ai-plugin.json
    매니페스트 파일을 만들고 yourdomain.com/.well-known/ai-plugin.json에서 호스트합니다. 
    • The file includes metadata about your plugin (name, logo, etc.), details about authentication required (type of auth, OAuth URLs, etc.), and an OpenAPI spec for the endpoints you want to expose.
    • 이 파일에는 플러그인에 대한 메타데이터(이름, 로고 등), 필요한 인증에 대한 세부 정보(인증 유형, OAuth URL 등), 노출하려는 엔드포인트에 대한 OpenAPI 사양이 포함됩니다.
    • The model will see the OpenAPI description fields, which can be used to provide a natural language description for the different fields.
    • 모델은 다양한 필드에 대한 자연어 설명을 제공하는 데 사용할 수 있는 OpenAPI 설명 필드를 볼 수 있습니다.
    • We suggest exposing only 1-2 endpoints in the beginning with a minimum number of parameters to minimize the length of the text. The plugin description, API requests, and API responses are all inserted into the conversation with ChatGPT. This counts against the context limit of the model.
    • 텍스트 길이를 최소화하기 위해 최소한의 매개변수로 처음에 1-2개의 endpoint만 노출하는 것이 좋습니다. 플러그인 설명, API 요청 및 API 응답은 모두 ChatGPT와의 대화에 삽입됩니다. 이는 모델의 컨텍스트 제한에 포함됩니다.

 

  1. Register your plugin in the ChatGPT UI
    • Select the plugin model from the top drop down, then select “Plugins”, “Plugin Store”, and finally “Install an unverified plugin” or “Develop your own plugin”.
    • 상단 드롭다운에서 플러그인 모델을 선택한 다음 "플러그인", "플러그인 스토어"를 선택하고 마지막으로 "확인되지 않은 플러그인 설치" 또는 "자체 플러그인 개발"을 선택합니다.
    • If authentication is required, provide an OAuth 2 client_id and client_secret or an API key 
    • 인증이 필요한 경우 OAuth 2 client_id 및 client_secret 또는 API 키를 제공하십시오.

 

  1. Users activate your plugin
    사용자가 플러그인을 활성화합니다. 
    • Users must manually activate your plugin in the ChatGPT UI. (ChatGPT will not use your plugin by default.)
    • 사용자는 ChatGPT UI에서 플러그인을 수동으로 활성화해야 합니다. (ChatGPT는 기본적으로 플러그인을 사용하지 않습니다.)
    • During the alpha, plugin developers will be able to share their plugin with 15 additional users (only other developers can install unverified plugins currently). Overtime we will roll out a way to submit your plugin for review to be exposed to all of ChatGPT’s user base.
    • 알파 기간 동안 플러그인 개발자는 15명의 추가 사용자와 플러그인을 공유할 수 있습니다(현재 다른 개발자만 확인되지 않은 플러그인을 설치할 수 있음). 시간이 지나면 모든 ChatGPT 사용자 기반에 노출될 검토를 위해 플러그인을 제출하는 방법을 출시할 것입니다.
    • If auth is required, users will be redirected via OAuth to your plugin; you can optionally create new accounts here as well.
    • 인증이 필요한 경우 사용자는 OAuth를 통해 플러그인으로 리디렉션됩니다. 선택적으로 여기에서 새 계정을 만들 수도 있습니다.
    • In the future, we hope to build features to help users discover useful & popular plugins.
    • 앞으로는 사용자가 유용하고 인기 있는 플러그인을 찾는 데 도움이 되는 기능을 구축할 수 있기를 바랍니다.

 

  1. Users begin a conversation
    • OpenAI will inject a compact description of your plugin in a message to ChatGPT, invisible to end users. This will include the plugin description, endpoints, and examples.
    • OpenAI는 최종 사용자에게 보이지 않는 ChatGPT 메시지에 플러그인에 대한 간략한 설명을 삽입합니다. 여기에는 플러그인 설명, 끝점 및 예제가 포함됩니다.
    • When a user asks a relevant question, the model may choose to invoke an API call from your plugin if it seems relevant; for POST requests, we require that developers build a user confirmation flow.
    • 사용자가 관련 질문을 할 때 모델은 관련이 있다고 판단되면 플러그인에서 API call을 호출하도록 선택할 수 있습니다. POST 요청의 경우 개발자가 사용자 확인 흐름을 구축해야 합니다.
    • The model will incorporate the API results into its response to the user.
    • 모델은 API 결과를 사용자에 대한 응답에 통합합니다.
    • The model might include links returned from API calls in its response. These will be displayed as rich previews (using the OpenGraph protocol, where we pull the site_name, title, description, image, and url fields)"
    • 모델은 응답에 API 호출에서 반환된 링크를 포함할 수 있습니다. 풍부한 미리보기로 표시됩니다(Site_name, 제목, 설명, 이미지 및 URL 필드를 가져오는 OpenGraph 프로토콜 사용)"

 

Currently, we will be sending the user’s country and state in the Plugin conversation header (if you are in California for example, it would look like {"openai-subdivision-1-iso-code": "US-CA"}. For further data sources, users will have to opt in via a consent screen. This is useful for shopping, restaurants, weather, and more. You can read more in our developer terms of use.

 

현재 플러그인 대화 헤더에 사용자의 국가와 주를 보낼 예정입니다(예를 들어 캘리포니아에 있는 경우 {"openai-subdivision-1-iso-code": "US-CA"}와 같이 표시됨). 추가 데이터 소스를 사용하려면 사용자가 동의 화면을 통해 선택해야 합니다. 이것은 쇼핑, 레스토랑, 날씨 등에 유용합니다. 개발자 사용 약관에서 자세한 내용을 읽을 수 있습니다.

 

반응형

Comment


반응형

Azure OpenAI를 사용하려면 해당 서비스를 사용할 수 있는 권한을 Microsoft 사로부터 얻어야 합니다.

저는 공부 목적으로 필요하다고 신청했는데 거부 됐습니다.

 

 

실제 이 Azure OpenAI를 이용해서 제품을 개발하고자 한다면 한번 신청해 보세요.

신청 방법은 아래 글에 정리 해 놨습니다.

https://coronasdk.tistory.com/1304

 

Azure OpenAI 를 사용하기 위한 사전 요구 사항들 - 사용 요청 거부 됨

OpenAI CookBook 을 거의 다 공부하고 Azure OpenAI 를 공부할 차례 입니다. https://github.com/openai/openai-cookbook GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API Examples and guides for using the OpenAI API. C

coronasdk.tistory.com

 

저는 일단 실습은 못하고 Cookbook에 있는 글로 공부해 보겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/azure/finetuning.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

 

Azure Fine tuning example

In this example we'll try to go over all operations that can be done using the Azure endpoints and their differences with the openAI endpoints (if any).

 

이 예제에서는 Azure endpoints 를  사용하여 수행할 수 있는 모든 작업과 openAI endpoints  (있는 경우)과의 차이점을 살펴보겠습니다.


This example focuses on finetuning but also touches on the majority of operations that are available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a finetune model adaptation tutorial.

 

이 예제는 finetuning에 중점을 두지만 API를 사용하여 사용할 수 있는 대부분의 작업도 다룹니다. 이 예제는 간단한 작업을 빠르게 보여주기 위한 것이며 finetuning 모델 적용 튜토리얼이 아닙니다.

 

import openai
from openai import cli

 

Setup

For the following sections to work properly we first have to setup some things. Let's start with the api_base and api_version. To find your api_base go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for the "Endpoint" value.

 

다음 섹션이 제대로 작동하려면 먼저 몇 가지를 설정해야 합니다. api_base 및 api_version부터 시작하겠습니다. api_base를 찾으려면 https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints"에서 "Endpoint" 값을 찾습니다.

 

openai.api_version = '2022-12-01'
openai.api_base = '' # Please add your endpoint here

 

We next have to setup the api_type and api_key. We can either get the key from the portal or we can get it through Microsoft Active Directory Authentication. Depending on this the api_type is either azure or azure_ad.

 

다음으로 api_type 및 api_key를 설정해야 합니다. 포털에서 키를 얻거나 Microsoft Active Directory 인증을 통해 얻을 수 있습니다. 이에 따라 api_type은 azure 또는 azure_ad입니다.

 

Setup: Portal

Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for one of the "Keys" values.

 

먼저 포털에서 키를 가져오는 방법을 살펴보겠습니다. https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints"에서 "Keys" 값 중 하나를 찾습니다.

 

openai.api_type = 'azure'
openai.api_key = ''  # Please add your api key here

(Optional) Setup: Microsoft Active Directory Authentication

Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal.

 

(선택 사항) 설정: Microsoft Active Directory 인증
이제 Microsoft Active Directory 인증을 통해 키를 얻는 방법을 살펴보겠습니다. 포털의 키 대신 Active Directory 인증을 사용하려면 다음 코드의 주석을 제거하십시오.

 

# from azure.identity import DefaultAzureCredential

# default_credential = DefaultAzureCredential()
# token = default_credential.get_token("https://cognitiveservices.azure.com/.default")

# openai.api_type = 'azure_ad'
# openai.api_key = token.token

 

Files

In the next section we will focus on the files operations: importing, listing, retrieving, deleting. For this we need to create 2 temporary files with some sample data. For the sake of simplicity, we will use the same data for training and validation.

 

다음 섹션에서는 가져오기, 나열, 검색, 삭제와 같은 파일 작업에 중점을 둘 것입니다. 이를 위해 일부 샘플 데이터로 2개의 임시 파일을 생성해야 합니다. 단순화를 위해 교육 및 검증에 동일한 데이터를 사용합니다.

 

import shutil
import json

training_file_name = 'training.jsonl'
validation_file_name = 'validation.jsonl'

sample_data = [{"prompt": "When I go to the store, I want an", "completion": "apple."},
    {"prompt": "When I go to work, I want a", "completion": "coffee."},
    {"prompt": "When I go home, I want a", "completion": "soda."}]

print(f'Generating the training file: {training_file_name}')
with open(training_file_name, 'w') as training_file:
    for entry in sample_data:
        json.dump(entry, training_file)
        training_file.write('\n')

print(f'Copying the training file to the validation file')
shutil.copy(training_file_name, validation_file_name)

 

Files: Listing

List all of the uploaded files and check for the ones that are named "training.jsonl" or "validation.jsonl"

 

업로드된 모든 파일을 나열하고 이름이 "training.jsonl" 또는 "validation.jsonl"인 파일을 확인합니다.

 

print('Checking for existing uploaded files.')
results = []
files = openai.File.list().data
print(f'Found {len(files)} total uploaded files in the subscription.')
for item in files:
    if item["filename"] in [training_file_name, validation_file_name]:
        results.append(item["id"])
print(f'Found {len(results)} already uploaded files that match our names.')

 

Files: Deleting

Let's now delete those found files (if any) since we're going to be re-uploading them next.

 

다음에 다시 업로드할 예정이므로 찾은 파일(있는 경우)을 삭제하겠습니다.

 

print(f'Deleting already uploaded files...')
for id in results:
    openai.File.delete(sid = id)

 

Files: Importing & Retrieving

Now, let's import our two files ('training.jsonl' and 'validation.jsonl') and keep those IDs since we're going to use them later for finetuning.

 

이제 두 파일('training.jsonl' 및 'validation.jsonl')을 가져오고 나중에 미세 조정에 사용할 것이므로 해당 ID를 유지하겠습니다.


For this operation we are going to use the cli wrapper which does a bit more checks before uploading and also gives us progress. In addition, after uploading we're going to check the status our import until it has succeeded (or failed if something goes wrong)

 

이 작업을 위해 업로드하기 전에 조금 더 확인하고 진행률을 제공하는 cli 래퍼를 사용할 것입니다. 또한 업로드 후 가져오기가 성공할 때까지(또는 무언가 잘못되면 실패할 때까지) 가져오기 상태를 확인합니다.

 

import time

def check_status(training_id, validation_id):
    train_status = openai.File.retrieve(training_id)["status"]
    valid_status = openai.File.retrieve(validation_id)["status"]
    print(f'Status (training_file | validation_file): {train_status} | {valid_status}')
    return (train_status, valid_status)

#importing our two files
training_id = cli.FineTune._get_or_upload(training_file_name, True)
validation_id = cli.FineTune._get_or_upload(validation_file_name, True)

#checking the status of the imports
(train_status, valid_status) = check_status(training_id, validation_id)

while train_status not in ["succeeded", "failed"] or valid_status not in ["succeeded", "failed"]:
    time.sleep(1)
    (train_status, valid_status) = check_status(training_id, validation_id)

 

Files: Downloading

Now let's download one of the files, the training file for example, to check that everything was in order during importing and all bits are there.

 

이제 파일 중 하나(예: 교육 파일)를 다운로드하여 가져오는 동안 모든 것이 제대로 작동하고 모든 비트가 있는지 확인합니다.

 

print(f'Downloading training file: {training_id}')
result = openai.File.download(training_id)
print(result.decode('utf-8'))

 

Finetune

In this section we are going to use the two training and validation files that we imported in the previous section, to train a finetune model.

 

이 섹션에서는 finetune  모델을 교육하기 위해 이전 섹션에서 가져온 두 개의 교육 및 검증 파일을 사용할 것입니다.

 

 

Finetune: Adapt

First let's create the finetune adaptation job.

먼저 미세 조정 적응 작업을 생성해 보겠습니다.

 

create_args = {
    "training_file": training_id,
    "validation_file": validation_id,
    "model": "babbage",
    "compute_classification_metrics": True,
    "classification_n_classes": 3,
    "n_epochs": 20,
    "batch_size": 3,
    "learning_rate_multiplier": 0.3
}
resp = openai.FineTune.create(**create_args)
job_id = resp["id"]
status = resp["status"]

print(f'Fine-tunning model with jobID: {job_id}.')

 

Finetune: Streaming

While the job runs, we can subscribe to the streaming events to check the progress of the operation.

작업이 실행되는 동안 스트리밍 이벤트를 구독하여 작업 진행 상황을 확인할 수 있습니다.

 

 

import signal
import datetime

def signal_handler(sig, frame):
    status = openai.FineTune.retrieve(job_id).status
    print(f"Stream interrupted. Job is still {status}.")
    return

print(f'Streaming events for the fine-tuning job: {job_id}')
signal.signal(signal.SIGINT, signal_handler)

events = openai.FineTune.stream_events(job_id)
try:
    for event in events:
        print(f'{datetime.datetime.fromtimestamp(event["created_at"])} {event["message"]}')

except Exception:
    print("Stream interrupted (client disconnected).")

 

Finetune: Listing and Retrieving

Now let's check that our operation was successful and in addition we can look at all of the finetuning operations using a list operation.

이제 작업이 성공했는지 확인하고 목록 작업을 사용하여 모든 finetune  작업을 볼 수 있습니다.

 

status = openai.FineTune.retrieve(id=job_id)["status"]
if status not in ["succeeded", "failed"]:
    print(f'Job not in terminal status: {status}. Waiting.')
    while status not in ["succeeded", "failed"]:
        time.sleep(2)
        status = openai.FineTune.retrieve(id=job_id)["status"]
        print(f'Status: {status}')
else:
    print(f'Finetune job {job_id} finished with status: {status}')

print('Checking other finetune jobs in the subscription.')
result = openai.FineTune.list()
print(f'Found {len(result.data)} finetune jobs.')

 

Finetune: Deleting

Finally we can delete our finetune job.
WARNING: Please skip this step if you want to continue with the next section as the finetune model is needed. (The delete code is commented out by default)

 

마지막으로 finetune  작업을 삭제할 수 있습니다.
경고: finetune 모델이 필요하므로 다음 섹션을 계속하려면 이 단계를 건너뛰십시오. (삭제 코드는 기본적으로 주석 처리됨)

 

# openai.FineTune.delete(sid=job_id)

 

Deployments

In this section we are going to create a deployment using the finetune model that we just adapted and then used the deployment to create a simple completion operation.

 

이 섹션에서는 방금 수정한 finetune  모델을 사용하여 deployment 를 생성한 다음 deployment 를 사용하여 간단한 completion  작업을 생성할 것입니다.

 

Deployments: Create

Let's create a deployment using the fine-tune model.

fine-tune모델을 사용하여 deployment 를 생성해 보겠습니다.

 

#Fist let's get the model of the previous job:
result = openai.FineTune.retrieve(id=job_id)
if result["status"] == 'succeeded':
    model = result["fine_tuned_model"]

# Now let's create the deployment
print(f'Creating a new deployment with model: {model}')
result = openai.Deployment.create(model=model, scale_settings={"scale_type":"standard"})
deployment_id = result["id"]

 

Deployments: Retrieving

Now let's check the status of the newly created deployment

이제 새로 생성된 배포의 상태를 확인하겠습니다.

 

print(f'Checking for deployment status.')
resp = openai.Deployment.retrieve(id=deployment_id)
status = resp["status"]
print(f'Deployment {deployment_id} is with status: {status}')

Deployments: Listing

Now because creating a new deployment takes a long time, let's look in the subscription for an already finished deployment that succeeded.

이제 새 deployment를 만드는 데 시간이 오래 걸리므로 이미 완료된 deployment에 대한 subscription 을 살펴보겠습니다.

 

print('While deployment running, selecting a completed one.')
deployment_id = None
result = openai.Deployment.list()
for deployment in result.data:
    if deployment["status"] == "succeeded":
        deployment_id = deployment["id"]
        break

if not deployment_id:
    print('No deployment with status: succeeded found.')
else:
    print(f'Found a successful deployment with id: {deployment_id}.')

 

Completions

Now let's send a sample completion to the deployment.

이제 deployment에 샘플 completion 을 보내겠습니다.

 

print('Sending a test completion job')
start_phrase = 'When I go home, I want a'
response = openai.Completion.create(deployment_id=deployment_id, prompt=start_phrase, temperature=0, stop=".")
text = response['choices'][0]['text'].replace('\n', '').replace(' .', '.').strip()
print(f'"{start_phrase} {text}."')

 

Deployments: Delete

Finally let's delete the deployment

마지막으로 deployment를 삭제하겠습니다.

 

print(f'Deleting deployment: {deployment_id}')
openai.Deployment.delete(sid=deployment_id)

 

반응형

Comment


반응형

Azure OpenAI를 사용하려면 해당 서비스를 사용할 수 있는 권한을 Microsoft 사로부터 얻어야 합니다.

저는 공부 목적으로 필요하다고 신청했는데 거부 됐습니다.

 

 

실제 이 Azure OpenAI를 이용해서 제품을 개발하고자 한다면 한번 신청해 보세요.

 

신청 방법은 아래 글에 정리 해 놨습니다.

 

https://coronasdk.tistory.com/1304

 

Azure OpenAI 를 사용하기 위한 사전 요구 사항들 - 사용 요청 거부 됨

OpenAI CookBook 을 거의 다 공부하고 Azure OpenAI 를 공부할 차례 입니다. https://github.com/openai/openai-cookbook GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API Examples and guides for using the OpenAI API. C

coronasdk.tistory.com

 

저는 일단 실습은 못하고 Cookbook에 있는 글로 공부해 보겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.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

 

 

참고로 Azure OpenAI Embeddings + Search 관련 유투브 클립입니다.

 

https://www.youtube.com/watch?v=ocxq84ocYi0 

 

아래부터 Cookbook 내용입니다.

 

Azure embeddings example

 

In this example we'll try to go over all operations for embeddings that can be done using the Azure endpoints.
This example focuses on embeddings but also touches some other operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a tutorial.

 

이 예제에서는 Azure endpoints를 사용하여 수행할 수 있는 embeddings 에 대한 작업을 살펴보겠습니다.
이 예제는 임베딩에 중점을 두지만 API를 사용하여 사용할 수 있는 다른 작업도 다룹니다. 이 예제는 간단한 작업을 보여주는 빠른 방법이며 튜토리얼이 아닙니다.

 

import openai
from openai import cli

Setup

For the following sections to work properly we first have to setup some things. Let's start with the api_base and api_version. To find your api_base go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for the "Endpoint" value.

 

다음 섹션이 제대로 작동하려면 먼저 몇 가지를 설정해야 합니다. api_base 및 api_version부터 시작하겠습니다. api_base를 찾으려면 https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints" 에서 "Endpoint" 값을 찾습니다.

 

openai.api_version = '2022-12-01'
openai.api_base = '' # Please add your endpoint here

다음으로 api_type 및 api_key를 설정해야 합니다. 포털에서 키를 얻거나 Microsoft Active Directory 인증을 통해 얻을 수 있습니다. 이에 따라 api_type은 azure 또는 azure_ad입니다.

 

Setup: Portal

Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for one of the "Keys" values.

 

먼저 포털에서 키를 가져오는 방법을 살펴보겠습니다. https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints"에서 "Keys" 값 중 하나를 찾습니다.

 

openai.api_type = 'azure'
openai.api_key = ''  # Please add your api key here

(Optional) Setup: Microsoft Active Directory Authentication

Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal.

 

(선택 사항) 설정: Microsoft Active Directory 인증
이제 Microsoft Active Directory 인증을 통해 키를 얻는 방법을 살펴보겠습니다. 포털의 키 대신 Active Directory 인증을 사용하려면 다음 코드의 주석을 제거하십시오.

 

# from azure.identity import DefaultAzureCredential

# default_credential = DefaultAzureCredential()
# token = default_credential.get_token("https://cognitiveservices.azure.com/.default")

# openai.api_type = 'azure_ad'
# openai.api_key = token.token

 

Deployments

In this section we are going to create a deployment that we can use to create embeddings.

이 섹션에서는 embeddings을 만드는 데 사용할 수 있는 deployment 를 만들 것입니다.

 

Deployments: Create manually

Let's create a deployment using the text-similarity-curie-001 model. Create a new deployment by going to your Resource in your portal under "Resource Management" -> "Model deployments".

text-similarity-curie-001 모델을 사용하여 배포를 생성해 보겠습니다. "Resource Management" -> "Model deployments"에서 포털의 리소스로 이동하여 새 deployment를 만듭니다.

 

(Optional) Deployments: Create programatically

We can also create a deployment using code:

코드를 사용하여 deployment 를 만들 수도 있습니다.

 

model = "text-similarity-curie-001"

# Now let's create the deployment
print(f'Creating a new deployment with model: {model}')
result = openai.Deployment.create(model=model, scale_settings={"scale_type":"standard"})
deployment_id = result["id"]

 

(Optional) Deployments: Retrieving

Now let's check the status of the newly created deployment

이제 새로 생성된 배포의 상태를 확인하겠습니다.

print(f'Checking for deployment status.')
resp = openai.Deployment.retrieve(id=deployment_id)
status = resp["status"]
print(f'Deployment {deployment_id} is with status: {status}')

 

Deployments: Listing

Now because creating a new deployment takes a long time, let's look in the subscription for an already finished deployment that succeeded.

이제 새 deployment 를 만드는 데 시간이 오래 걸리므로 이미 완료된 deployment 에 대한 subscription 을 살펴보겠습니다.

 

print('While deployment running, selecting a completed one that supports embeddings.')
deployment_id = None
result = openai.Deployment.list()
for deployment in result.data:
    if deployment["status"] != "succeeded":
        continue
    
    model = openai.Model.retrieve(deployment["model"])
    if model["capabilities"]["embeddings"] != True:
        continue
    
    deployment_id = deployment["id"]
    break

if not deployment_id:
    print('No deployment with status: succeeded found.')
else:
    print(f'Found a succeeded deployment that supports embeddings with id: {deployment_id}.')

 

Embeddings

Now let's send a sample embedding to the deployment.

이제 배포에 샘플 임베딩을 보내겠습니다.

 

embeddings = openai.Embedding.create(deployment_id=deployment_id,
                                     input="The food was delicious and the waiter...")
                                
print(embeddings)

 

(Optional) Deployments: Delete

Finally let's delete the deployment

 

마지막으로 deployment를 삭제하겠습니다.

 

 

 

 

반응형

Comment


반응형

Azure OpenAI를 사용하려면 해당 서비스를 사용할 수 있는 권한을 Microsoft 사로부터 얻어야 합니다.

저는 공부 목적으로 필요하다고 신청했는데 거부 됐습니다.

 

 

실제 이 Azure OpenAI를 이용해서 제품을 개발하고자 한다면 한번 신청해 보세요.

 

신청 방법은 아래 글에 정리 해 놨습니다.

 

https://coronasdk.tistory.com/1304

 

Azure OpenAI 를 사용하기 위한 사전 요구 사항들 - 사용 요청 거부 됨

OpenAI CookBook 을 거의 다 공부하고 Azure OpenAI 를 공부할 차례 입니다. https://github.com/openai/openai-cookbook GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API Examples and guides for using the OpenAI API. C

coronasdk.tistory.com

 

저는 일단 실습은 못하고 Cookbook에 있는 글로 공부해 보겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/azure/completions.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

 

Azure completions example

 

In this example we'll try to go over all operations needed to get completions working using the Azure endpoints.
This example focuses on completions but also touches on some other operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a tutorial.

 

이 예제에서는 Azure 엔드포인트를 사용하여 작업을 completions 하는 데 필요한 모든 작업을 살펴보겠습니다.
이 예제는 completions 에 중점을 두지만 API를 사용하여 사용할 수 있는 다른 작업도 다룹니다. 이 예제는 간단한 작업을 보여주는 빠른 방법이며 튜토리얼이 아닙니다.

 

import openai
from openai import cli

 

Setup

For the following sections to work properly we first have to setup some things. Let's start with the api_base and api_version. To find your api_base go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for the "Endpoint" value.

 

다음 섹션이 제대로 작동하려면 먼저 몇 가지를 설정해야 합니다. api_base 및 api_version부터 시작하겠습니다. api_base를 찾으려면 https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "리소스 관리" -> ""Keys and Endpoints""에서 "Endpoint" 값을 찾습니다.

 

==> 이 부분이 Azure OpenAI 사용 권한이 필요한 부분 입니다.

 

openai.api_version = '2022-12-01'
openai.api_base = '' # Please add your endpoint here

 

다음으로 api_type 및 api_key를 설정해야 합니다. 포털에서 키를 얻거나 Microsoft Active Directory 인증을 통해 얻을 수 있습니다. 이에 따라 api_type은 azure 또는 azure_ad입니다.

 

Setup: Portal

Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for one of the "Keys" values.

 

먼저 포털에서 키를 가져오는 방법을 살펴보겠습니다. https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints"에서 "Keys" 값 중 하나를 찾습니다.

 

openai.api_type = 'azure'
openai.api_key = ''  # Please add your api key here

 

(Optional) Setup: Microsoft Active Directory Authentication

Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal.

 

(선택 사항) 설정: Microsoft Active Directory 인증
이제 Microsoft Active Directory 인증을 통해 키를 얻는 방법을 살펴보겠습니다. 포털의 키 대신 Active Directory 인증을 사용하려면 다음 코드의 주석을 제거하십시오.

 

# from azure.identity import DefaultAzureCredential

# default_credential = DefaultAzureCredential()
# token = default_credential.get_token("https://cognitiveservices.azure.com/.default")

# openai.api_type = 'azure_ad'
# openai.api_key = token.token

 

Deployments

In this section we are going to create a deployment using the text-davinci-002 model that we can then use to create completions.

이 섹션에서는 completions 를 생성하는 데 사용할 수 있는 text-davinci-002 모델을 사용하여 배포를 생성할 것입니다.

 

 

Deployments: Create manually

Create a new deployment by going to your Resource in your portal under "Resource Management" -> "Model deployments". Select text-davinci-002 as the model.

 

"리소스 관리" -> "모델 배포"에서 포털의 리소스로 이동하여 새 배포를 만듭니다. text-davinci-002를 모델로 선택합니다.

 

(Optional) Deployments: Create programatically

We can also create a deployment using code:

코드를 사용하여 배포를 만들 수도 있습니다.

 

model = "text-davinci-002"

# Now let's create the deployment
print(f'Creating a new deployment with model: {model}')
result = openai.Deployment.create(model=model, scale_settings={"scale_type":"standard"})
deployment_id = result["id"]
print(f'Successfully created deployment with id: {deployment_id}')

 

(Optional) Deployments: Wait for deployment to succeed

Now let's check the status of the newly created deployment and wait till it is succeeded.

 

이제 새로 생성된 배포의 상태를 확인하고 성공할 때까지 기다리겠습니다.

 

print(f'Checking for deployment status.')
resp = openai.Deployment.retrieve(id=deployment_id)
status = resp["status"]
print(f'Deployment {deployment_id} has status: {status}')
while status not in ["succeeded", "failed"]:
    resp = openai.Deployment.retrieve(id=deployment_id)
    status = resp["status"]
    print(f'Deployment {deployment_id} has status: {status}')

 

Completions

Now let's send a sample completion to the deployment.

 

이제 배포에 샘플 완료를 보내겠습니다.

 

prompt = "The food was delicious and the waiter"
completion = openai.Completion.create(deployment_id=deployment_id,
                                     prompt=prompt, stop=".", temperature=0)
                                
print(f"{prompt}{completion['choices'][0]['text']}.")

 

(Optional) Deployments: Delete

Finally let's delete the deployment

 

print(f'Deleting deployment: {deployment_id}')
openai.Deployment.delete(sid=deployment_id)

 

이 과정을 보니까 Azure OpenAI를 사용하는 것은 그냥 OpenAI API 를 사용하기 이전에 openai.Deployment.create() API를 사용해서 Deployment 부터 하네요.

 

그리고 추가적으로 Deployment 가 완료 되는지 여부를 openai.Deployment.retrieve() 를 사용해서 체크하는 부분이 있구요.

 

이렇게 한번 Deployment가 완료 되면 다른 openai API를 사용하는 방법과 똑 같이 openai.Completion.create() API를 사용해서 prompt 를 전달하고 응답을 받습니다.

 

그리고 마지막으로 해당 Deployment를 Delete 하는 과정이 있구요.

이때는 openai.Deployment.delete() API 를 사용합니다.

 

그냥 OpenAI API 를 사용할 때는 (Azure) 를 거치지 않고) 이 Deployment 단계들은 필요 없습니다. 그냥 openai api key 만 전달 한 후 openAI API를 사용하시면 됩니다.

 

참고로 실제로 실습을 하는 모습을 보려면 아래 유투브 클립을 보시면 됩니다.

 

https://www.youtube.com/watch?v=lHw1tZhXlEo 

 

 

반응형

Comment


반응형

OpenAI CookBook 을 거의 다 공부하고 Azure OpenAI 를 공부할 차례 입니다.

 

https://github.com/openai/openai-cookbook

 

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

 

첫 예제의 Setup 부터 막히더라구요.

 

 

api_base 와 api_version 을 구하는 방법도 모르겠어서 여기 저기 구글링을 해 보았습니다.

(이제는 Binging 을 한다고 말해야 하나?)

 

우선 Microsoft Azure 로 들어가서 Azure OpenAI 서비스를 선택합니다.

(Microsoft Azure 에 가입 돼 있어야 합니다. 일단 가입은 무료입니다.)

 

Azure OpenAI 라고 검색을 하시면 위와 같은 아이콘을 보실 수 있습니다.

 

클릭하면 이런 화면이 뜹니다.

 

여기서 Create 을 클릭하시면 ......

 

 

이런 화면이 뜹니다.

 

밑에 붉은 background 에 있는 글을 보세요.

 

Azure OpenAI Service is currently available to customers via an application form. The selected subscription has not been enabled for use of the service and does not have quota for any pricing tiers. Click here to request access to Azure OpenAI service.

 

Azure OpenAI 서비스는 현재 신청 양식을 통해 고객에게 제공됩니다. 선택한 구독은 서비스 사용을 위해 활성화되지 않았으며 가격 책정 계층에 대한 할당량이 없습니다. Azure OpenAI 서비스에 대한 액세스를 요청하려면 여기를 클릭하십시오.

 

Azure OpenAI 를 사용하려면 따로 신청을 하셔야 합니다.

여기서 링크를 클릭하면 아래와 같은 페이지로 갑니다.

 

저는 여기서 신청서 양식을 다 작성을 하고 마지막에 긴 설문도 다 작성을 하고 Submit을 눌렀습니다.

 

그러면 아래와 같은 화면이 나옵니다.

 

신청은 했는데 이게 승인이 될지 거부가 될지 그리고 승인이 되면 언제 될지 모르겠네요.

 

일단 현재로서는 실습을 하지는 못 하겠고 Cookbook 에 있는 글을 통해서 공부만 해 둬야 겠습니다.

 

 

아래는 Azure OpenAI 를 사용해서 Azure에서 리소스를 생성하고 배치하는 방법을 알려 주는 How-to 페이지 입니다.

여기서도 Prerequisites 로 Auzre 에 가입하고 위 신청서를 작성해야 한다고 나오네요.

 

How-to - Create a resource and deploy a model using Azure OpenAI Service - Azure OpenAI | Microsoft Learn

 

How-to - Create a resource and deploy a model using Azure OpenAI Service - Azure OpenAI

Walkthrough on how to get started with Azure OpenAI and make your first resource and deploy your first model.

learn.microsoft.com

 

아래는 신청서 작성하는 페이지 입니다.

https://aka.ms/oai/access

 

Dynamics 365 Customer Voice

 

customervoice.microsoft.com

 

이상 Azure OpenAI 를 사용하기 위한 Prerequisites 에 대한 Research 내용 공유글 이었습니다.

 

==============================

 

이 글 작성하고 이메일을 확인 했더니 금방 Microsoft 에서 답변 이메일이 왔네요.

 

 

요청은 거부 됐습니다.

 

저는 그냥 솔직하게 공부할 목적으로 사용하고 싶다라고 했는데 이런 경우는 받아들여지지 않네요.

그냥 Cookbook 글만을 통해서 공부만 해야 겠습니다.

반응형

Comment


반응형

 

You can now access GPT-4 models with 8K context via the existing OpenAI API.

이제 기존 OpenAI API를 통해 8K 컨텍스트로 GPT-4 모델에 액세스할 수 있습니다.

 

As an early customer we'd love to hear about your experience. Feel free to share feedback on our community forum or reach out directly to our team.

 

General API discussion

Welcome to the General Discussion! We encourage you to use this thread to discuss your experiences using the OpenAI API and to meet other users.

community.openai.com

초기 고객으로서 귀하의 경험에 대해 듣고 싶습니다. 커뮤니티 포럼에서 자유롭게 의견을 공유하거나 팀에 직접 연락하세요.

 

Best,
The OpenAI team

 

이런 내용입니다.

 

저는 GPT-4 API 사용 권한을 waiting list 에 3월 14일 신청 했었습니다.

 

 

Thank you for joining the waitlist to build with GPT-4!

 

GPT-4로 빌드하기 위한 대기자 명단에 등록해 주셔서 감사합니다!

 

To balance capacity with demand, we'll be sending invites gradually over time.

 

용량과 수요의 균형을 맞추기 위해 시간이 지남에 따라 점진적으로 초대장을 보낼 것입니다.

 

While we ramp up, invites will be prioritized to developers who have previously build with the OpenAI API. You can also gain priority access if you contribute model evaluations to OpenAI Evals that get merged, as this will help us improve the models for everyone.

 

확장하는 동안 초대는 이전에 OpenAI API로 빌드한 개발자에게 우선순위가 부여됩니다. 병합되는 OpenAI Eval에 모델 평가를 제공하면 모든 사람을 위해 모델을 개선하는 데 도움이 되므로 우선 액세스 권한을 얻을 수 있습니다.


Once you’re off the waitlist, you’ll receive an email with further instructions on how to get started. We will process requests for the 8K and 32K models at different rates based on capacity, so you can expect to receive 8K access first.

 

대기자 명단에서 제외되면 시작하는 방법에 대한 추가 지침이 포함된 이메일을 받게 됩니다. 용량에 따라 다른 속도로 8K 및 32K 모델에 대한 요청을 처리하므로 먼저 8K 액세스를 받을 수 있습니다.


We appreciate your interest, and look forward to having you build with GPT-4 soon. In the meantime, we suggest getting started with gpt-3.5-turbo, the model powering ChatGPT.

 

귀하의 관심에 감사드리며 곧 GPT-4로 빌드할 수 있기를 기대합니다. 그동안 ChatGPT를 지원하는 모델인 gpt-3.5-turbo를 시작하는 것이 좋습니다.


– The OpenAI Team


P.S. You can also preview GPT-4 on chat.openai.com if you’re a ChatGPT Plus subscriber. We expect to be severely capacity constrained, so there will be a usage cap for the model depending on demand and system performance.

 

추신 ChatGPT Plus 구독자인 경우 chat.openai.com에서 GPT-4를 미리 볼 수도 있습니다. 용량이 심각하게 제한될 것으로 예상되므로 수요 및 시스템 성능에 따라 모델에 대한 사용 한도가 있을 것입니다.

 

지금은 GPT-4 API 8k 용량에 대한 접근권만 허용이 된 것이네요.

 

어쨌든 공부를 시작할 수 있을 것 같습니다.

 

저는 2023년 1월 3일부터 GPT-3 API 관련해서 공부를 시작했습니다.

일종의 New Year's Resolution 이 돼 버렸는데요.

 

공부 거의 마칠 무렵인 3월 1일에 GPT-3.5 turbo API (ChatGPT API) 가 발표 됐습니다.

 

그래서 며칠동안 Update 된 API 를 다시 공부 해야 됐는데요.

 

14일 후인 3월 14일 Open AI 에서는 GPT-4 가 발표 됐습니다.

 

정말 정신 없이 발전하는 것 같습니다.

 

원래 계획은 OpenAI API Cookbook을 마치고 개인 프로젝트를 구상해서 추진하려고 했습니다.

 

이제 Cookbook을 거의 다 마치고 Azure 와 연결해서 사용할 수 있는 방법에 대한 글 3가지만 남아 있었는데...

이제 CPT-4 가 발표 됐으니 update 된 내용도 다시 수정하거나 추가해서 정리 해야 될 것 같습니다.

 

개인적으로 이번달 (3월) 안으로 Cookbook 공부 다 마치고 4월부터 개인 프로젝트 구상에 들어가야 겠습니다.

 

정말 따라가기 벅찰 정도로 발전하는군요.

 

반응형
TAG GPT-4, openai

Comment


반응형

오늘은 그림을 그리는 OpenAI의 AI 화가 DALL-E API 입니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/dalle/Image_generations_edits_and_variations_with_DALL-E.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

DALL-E

This notebook shows how to use OpenAI's DALL-E image API endpoints.

이 노트북은 OpenAI의 DALL-E 이미지 API endpoints를 사용하는 방법을 보여줍니다.

 

There are three API endpoints:

세 가지 API endpoints가 있습니다.

  • Generations: generates an image or images based on an input caption
  • Generations: 입력 캡션을 기반으로 이미지를 생성합니다.
  • Edits: edits or extends an existing image
  • 편집: 기존 이미지를 편집하거나 확장합니다.
  • Variations: generates variations of an input image
  • 변형: 입력 이미지의 변형을 생성합니다.

Setup

  • Import the packages you'll need
  • 필요한 패키지 가져오기
  • Import your OpenAI API key: You can do this by running ``export OPENAI_API_KEY="your API key"\ in your terminal.
  • OpenAI API key 가져오기 
  • Set a directory to save images to
  • 이미지를 저장할 디렉토리 설정

이제 소스 코드를 보겠습니다.

# imports
import openai  # OpenAI Python library to make API calls
import requests  # used to download images
import os  # used to access filepaths
from PIL import Image  # used to print and edit images

# set API key
openai.api_key = os.environ.get("OPENAI_API_KEY")

 

먼저 필요한 모듈들을 import 합니다.

openai를 import 해 openaai api를 사용할 수 있도록 합니다.

그 다음에 requests 모듈을 import 했습니다. 이 모듈은 openai 에 이미지가 생성 된 후 이 이미지를 나의 local 컴퓨터로 다운로드 받기 위해 필요합니다. 

이 모듈은 파이썬에서 HTTP request를 보낼 수 있도록 합니다. HTTP를 사용해서 OpenAI쪽에 생성돼 있는 이미지를 다운 로드 받게 됩니다.

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

 

Python Requests Module

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

 

그 다음은 os 모듈 입니다. 나의 local computer에 있는 환경 변수 값도 불러 오고 이미지가 저장될 폴더 위치도 설정하고 저장되는 이미지 파일 이름도 설정하는 등의 일들을 하는데 사용 됩니다.

https://docs.python.org/3/library/os.html

 

os — Miscellaneous operating system interfaces

Source code: Lib/os.py This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, s...

docs.python.org

 

그리고 마지막으로 Image PIL 모듈에 있는 Image 함수를 import 합니다.

이 PIL 모듈은 파이썬에서 이미지를 다룰 때 사용하는 모듈입니다.

https://pillow.readthedocs.io/en/stable/

 

Pillow

Pillow is the friendly PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors. Pillow for enterprise is available via the Tidelift Subscription...

pillow.readthedocs.io

https://pillow.readthedocs.io/en/stable/handbook/tutorial.html

 

Tutorial

Using the Image class: The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in several ways; e...

pillow.readthedocs.io

 

# set a directory to save DALL-E images to
image_dir_name = "images"
image_dir = os.path.join(os.curdir, image_dir_name)

# create the directory if it doesn't yet exist
if not os.path.isdir(image_dir):
    os.mkdir(image_dir)

# print the directory to save to
print(f"{image_dir=}")

그 다음은 생성한 이미지를 저장할 폴더의 위치를 정해 줍니다.

폴더 이름은 images 가 되고 그 위치는 현재 디렉토리에 있습니다.

 

if 문은 만약에 현재 디렉토리 안에 images라는 폴더가 없다면 mkdir() 을 이용해서 폴더를 생성하게 됩니다.

print() 결과는 아래와 같습니다.

image_dir='.\\images'

 

Generations

The generation API endpoint creates an image based on a text prompt.

 

generation API endpoint는 텍스트 프롬프트를 기반으로 이미지를 생성합니다.

 

Required inputs:

  • prompt (str): A text description of the desired image(s). The maximum length is 1000 characters.
  • 프롬프트(str): 원하는 이미지에 대한 텍스트 설명입니다. 최대 길이는 1000자입니다.

Optional inputs:

  • n (int): The number of images to generate. Must be between 1 and 10. Defaults to 1.
  • n (int): 생성할 이미지의 수. 1에서 10 사이여야 합니다. 기본값은 1입니다.
  • size (str): The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Smaller images are faster. Defaults to "1024x1024".
  • size (str): 생성된 이미지의 크기. "256x256", "512x512" 또는 "1024x1024" 중 하나여야 합니다.이미지가 작으면 더 빠릅니다.. 기본값은 "1024x1024"입니다.
  • response_format (str): The format in which the generated images are returned. Must be one of "url" or "b64_json". Defaults to "url".
  • response_format(str): 생성된 이미지가 반환되는 형식입니다. "url" 또는 "b64_json" 중 하나여야 합니다. 기본값은 "url"입니다.
  • user (str): A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. Learn more.

* user(str): OpenAI가 남용을 모니터링하고 감지하는 데 도움이 되는 최종 사용자를 나타내는 고유 식별자입니다. 

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

# create an image

# set the prompt
prompt = "Create picture for a Youtube channel Banner image named AI Madang, express the concept of Artificial Intellegent state-of-the-art technology and the concept of a play ground where human can play happily."

# call the OpenAI API
generation_response = openai.Image.create(
    prompt=prompt,
    n=1,
    size="1024x1024",
    response_format="url",
)

# print response
print(generation_response)

이 코드는 OpenAI 의 openai.Image.create() API를 사용해서 원하는 이미지를 만드는 과정입니다.

 

일단 내가 원하는 이미지를 prompt 변수에 담습니다.

저는 AI Madang 이라는 유투브 채널을 만들려고 하는데 그 채널의 Banner image로 사용할 최첨단 기술과 인간들의 놀이터 느낌이 나는 그림을 만들어 달라고 할 계획입니다.

 

그 다음은 openai.Image.create() API call 을 하는 부분 입니다. prompt가 들어가고 n은 그림 갯수를 나타내니까 그림은 1개만 만들라는 겁니다. 그리고 size는 1024X1024 입니다. response_format 은 url 이구요.

 

이 url을 이용해서 requests 모듈로 HTTP를 통해 이미지를 가져 오고 이것을 os 모듈을 이용해서 내 컴퓨터의 원하는 폴더에 저장 하는 작업을 할 겁니다.

그 이미지를 display 할 때 PIL 모듈의 Image 함수를 사용할 거구요.

 

저 같은 경우는 print 결과가 아래와 같이 나왔습니다.

 

 

OpenAI 에서 이미지가 생성 돼 있고 그 이미지가 위치해 있는 URL 을 받았습니다.

 

저 URL을 클릭하면 openai가 생성한 이미지가 나옵니다.

 

 

이미지가 마음에 안 들어서 몇 번 반복 했는데..... 여전히 마음에 안 드네요.

아직까지 저런 어려운 내용은 제대로 소화를 못 하는 것 같습니다.

 

어쨌든 오늘은 DALL-E API 를 공부하는 과정이니 그냥 넘어 가겠습니다.

 

Note: If you get this error - AttributeError: module 'openai' has no attribute 'Image' - you'll need to upgrade your OpenAI package to the latest version. You can do this by running pip install openai --upgrade in your terminal.

 

참고: AttributeError: module 'openai' has no attribute 'Image' 오류가 발생하면 OpenAI 패키지를 최신 버전으로 업그레이드해야 합니다. 터미널에서 pip install openai --upgrade를 실행하여 이를 수행할 수 있습니다.

 

# save the image
generated_image_name = "generated_image2.png"  # any name you like; the filetype should be .png
generated_image_filepath = os.path.join(image_dir, generated_image_name)
generated_image_url = generation_response["data"][0]["url"]  # extract image URL from response
generated_image = requests.get(generated_image_url).content  # download the image

with open(generated_image_filepath, "wb") as image_file:
    image_file.write(generated_image)  # write the image to the file

이제 이 이미지를 로컬에 저장하는 과정입니다.

generated_image2.png 라고 이름을 정할 생각입니다.

 

generated_image_filepath 라는 변수에 위에서 만들었던 images 라는 폴더 경로와 여기서 만들었던 이미지 파일 이름을 결합 시킵니다.

 

그리고 이미지가 있는 url 주소를 generated_image_url 에 담습니다.

 

그리고 requests 모듈의 get() 함수를 사용해서 그 이미지를 위 generated_image_url 로 다운로드 합니다.

 

그 다음 open() 메소드는 PIL 모듈에 있는 함수 입니다. 

 

https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open

 

Image Module

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, a...

pillow.readthedocs.io

 

wb 는 binary format으로 열라는 겁니다.

 

파이썬에서는 기본적으로 text 모드로 열게 되어 있는데 b 라는 의미는 이 텍스트가 아니라 바이너리 모드라는 의미 입니다. w 는 writing 입니다. 이와 반대로 r 은 reading 입니다. 읽기 모드가 아닌 쓰기 모드로 열라는 겁니다.

이렇게 하면 나중에 수정할 수 있습니다.

 

write() 함수를 사용해서 파일로 저장합니다. 이 함수는 Python 함수 입니다.

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

 

Python File write() Method

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

이제 생성된 이미지가 내 컴퓨터 안에 완전히 다운로드 됐습니다.

맨 오른쪽에 이 이미지가 있습니다. 나머지는 전에 연습 할 때 생성한 이미지들입니다.

# print the image
print(generated_image_filepath)
display(Image.open(generated_image_filepath))

이제 이 그림을 JupyterLab 화면에 display 해 보겠습니다.

print() 로는 파일 경로와 이름을 표시하고 display()는 이미지를 표시합니다.

 

실행 결과 입니다.

 

 

 

Variations

The variations endpoint generates new images (variations) similar to an input image.

 

변형(variation) endpoint 는 입력 이미지와 유사한 새 이미지(변형)를 생성합니다.

 

Here we'll generate variations of the image generated above.

 

여기서는 위에서 생성된 이미지의 변형을 생성합니다.

 

Required inputs:

  • image (str): The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
  • image(str): 변형의 기초로 사용할 이미지입니다. 유효한 PNG 파일이어야 하며 4MB 미만의 정사각형이어야 합니다.
  •  

Optional inputs:

  • n (int): The number of images to generate. Must be between 1 and 10. Defaults to 1.
  • n (int): 생성할 이미지의 수. 1에서 10 사이여야 합니다. 기본값은 1입니다.
  • size (str): The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Smaller images are faster. Defaults to "1024x1024".
  • size (str): 생성된 이미지의 크기. "256x256", "512x512" 또는 "1024x1024" 중 하나여야 합니다. 작은 이미지가 더 빠릅니다. 기본값은 "1024x1024"입니다.
  • response_format (str): The format in which the generated images are returned. Must be one of "url" or "b64_json". Defaults to "url".
  • response_format(str): 생성된 이미지가 반환되는 형식입니다. "url" 또는 "b64_json" 중 하나여야 합니다. 기본값은 "url"입니다.
  • user (str): A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. Learn more.
 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

user(str): OpenAI가 남용을 모니터링하고 감지하는 데 도움이 되는 최종 사용자를 나타내는 고유 식별자입니다. 

 

# create variations

# call the OpenAI API, using `create_variation` rather than `create`
variation_response = openai.Image.create_variation(
    image=generated_image,  # generated_image is the image generated above
    n=2,
    size="1024x1024",
    response_format="url",
)

# print response
print(variation_response)

 

이 코드는 위에서 생성된 이미지를 openai.Image.create_variation() API 를 사용해서 변형 시키는 겁니다.

이미지는 2개를 생성하고 크기는 1024X1024 입니다. response_format 은 url이구요.

 

프린트한 결과는 아래와 같습니다.

 

 

이미지를 2개 만들라고 했더니 URL도 두개가 나오네요.

 

클릭해 봤더니 다음과 같은 이미지들이 나옵니다.

 

 

 

# save the images
variation_urls = [datum["url"] for datum in variation_response["data"]]  # extract URLs
variation_images = [requests.get(url).content for url in variation_urls]  # download images
variation_image_names = [f"variation_image_{i}.png" for i in range(len(variation_images))]  # create names
variation_image_filepaths = [os.path.join(image_dir, name) for name in variation_image_names]  # create filepaths
for image, filepath in zip(variation_images, variation_image_filepaths):  # loop through the variations
    with open(filepath, "wb") as image_file:  # open the file
        image_file.write(image)  # write the image to the file

다음 코드는 이 두 이미지 파일을 로컬에 save 하는 과정입니다.

 

위의 과정과 똑 같은데 이미지가 두개 이므로 이것을 처리하기 위해 for 문을 사용했습니다.

 

실행 결과 입니다.

 

내 컴퓨터 안에 두개의 파일이 추가 됐습니다.

깜빡하고 이름을 바꾸지 않았더니 기존에 있는 이미지에 덮어 썼네요.

기존 이미지 두개는 날아갔습니다. 뭐 지금은 공부하는 중이니 상관은 없습니다.

실전에서는 아주 조심해야 겠네요. 자동으로 이름에 surfix 나 prefix 같은 것을 달아 주고 또 기존에 같은 이미지가 있으면 새 이미지에 surfix나 prefix 를 붙여주는 로직을 만들어야 겠죠.

 

# print the original image
print(generated_image_filepath)
display(Image.open(generated_image_filepath))

# print the new variations
for variation_image_filepaths in variation_image_filepaths:
    print(variation_image_filepaths)
    display(Image.open(variation_image_filepaths))

 

이 그림을 display 하는 스크립트 입니다.

위에서 한것과 똑 같은데 2개를 display 하기 때문에 for 문을 사용했습니다.

 

원본 파일을 display 하고 for 문 안에서는 변형 이미지 파일 2개를 display 합니다.

결과는 생성했던 3개 파일 모두 display 됩니다.

 

 

 

 

Edits

The edit endpoint uses DALL-E to generate a specified portion of an existing image. Three inputs are needed: the image to edit, a mask specifying the portion to be regenerated, and a prompt describing the desired image.

edit endpoint는 DALL-E를 사용하여 기존 이미지의 지정된 부분을 generate 합니다. 편집할 이미지, 재생성할 부분을 지정하는 마스크, 원하는 이미지를 설명하는 프롬프트의 세 가지 입력이 필요합니다.

 

 

Required inputs:

  • image (str): The image to edit. Must be a valid PNG file, less than 4MB, and square.
  • image (str): 편집할 이미지. 유효한 PNG 파일이어야 하며 4MB 미만의 정사각형이어야 합니다.
  • mask (str): An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where image should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as image.
  • 마스크(str): 완전히 투명한 영역(예: 알파가 0인 경우)이 이미지를 편집해야 하는 위치를 나타내는 추가 이미지입니다. 4MB 미만의 유효한 PNG 파일이어야 하며 이미지와 크기가 같아야 합니다.
  • prompt (str): A text description of the desired image(s). The maximum length is 1000 characters.
  • 프롬프트(str): 원하는 이미지에 대한 텍스트 설명입니다. 최대 길이는 1000자입니다.

 

Optional inputs:

  • n (int): The number of images to generate. Must be between 1 and 10. Defaults to 1.
  • n (int): 생성할 이미지의 수. 1에서 10 사이여야 합니다. 기본값은 1입니다.
  • size (str): The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Smaller images are faster. Defaults to "1024x1024".
  • size (str): 생성된 이미지의 크기. "256x256", "512x512" 또는 "1024x1024" 중 하나여야 합니다. 작은 이미지가 더 빠릅니다. 기본값은 "1024x1024"입니다.
  • response_format (str): The format in which the generated images are returned. Must be one of "url" or "b64_json". Defaults to "url".
  • response_format(str): 생성된 이미지가 반환되는 형식입니다. "url" 또는 "b64_json" 중 하나여야 합니다. 기본값은 "url"입니다.
  • user (str): A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. Learn more.
 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

user(str): OpenAI가 남용을 모니터링하고 감지하는 데 도움이 되는 최종 사용자를 나타내는 고유 식별자입니다. 

 

Set Edit Area

An edit requires a "mask" to specify which portion of the image to regenerate. Any pixel with an alpha of 0 (transparent) will be regenerated. The code below creates a 1024x1024 mask where the bottom half is transparent.

편집에는 재생성할 이미지 부분을 지정하는 "마스크"가 필요합니다. 알파가 0(투명)인 모든 픽셀이 재생성됩니다. 아래 코드는 아래쪽 절반이 투명한 1024x1024 마스크를 만듭니다.

# create a mask
width = 1024
height = 1024
mask = Image.new("RGBA", (width, height), (0, 0, 0, 1))  # create an opaque image mask

# set the bottom half to be transparent
for x in range(width):
    for y in range(height // 2, height):  # only loop over the bottom half of the mask
        # set alpha (A) to zero to turn pixel transparent
        alpha = 0
        mask.putpixel((x, y), (0, 0, 0, alpha))

# save the mask
mask_name = "bottom_half_mask.png"
mask_filepath = os.path.join(image_dir, mask_name)
mask.save(mask_filepath)

이렇게 생성한 마스크는 아래 반쪽만 알파갑을 준 것입니다. 그냥 눈으로 보면 별 티는 안 납니다.

 

Perform Edit

Now we supply our image, caption and mask to the API to get 5 examples of edits to our image

 

이제 이미지, 캡션 및 마스크를 API에 제공하여 이미지 편집의 5가지 예를 얻습니다.

 

# edit an image

# call the OpenAI API
edit_response = openai.Image.create_edit(
    image=open(generated_image_filepath, "rb"),  # from the generation section
    mask=open(mask_filepath, "rb"),  # from right above
    prompt=prompt,  # from the generation section
    n=1,
    size="1024x1024",
    response_format="url",
)

# print response
print(edit_response)

openai.Image.create_edit() API 를 사용해서 원본 이미지를 편집을 합니다.

 

결과는 아래와 같습니다.

 

 

URL을 클릭을 하니 아래와 같은 이미지가 나옵니다.

 

# save the image
edited_image_name = "edited_image.png"  # any name you like; the filetype should be .png
edited_image_filepath = os.path.join(image_dir, edited_image_name)
edited_image_url = edit_response["data"][0]["url"]  # extract image URL from response
edited_image = requests.get(edited_image_url).content  # download the image

with open(edited_image_filepath, "wb") as image_file:
    image_file.write(edited_image)  # write the image to the file

 

이 이미지 파일을 로컬에 저장합니다.

 

edited_image.png 파일이 생겼습니다.

사실은 기존에 있던 파일에 덮어 쓰기를 했습니다.

 

보시면 원본파일은 generated_image2.png 에서 아래 절반이 바뀐 것을 보실 수 있습니다.

 

# print the original image
print(generated_image_filepath)
display(Image.open(generated_image_filepath))

# print edited image
print(edited_image_filepath)
display(Image.open(edited_image_filepath))

이 부분은 Jupyterlab에 display 하는 부분 입니다.

원본과 편집본 두개를 display 합니다.

 

 

이렇게 하니까 아래 절 반이 바뀐 것을 쉽게 알 수가 있네요.

 

여기까지 OpenAI 의 DALL-E API 를 공부해 봤습니다.

반응형

Comment

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

 

반응형

Comment

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 가 공개 됐네요.

 

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

 

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

반응형

Comment


반응형

요즘은 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

반응형

Comment