ゼファーネットのロゴ

初心者向け OpenAI API: わかりやすいスターター ガイド – KDnuggets

日付:

初心者向け OpenAI API: わかりやすいスターター ガイド
著者による画像
 

このチュートリアルでは、さまざまなユースケースに合わせて OpenAI API をセットアップして使用する方法を学びます。このチュートリアルは、Python プログラミングの知識が限られている人でも理解しやすいように設計されています。誰でも応答を生成し、高品質の大規模言語モデルにアクセスできる方法を探っていきます。

  オープンAI API 開発者は、OpenAI によって開発された幅広い AI モデルに簡単にアクセスできます。開発者が最先端の OpenAI モデルを活用したインテリジェントな機能をアプリケーションに組み込むことができる、ユーザーフレンドリーなインターフェイスを提供します。 API は、テキスト生成、マルチターン チャット、埋め込み、文字起こし、翻訳、テキスト読み上げ、画像理解、画像生成など、さまざまな目的に使用できます。さらに、この API は、curl、Python、Node.js と互換性があります。 

OpenAI API の使用を開始するには、まず openai.com でアカウントを作成する必要があります。以前は、すべてのユーザーに無料のクレジットが付与されていましたが、現在は新規ユーザーはクレジットを購入する必要があります。 

クレジットを購入するには、「設定」、「請求」、最後に「支払い詳細の追加」に移動します。デビットカードまたはクレジットカードの情報を入力し、自動リチャージを必ず無効にしてください。 10 USD をチャージすると、XNUMX 年間使用できます。

 

初心者向け OpenAI API: わかりやすいスターター ガイド
 

「API キー」に移動し、「新しい秘密キーの作成」を選択して、API キーを作成しましょう。名前を付けて「秘密キーの作成」をクリックします。

 

初心者向け OpenAI API: わかりやすいスターター ガイド
 

API をコピーし、ローカル マシンに環境変数を作成します。

 

初心者向け OpenAI API: わかりやすいスターター ガイド
 

私はIDEとしてDeepnoteを使用しています。環境変数を作成するのは簡単です。 「統合」に移動し、「環境変数の作成」を選択し、キーの名前と値を指定して、統合を作成するだけです。

 

初心者向け OpenAI API: わかりやすいスターター ガイド
 

次に、pip を使用して OpenAI Python パッケージをインストールします。 

%pip install --upgrade openai

次に、さまざまなタイプのモデルにグローバルにアクセスできるクライアントを作成します。

環境変数に「OPENAI_API_KEY」という名前を設定した場合、OpenAI クライアントに API キーを提供する必要はありません。

from openai import OpenAI

client = OpenAI()

API キーを指定する必要があるのは、環境変数の名前がデフォルトの名前と異なる場合のみであることに注意してください。

import os
from openai import OpenAI

client = OpenAI(
  api_key=os.environ.get("SECRET_KEY"),
 )

従来の関数を使用して応答を生成します。完了関数では、応答を生成するためにモデル名、プロンプト、およびその他の引数が必要です。

completion = client.completions.create(
    model="gpt-3.5-turbo-instruct",
    prompt="Write a short story about Elon Musk being the biggest troll.",
    max_tokens=300,
    temperature=0.7,
)
print(completion.choices[0].text)

 

GPT3.5 モデルは、イーロン・マスクに関する驚くべきストーリーを生み出しました。 

 

初心者向け OpenAI API: わかりやすいスターター ガイド
 

追加の引数 `stream` を指定することで、応答をストリーミングすることもできます。 

ストリーム機能を使用すると、完全な応答を待つ代わりに、出力が生成されるとすぐに処理できるようになります。このアプローチは、言語モデルの出力を一度にではなくトークンごとに返すことにより、知覚される待ち時間を短縮するのに役立ちます。

stream = client.completions.create(
    model="gpt-3.5-turbo-instruct",
    prompt="Write a Python code for accessing the REST API securely.",
    max_tokens=300,
    temperature=0.7,
    stream = True
)
for chunk in stream:
        print(chunk.choices[0].text, end="")

 

