見出し画像

OpenAI Cookbook まとめ

「OpenAI Cookbook」の重要そうな部分をまとめました。

前回

1. OpenAI Cookbook

「OpenAI Cookbook」は、「OpenAI API」で一般的なタスクを実行するためのサンプルコードおよびサンプルプロンプト集です。

2. 大規模言語モデルの仕組み

大規模言語モデルは、テキストの入力文字列が与えられると、次に来るテキストを予測します。大規模言語モデルは、膨大な量のテキストで、この予測エラーを最小限に抑える方法を学習します。これによって、モデルはこの予測に役立つ概念を理解します。

たとえば、次のような概念を学びます。

・スペルの書き方
・文法のしくみ
・どのように言い換えるか
・質問にどう答えるか
・会話の続け方
・多言語での書き方
・コードの書き方
・etc…

3. 大規模言語モデルの操作

大規模言語モデルは、以下の方法で出力を促すことができます。

・Instructionプロンプト : モデルに自分の欲しいものを伝える
・Completionプロンプト : モデルに自分の欲しいものの冒頭部分を示す
・Demonstrationプロンプト : モデルに自分の欲しいものの例を示す
  ・Few-Shot学習 : プロンプトのいくつかの例
  ・ファインチューニング : 学習データセットの例

3-1. Instructionプロンプト

Instructionプロンプトでは、モデルに自分の欲しいことを直接伝えます。Instructionモデル (text-davinci-003 など text- で始まるモデル) は、命令に従うように特別に設計されているため、プロンプトに指示を書くことで、モデルはその指示に従って最善を尽くします。

Extract the name of the author from the quotation below.

“Some humans theorize that intelligent species go extinct before they can expand into outer space. If they're correct, then the hush of the night sky is the silence of the graveyard.”
― Ted Chiang, Exhalation
Ted Chiang

3-2. Completionプロンプト

Completionプロンプトでは、モデルに自分の欲しいものの冒頭部分を示します。言語モデルが次に来そうなテキストを書き込もうとする特性を利用します。また、モデルはどこで停止するかを認識していないため、目的の出力を超えて生成されがちです。そのため、停止シーケンスまたは後処理が必要になることがよくあります。

Some humans theorize that intelligent species go extinct before they can expand into outer space. If they're correct, then the hush of the night sky is the silence of the graveyard.”
― Ted Chiang, Exhalation

The author of this quote is
Ted Chiang

3-3. Demonstrationプロンプト (Few-Shot学習)

Demonstrationプロンプトでは、モデルに自分の欲しいものの例を示します。このアプローチは、モデルがプロンプトで提供するいくつかの例から学習するため、Few-Shot学習と呼ばれます。

Quote:
“When the reasoning mind is forced to confront the impossible again and again, it has no choice but to adapt.”
― N.K. Jemisin, The Fifth Season
Author: N.K. Jemisin

Quote:
“Some humans theorize that intelligent species go extinct before they can expand into outer space. If they're correct, then the hush of the night sky is the silence of the graveyard.”
― Ted Chiang, Exhalation
Author:
Ted Chiang

3-4. Demonstrationプロンプト (ファインチューニング)