初心者向け OpenAI API: わかりやすいスターター ガイド

モデルは API チャット完了を使用しました。応答を生成する前に、利用可能なモデルを調べてみましょう。   

利用可能なすべてのモデルのリストを表示するか、 Models 公式ドキュメントのページ。 

print(client.models.list())

初心者向け OpenAI API: わかりやすいスターター ガイド
 

最新バージョンの GPT-3.5 を使用し、システム プロンプトとユーザー メッセージの辞書のリストを提供します。必ず同じメッセージ パターンに従ってください。

completion = client.chat.completions.create(
    model="gpt-3.5-turbo-1106",
    messages=[
        {
            "role": "system",
            "content": "You are an experienced data scientist, adept at presenting complex data concepts with creativity.",
        },
        {
            "role": "user",
            "content": "What is Feature Engineering, and what are some common methods?",
        },
    ],
)

print(completion.choices[0].message.content)

 

ご覧のとおり、従来の API と同様の結果が生成されました。では、なぜこの API を使用するのでしょうか?次に、チャット完了 API がより柔軟で使いやすい理由を学びます。

Feature engineering is the process of selecting, creating, or transforming features (variables) in a dataset to improve the performance of machine learning models. It involves identifying the most relevant and informative features and preparing them for model training. Effective feature engineering can significantly enhance the predictive power of a model and its ability to generalize to new data.

Some common methods of feature engineering include:

1. Imputation: Handling missing values in features by filling them in with meaningful values such as the mean, median, or mode of the feature.

2. One-Hot Encoding: Converting categorical variables into binary vectors to represent different categories as individual features.

3. Normalization/Standardization: Scaling numerical features to bring t.........

 

ここでは、AI モデルとマルチターン会話を行う方法を学びます。これを行うには、前の会話にアシスタントの応答を追加し、同じメッセージ形式で新しいプロンプトも含めます。その後、チャット補完機能に辞書のリストを提供します。

chat=[
    {"role": "system", "content": "You are an experienced data scientist, adept at presenting complex data concepts with creativity."},
    {"role": "user", "content": "What is Feature Engineering, and what are some common methods?"}
  ]
chat.append({"role": "assistant", "content": str(completion.choices[0].message.content)})
chat.append({"role": "user", "content": "Can you summarize it, please?"})

completion = client.chat.completions.create(
  model="gpt-3.5-turbo-1106",
  messages=chat
)

print(completion.choices[0].message.content)

 

モデルはコンテキストを理解し、特徴量エンジニアリングを要約しました。

Feature engineering involves selecting, creating, or transforming features in a dataset to enhance the performance of machine learning models. Common methods include handling missing values, converting categorical variables, scaling numerical features, creating new features using interactions and polynomials, selecting important features, extracting time-series and textual features, aggregating information, and reducing feature dimensionality. These techniques aim to improve the model's predictive power by refining and enriching the input features.

高度なアプリケーションを開発するには、テキストを埋め込みに変換する必要があります。これらの埋め込みは、類似性検索、セマンティック検索、および推奨エンジンに使用されます。 API テキストとモデル名を指定することで、埋め込みを生成できます。それはとても簡単です。 

text = "Data Engineering is a rapidly growing field that focuses on the collection, storage, processing, and analysis of large volumes of structured and unstructured data. It involves various tasks such as data extraction, transformation, loading (ETL), data modeling, database design, and optimization to ensure that data is accessible, accurate, and relevant for decision-making purposes."

DE_embeddings = client.embeddings.create(input=text, model="text-embedding-3-small")
print(chat_embeddings.data[0].embedding)

 

[0.0016297283582389355, 0.0013418874004855752, 0.04802832752466202, -0.041273657232522964, 0.02150309458374977, 0.004967313259840012,.......]

テキストを音声に変換したり、音声をテキストに変換したり、オーディオ API を使用して翻訳したりできるようになりました。 