十分な学習例があれば、カスタムモデルをファインチューニングできます。この場合、指示は不要になります。ただし、プロンプトを終了して出力を開始するタイミングをモデルに伝えるために、セパレータシーケンス (例 : -> や ###) を含めると役立つ場合があります。これがないと、入力テキストの詳細化を続行するリスクがあります。

Some humans theorize that intelligent species go extinct before they can expand into outer space. If they're correct, then the hush of the night sky is the silence of the graveyard.”
― Ted Chiang, Exhalation

###
 Ted Chiang

3-5. プロンプトトリック

プロンプトでは、次のようなトリックを試すこともできます。

・明確な指示を出す
たとえば、出力をカンマ区切りのリストにしたい場合は、「カンマ区切りのリストで返してください」、答えがわからないときに"わかりません"と言わせたい場合は、「答えがわからない場合は"わかりません"と言ってください」と伝えます。

・より良い例を提供する
プロンプトで例を示す場合は、例が多様で高品質であることを確認してください。

・専門家のように答えてもらう
「専門家のように答えてください」と頼むと、専門家が答えると思われる高品質な回答を返します。

・段階的に考えてもらう
「段階的に考えてみましょう」と最終的な答えの前にその理由を説明させることで、最終的な答えが一貫して正しい可能性を高めることができます。

その他のプロンプト例については、「OpenAI Examples」が参考になります。

4. テキストの生成

大規模言語モデルは、テキストの生成が得意です。
以下のようなタスクを支援できます。

・ブログ記事
・メールコピー
・広告コピー
・ウェブサイトコピー
・製品説明
・メモ
・ストーリーテリング
・ブレーンストーミング
・質問作成
・etc…

4-1. テキストの生成の例

テキストの生成の例は、次のとおりです。

Write an email to a colleague named Jill congratulating her on her promotion. The tone should be warm yet professional. Mention how you admire the work she's been putting in.  Include a joke about how her pet lizard Max enjoys eating grasshoppers. Mention how you're looking forward to the team off-site next week.
Dear Jill,

Congratulations on your promotion! I've been admiring the great work you've been putting in and I'm really happy for your success. Max the lizard must be thrilled too - I bet he's looking forward to feasting on even more grasshoppers!

I'm really looking forward to next week's team off-site. It's going to be great to catch up with everyone and brainstorm some new ideas.

Best,

[Your Name]

5. テキストの説明

大規模言語モデルの機能の1つは、テキストから情報を抽出することです。
以下のような情報を抽出できます。

◎ テキストの質問応答
・ナレッジベースにクエリを実行して、情報を収集。
・文書にクエリを実行して、内容を理解。
・文書にクエリを実行して、タグ、クラス、エンティティなどを抽出。

◎ テキストの要約
・長い文書の要約。
・メールやメッセージスレッドの要約。
・会議メモの要約。

◎ テキストの分類
・顧客メッセージをトピック別に分類。
・文書をトピック別に分類。
・テキストのトーンまたは感情の分類。

◎ エンティティの抽出
・顧客メッセージから連絡先情報を抽出。
・文書から人物、会社、製品名前を抽出。
・カスタマーレビューやフィードバックで言及されているものを抽出。

5-1. テキストの質問応答の例

テキストの質問応答の例は、次のとおりです。

Using the following text, answer the following question. If the answer is not contained within the text, say "I don't know."

Text:
"""
Oklo Mine (sometimes Oklo Reactor or Oklo Mines), located in Oklo, Gabon on the west coast of Central Africa, is believed to be the only natural nuclear fission reactor. Oklo consists of 16 sites at which self-sustaining nuclear fission reactions are thought to have taken place approximately 1.7 billion years ago, and ran for hundreds of thousands of years. It is estimated to have averaged under 100 kW of thermal power during that time.
"""

Question: How many natural fission reactors have ever been discovered?

Answer:
 One

5-2. テキストの要約の例

テキストの要約の例は、次のとおりです。

Summarize the following text.

Text:
"""
Two independent experiments reported their results this morning at CERN, Europe's high-energy physics laboratory near Geneva in Switzerland. Both show convincing evidence of a new boson particle weighing around 125 gigaelectronvolts, which so far fits predictions of the Higgs previously made by theoretical physicists.

"As a layman I would say: 'I think we have it'. Would you agree?" Rolf-Dieter Heuer, CERN's director-general, asked the packed auditorium. The physicists assembled there burst into applause.
"""

Summary:
CERN has announced the discovery of a new particle, the Higgs boson. This particle has been predicted by theoretical physicists and is a major step forward in our understanding of the universe.

5-3. テキストの分類

テキストを分類する最善の方法は、クラスが事前にわかっているかどうかによって異なります。
クラスが事前にわかっている場合は、ファインチューニングしたモデルを使用するのが最適です (Fine-tuned_classification.ipynb参照)。
クラスが事前にわかっていない場合は、Zero-Shot分類を試すことができます (Zero-shot_classification.ipynb参照)。

5-4. エンティティの抽出

エンティティの抽出の例は、次のとおりです。

From the text below, extract the following entities in the following format:
Companies: <comma-separated list of companies mentioned>
People & titles: <comma-separated list of people mentioned (with their titles or roles appended in parentheses)>

Text:
"""
In March 1981, United States v. AT&T came to trial under Assistant Attorney General William Baxter. AT&T chairman Charles L. Brown thought the company would be gutted. He realized that AT&T would lose and, in December 1981, resumed negotiations with the Justice Department. Reaching an agreement less than a month later, Brown agreed to divestiture—the best and only realistic alternative. AT&T's decision allowed it to retain its research and manufacturing arms. The decree, titled the Modification of Final Judgment, was an adjustment of the Consent Decree of 14 January 1956. Judge Harold H. Greene was given the authority over the modified decree....

In 1982, the U.S. government announced that AT&T would cease to exist as a monopolistic entity. On 1 January 1984, it was split into seven smaller regional companies, Bell South, Bell Atlantic, NYNEX, American Information Technologies, Southwestern Bell, US West, and Pacific Telesis, to handle regional phone services in the U.S. AT&T retains control of its long distance services, but was no longer protected from competition.
"""
Companies: United States v. AT&T, AT&T, Justice Department, Bell South, Bell Atlantic, NYNEX, American Information Technologies, Southwestern Bell, US West, Pacific Telesis
People & titles: William Baxter (Assistant Attorney General), Charles L. Brown (AT&T chairman), Harold H. Greene (Judge)

6. テキストの編集

OpenAI APIには、completionエンドポイントに加えて、editエンドポイントも提供します。1つのテキスト入力のみを受け取るcompletionとは対照的に、editは2 つのテキスト入力 (InstructionとText) を受け取ります。

テキストの編集の例は、次のとおりです。

Fix the OCR errors
Therewassomehostilityntheenergybehindthe researchreportedinPerceptrons....Part of ourdrivecame,aswequiteplainlyacknoweldgednourbook,fromhe facthatfundingndresearchnergywerebeingdissipatedon. . .misleadingttemptsouseconnectionistmethodsnpracticalappli-cations.
There was some hostility in the energy behind the research reported in Perceptrons....Part of our drive came, as we quite plainly acknowledged in our book, from the fact that funding and research energy were being dissipated on...misleading attempts to use connectionist methods in practical applications.

6-1. 翻訳

completionエンドポイントによるテキストの翻訳の例は、次のとおりです。

Translate the following text from English to French.

English: That's life.
French:
 C'est la vie.

editエンドポイントによるテキストの翻訳の例は、次のとおりです。

translation into French
That's life.
C'est la vie.

7. テキストの比較

OpenAI APIのembeddingsエンドポイントを使用して、テキスト間の類似性を測定できます。埋め込みは、セマンティック検索、レコメンデーション、クラスター分析、near-duplicate検出などに使用できます。

7-1. セマンティック検索

埋め込みを検索に使用する最も簡単な手順は、次のとおりです。

◎ 検索前
 ・テキストコーパスをトークン制限よりも小さいチャンクに分割。
 ・各チャンクを埋め込みに変換。
 ・埋め込みを独自のデータベースまたはベクトル検索プロバイダに保存。
◎ 検索時
 ・検索クエリを埋め込みに変換。
 ・データベースで最も近い埋め込みを見つける。
 ・コサイン類似度でランク付けされた上位の結果を返す。

詳しくは、Semantic_text_search_using_embeddings.ipynb参照。

7-2. レコメンデーション

レコメンデーションは検索と似ていますが、入力が自由形式のテキストクエリではなく、セット内のアイテムになります。

詳しくは、Recommendation_using_embeddings.ipynb参照。

7-3. 埋め込みのカスタマイズ

OpenAI の埋め込みモデルの重みをファインチューニングすることはできませんが、学習データを使って、埋め込みをカスタマイズすることができます。

詳しくは、Customizing_embeddings.ipynb参照。

8. コードの生成

code-davinci-002 でのコードの生成の例は、次のとおりです。

SQL tables (and columns):
* Customers(customer_id, signup_date)
* Streaming(customer_id, video_id, watch_date, watch_minutes)

A well-written SQL query that lists customers who signed up during March 2020 and watched more than 50 hours of video in their first 30 days:
```
SELECT c.customer_id
FROM Customers c
JOIN Streaming s
ON c.customer_id = s.customer_id
WHERE c.signup_date BETWEEN '2020-03-01' AND '2020-03-31'
AND s.watch_date BETWEEN c.signup_date AND DATE_ADD(c.signup_date, INTERVAL 30 DAY)
GROUP BY c.customer_id
HAVING SUM(s.watch_minutes) > 50 * 60

code-davinci-002は変数名から推測できます。たとえば、watch_minutesの単位は分であるため、50時間と比較する前に60倍に変換する必要があると推測されます。

9. コードの説明

code-davinci-002 でのコードの説明の例は、次のとおりです。

A SQL query:
```
SELECT c.customer_id
FROM Customers c
JOIN Streaming s
ON c.customer_id = s.customer_id
WHERE c.signup_date BETWEEN '2020-03-01' AND '2020-03-31'
AND s.watch_date BETWEEN c.signup_date AND DATE_ADD(c.signup_date, INTERVAL 30 DAY)
GROUP BY c.customer_id
HAVING SUM(s.watch_minutes) > 50 * 60
```

Questions:
1. What does the SQL query do?
2. Why might someone be interested in this time period?
3. Why might a company be interested in this SQL query?

Answers:
1. The SQL query finds all customers who signed up in March 2020 and watched more than 50 hours of content in the first 30 days after signing up.
2. The time period is interesting because it is the first month of the COVID-19 pandemic.
3. A company might be interested in this SQL query because it can help them understand how the pandemic has affected their business.

10. コードの編集

OpenAIのeditエンドポイントは、コードの編集にも役立ちます。

code-davinci-edit-001でのコードの編集の例は、次のとおりです。

def tribonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    elif n == 2:
        return 1
    elif n == 3:
        return 2
    else:
        return tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3)

Instructionの例は、次のとおりです。

Add a docstring
Add typing
Improve the runtime
Add a test
Translate to JavaScript (or Rust or Lisp or any language you like)

ランタイムを改善して JavaScript に変換した後の出力例は、次のとおりです。

function tribonacci(n) {
  let a = 0;
  let b = 1;
  let c = 1;
  for (let i = 0; i < n; i++) {
    [a, b, c] = [b, c, a + b + c];
  }
  return a;
}

11. コードの比較

OpenAI API には、コード検索の埋め込み機能もあり、コードのセクションとテキストクエリとの関連性、またはコードの2つのセクション間の類似性を測定できます。

コードの埋め込みは、次のようなユース ケースに役立ちます。

・コード検索
・コードベースのクラスタリングと分析

詳しくは、Code_search.ipynbClustering.ipynbを参照。

次回



この記事が気に入ったらサポートをしてみませんか?