転写

私たちは使用します Wi-Fi 7 がすべてを変える YouTubeビデオをmp3に変換します。その後、ファイルを開いて音声トランスクリプト API に提供します。

audio_file= open("Data/techlinked.mp3", "rb")
transcript = client.audio.transcriptions.create(
  model="whisper-1",
  file=audio_file
)
print(transcript.text)

 

ウィスパーモデルは素晴らしいです。音声の完璧なトランスクリプトが付いています。 

The Consumer Electronics Show has officially begun in Las Vegas and we'll be bringing you all the highlights from right here in our regular studio where it's safe and clean and not a desert. I hate sand. The Wi-Fi Alliance announced that they have officially confirmed the Wi-Fi 7 standard and they've already started to certify devices to ensure they work together. Unlike me and Selena, that was never gonna last. The new standard will have twice the channel bandwidth of Wi-Fi 5, 6, and 6E, making it better for, surprise,......

インタビュー

英語の音声を別の言語に書き写すこともできます。私たちの場合は、ウルドゥー語に変換します。別の引数「言語」を追加し、それに ISO 言語コード「ur」を指定するだけです。

translations = client.audio.transcriptions.create(
    model="whisper-1",
    response_format="text",
    language="ur",
    file=audio_file,
)

print(translations)

 

非ラテン語の翻訳は不完全ですが、最低限の実用的な製品には使用できます。

کنسومر ایلیکٹرانک شاہی نے لاس بیگیس میں شامل شروع کیا ہے اور ہم آپ کو جمہوری بہترین چیزیں اپنے ریگلر سٹوڈیو میں یہاں جارہے ہیں جہاں یہ آمید ہے اور خوبصورت ہے اور دنیا نہیں ہے مجھے سانڈ بھولتا ہے وائ فائی آلائنٹس نے اعلان کیا کہ انہوں نے وائ فائی سیبن سٹانڈرڈ کو شامل شروع کیا اور انہوں ن........

スピーチへのテキスト

テキストを自然な音声に変換するために、Speech API を使用し、モデル名、声優名、および入力テキストを提供します。次に、音声ファイルを「Data」フォルダーに保存します。 

response = client.audio.speech.create(
  model="tts-1",
  voice="alloy",
  input= '''I see skies of blue and clouds of white
            The bright blessed days, the dark sacred nights
            And I think to myself
            What a wonderful world
         '''
)

response.stream_to_file("Data/song.mp3")

 

Deepnote Notebook 内でオーディオ ファイルを聞くには、IPython Audio 関数を使用します。

from IPython.display import Audio
Audio("Data/song.mp3")

 

初心者向け OpenAI API: わかりやすいスターター ガイド

OpenAI API は、チャット完了機能を通じてユーザーにマルチモーダル モデルへのアクセスを提供します。画像を理解するために、最新の GPT-4 ビジョン モデルを使用できます。 

message 引数には、画像と画像の URL に関する質問をするためのプロンプトが用意されています。画像の出典元は Pixabay。エラーを避けるために、同じメッセージ形式に従っていることを確認してください。

response = client.chat.completions.create(
    model="gpt-4-vision-preview",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Could you please identify this image's contents and provide its location?",
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://images.pexels.com/photos/235731/pexels-photo-235731.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2",
                    },
                },
            ],
        }
    ],
    max_tokens=300,
)

print(response.choices[0].message.content)

 

出力はイメージを完全に説明しています。 

This is an image of a person carrying a large number of rice seedlings on a carrying pole. The individual is wearing a conical hat, commonly used in many parts of Asia as protection from the sun and rain, and is walking through what appears to be a flooded field or a wet area with lush vegetation in the background. The sunlight filtering through the trees creates a serene and somewhat ethereal atmosphere.

It's difficult to determine the exact location from the image alone, but this type of scene is typically found in rural areas of Southeast Asian countries like Vietnam, Thailand, Cambodia, or the Philippines, where rice farming is a crucial part of the agricultural industry and landscape.

 

画像 URL を提供する代わりに、ローカル画像ファイルをロードしてチャット完了 API に提供することもできます。これを行うには、まずイメージをダウンロードする必要があります。 マンジート・シン・ヤダフ pexels.comから。

!curl -o /work/Data/indian.jpg "https://images.pexels.com/photos/1162983/pexels-photo-1162983.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"

 

次に、画像をロードしてbase64形式でエンコードします。 

import base64

def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')

image_path = "Data/indian.jpg"

# generating the base64 string
base64_image = encode_image(image_path)

 

画像の URL を提供する代わりに、メタデータと画像の Base64 文字列を提供します。

response = client.chat.completions.create(
    model="gpt-4-vision-preview",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Could you please identify this image's contents.",
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{base64_image}"
                    },
                },
            ],
        }
    ],
    max_tokens=100,
)

print(response.choices[0].message.content)

 

モデルは画像の分析に成功し、それについて詳細な説明を提供しました。

The image shows a woman dressed in traditional Indian attire, specifically a classical Indian saree with gold and white colors, which is commonly associated with the Indian state of Kerala, known as the Kasavu saree. She is adorned with various pieces of traditional Indian jewelry including a maang tikka (a piece of jewelry on her forehead), earrings, nose ring, a choker, and other necklaces, as well as bangles on her wrists.

The woman's hairstyle features jasmine flowers arranged in

DALLE-3 モデルを使用して画像を生成することもできます。モデル名、プロンプト、サイズ、品質、画像の数を画像 API に指定するだけです。 

response = client.images.generate(
  model="dall-e-3",
  prompt="a young woman sitting on the edge of a mountain",
  size="1024x1024",
  quality="standard",
  n=1,
)

image_url = response.data[0].url

 

生成されたイメージはオンラインに保存され、ダウンロードしてローカルに表示できます。これを行うには、画像の URL と保存先のローカル ディレクトリを指定して、`request` 関数を使用して画像をダウンロードします。その後、Pillow ライブラリの Image 関数を使用して画像を開いて表示します。

import urllib.request

from PIL import Image

urllib.request.urlretrieve(image_url, '/work/Data/woman.jpg')

img = Image.open('/work/Data/woman.jpg')

img.show()

 

生成された高品質の画像を受け取りました。本当に素晴らしいです!

 

初心者向け OpenAI API: わかりやすいスターター ガイド
 

OpenAI Python API の実行に苦労している場合は、お気軽に私のプロジェクトをチェックしてください。 ディープノート.

私はしばらく OpenAPI を試してきましたが、最終的に使用したクレジットは 0.22 ドルのみで、これはかなり手頃だと思います。私のガイドがあれば、初心者でも独自の AI アプリケーションの構築を始めることができます。これは単純なプロセスです。独自のモデルをトレーニングしたり、デプロイしたりする必要はありません。 API を使用して最先端のモデルにアクセスできます。API は新しいリリースごとに継続的に改善されています。

 

初心者向け OpenAI API: わかりやすいスターター ガイド
 

このガイドでは、OpenAI Python API を設定し、単純なテキスト応答を生成する方法について説明します。また、マルチターン チャット、埋め込み、文字起こし、翻訳、音声合成、ビジョン、画像生成 API についても学びます。 

これらの API を使用して高度な AI アプリケーションを構築してほしい場合は、お知らせください。 

読んでくれてありがとう。
 
 

アビッド・アリ・アワン (@ 1abidaliawan)は、機械学習モデルの構築を愛する認定データサイエンティストの専門家です。 現在、彼はコンテンツの作成と、機械学習とデータサイエンステクノロジーに関する技術ブログの執筆に注力しています。 Abidは、技術管理の修士号と電気通信工学の学士号を取得しています。 彼のビジョンは、精神疾患に苦しんでいる学生のためにグラフニューラルネットワークを使用してAI製品を構築することです。

スポット画像

最新のインテリジェンス

スポット画像