このレッスンでは、高度なプロンプトエンジニアリング技術を使用して LLM 回答のインテリジェンスと精度を向上させる方法について説明します。以前に確立されたベースライン評価に基づいて、SAP Cloud SDK for AI を使用して Few-shot Prompting や Meta-prompting などの強力な戦略を実装し、生成 AI アプリケーションの品質と精度の向上に対する影響を観察する方法を学習します。
Few-Shot プロンプト
推進技術を実装し、結果を評価して速報結果の改善を確認しよう。
以下のコードを使用します。
123456789101112131415161718192021222324252627282930313233343536373839
prompt_10 = Template(
messages=[
SystemMessage(
"""You are an intelligent assistant. Your task is to extract and categorize messages. Here are some example:
{{?few_shot_examples}}
Use the examples when extract and categorize the following message:
Extract and return a json with the follwoing keys and values:
- "urgency" as one of {{?urgency}}
- "sentiment" as one of {{?sentiment}}
- "categories" list of the best matching support category tags from: {{?categories}}
Your complete message should be a valid json string that can be read directly and only contain the keys mentioned in the list above. Never enclose it in ```json...```, no newlines, no unnessacary whitespaces."""),
UserMessage("{{?input}}")
]
)
import random
random.seed(42)
k = 3
examples = random.sample(dev_set, k)
example_template = """<example>
{example_input}
## Output
{example_output}
</example>"""
examples = '\n---\n'.join([example_template.format(example_input=example["message"], example_output=json.dumps(example["ground_truth"])) for example in examples])
f_10 = partial(send_request, prompt=prompt_10, few_shot_examples=examples, **option_lists)
response = f_10(input=mail["message"])
overall_result["few_shot--llama3.1-70b"] = evalulation_full_dataset(test_set_small, f_10)
pretty_print_table(overall_result)
このコードは、緊急度、センチメント、およびサポートカテゴリタグに従ってメッセージを抽出および分類するためのプロンプトテンプレートを作成することを目的としています。開発セットからランダムに選択された例を使用することで、書式設定されたfew-shot 学習プロンプトが生成されます。プロンプトは、特定の入力メッセージを処理および分類するために言語モデルに送信され、モデルの全体的なパフォーマンスが評価され、テーブル形式で表示されます。
以下に、コードの一部の拡張された説明を示します。
- ランダムシードの設定: "random.seed(42)" を使用してランダムシードを設定し、例のランダムサンプリングを再現できるようにします。これは、実験および評価における整合性の維持に役立ちます。
- サンプリング例: 変数 "k" が 3 に設定され、"dev_set" データセットからのサンプル数を示します。関数 "random.sample(dev_set, k)" では、開発セットから 3 つのランダムな例が選択されます。
- 書式設定の例: 選択した例は、テンプレート "example_template" に書式設定されます。各例には、入力メッセージおよび予想される出力が JSON 形式で含まれています。この書式設定された文字列は、"\n---\n" を使用して結合され、一連のまとまった例が作成されます。
- 部分関数アプリケーション: "部分" 関数を使用して、生成されたプロンプトと例を "send_request" 関数にバインドし、入力メッセージのみで呼び出すことができる関数 "f_10" を作成します。これにより、必要なコンテキストでモデルに依頼を送信するプロセスが合理化されます。
- 要求の送信および評価: スクリプトは、"mail["message"]" からの入力メッセージとともに、"f_10(input=mail["message"])" を使用して要求を送信します。結果は、小さなテストデータセット "test_set_small" に対して保存および評価されます。評価結果は、"overall_result["few_shot--llama3-70b"]" に保存されます。
- 出力表示: 最後に、"pretty_print_table(overall_result)" 関数を使用して、書式設定されたテーブルで評価結果を表示することで、結果を解釈しやすくなります。
応答の例:
12345 0%| | 0/20 [00:00<?, ?it/s]
is_valid_json correct_categories correct_sentiment correct_urgency
=========================================================================================
basic--llama3.1-70b 100.0% 83.5% 30.0% 70.0%
few_shot--llama3.1-70b 100.0% 84.0% 50.0% 90.0%これは、few-shot プロンプトを実装した後の評価の出力です。
センチメントおよび緊急度の割当の改善を確認することができます。
以前はベースラインを確立しており、テストデータを使用して、絞り込まれたプロンプトの結果とベースラインを評価および比較できるようになりました。
メタプロンプト
ここでは、緊急度やセンチメントなどのさまざまなタグに対するプロンプトの詳細なガイドを作成するためのメタプロンプトを実装します。
以下のコードを使用します。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
example_template_metaprompt = """<example>
{example_input}
## Output
{key}={example_output}
</example>"""
prompt_get_guide = Template(
messages=[
SystemMessage(
"""Here are some example:
---
{{?examples}}
---
Use the examples above to come up with a guide on how to distinguish between {{?options}} {{?key}}.
Use the following format:
```
### **<category 1>**
- <instruction 1>
- <instruction 2>
- <instruction 3>
### **<category 2>**
- <instruction 1>
- <instruction 2>
- <instruction 3>
...
```
When creating the guide:
- make it step-by-step instructions
- Consider than some labels in the examples might be in correct
- Avoid including explicit information from the examples in the guide
The guide has to cover: {{?options}}
"""
),
UserMessage("{{?input}}")
]
)
guides = {}
for i, key in enumerate(["categories", "urgency", "sentiment"]):
options = option_lists[key]
selected_examples_txt_metaprompt = '\n---\n'.join([example_template_metaprompt.format(example_input=example["message"], key=key, example_output=example["ground_truth"][key]) for example in dev_set])
guides[f"guide_{key}"] = send_request(prompt=prompt_get_guide, examples=selected_examples_txt_metaprompt,input=selected_examples_txt_metaprompt, key=key, options=options, _print=False, _model='gpt-4o')
print(guides['guide_urgency'])
このコードでは、データセット内のラベル付きの例から、"カテゴリ"、"緊急度"、"センチメント" などのさまざまなカテゴリのステップバイステップガイドが生成されます。
これにより、テキストデータのカテゴリ、緊急度、およびセンチメントを区別するために調整されたガイドが作成されます。特定のテンプレートを使用して例が書式設定され、ステップバイステップの指示を生成するためにこれらの例がモデルに送信されます。ガイドは、提供されている例のパターンに基づいてこれらのカテゴリを区別するのに役立ちます。
詳細な説明:
テンプレート定義:
- "example_template_metaprompt": サンプルの書式を設定するテンプレートを定義し、例内で入力と出力を構造化する方法を指定します。
- "prompt_get_guide": プロンプト形式の概要を示し、書式設定された例に基づいてガイドの生成を要求します。また、ガイドの書式および要件も指定されており、ステップバイステップの指示、不適切なラベルの可能性、および例の明示的な複製の回避が含まれます。
ガイド準備:
- このスクリプトでは、"カテゴリ"、"緊急度"、"センチメント" の 3 つのキーが繰り返されます。
- キーごとに、"option_lists" から関連オプションが取得されます。
選択および書式設定の例: キーごとに事前定義されたテンプレートを使用して "dev_set" からの例を書式設定し、入力メッセージおよび対応するグラウンドトゥルースを埋め込みます。
ガイド生成:
- 書式化されたプロンプトが例とともにモデル (gpt-4o) に送信され、キーごとに指定されたオプションを区別するためのガイドの生成が要求されます。
- 生成されたガイドはディクショナリ (ガイド) に保存され、各ガイドはそれぞれのキー ("guide_categories"、"guide_emergency"、"guide_sentiment" など) に関連付けられています。
このプロセスにより、さまざまな分類タスクに対して包括的かつ正確な指示ガイドが生成され、テキストデータの正しい分類が容易になります。
コードの最終行には、緊急性に関するガイドが表示されます。
プロンプトで使用できる各緊急カテゴリのルールについて説明するガイドが表示されます。
以下のコードを使用して、これらのガイドをプロンプトで利用します。
12345678910111213141516171819202122232425262728293031prompt_12 = Template(
messages=[
SystemMessage(
"""You are an intelligent assistant. Your task is to classify messages.
This is an explanation of `urgency` labels:
---
{{?guide_urgency}}
---
This is an explanation of `sentiment` labels:
---
{{?guide_sentiment}}
---
This is an explanation of `support` categories:
---
{{?guide_categories}}
---
Giving the following message:
Extract and return a json with the following keys and values:
- "urgency" as one of {{?urgency}}
- "sentiment" as one of {{?sentiment}}
- "categories" list of the best matching support category tags from: {{?categories}}
Your complete message should be a valid json string that can be read directly and only contain the keys mentioned in the list above. Never enclose it in ```json...```, no newlines, no unnessacary whitespaces.
"""
),
UserMessage("{{?input}}")
]
)
f_12 = partial(send_request, prompt=prompt_12, **option_lists, **guides)
response = f_12(input=mail["message"])
コードにより、メタプロンプトコードによって生成された事前定義済ガイドを使用して、緊急度、センチメント、およびサポートカテゴリに基づいてメッセージを分類するためのプロンプトのシステムロールが更新されます。その後、部分関数を使用して、このプロンプトを特定のオプションおよびガイドを含む要求として送信します。最後に、これらの分類を JSON 形式で抽出して返すための電子メールメッセージが処理されます。
以下のコードを使用して、このプロンプトとその応答を評価します。
1234
overall_result["metaprompting--llama3.1-70b"] = evalulation_full_dataset(test_set_small, f_12)
pretty_print_table(overall_result)
以下の出力を取得できます。
1234560%| | 0/20 [00:00<?, ?it/s]
is_valid_json correct_categories correct_sentiment correct_urgency
==============================================================================================
basic--llama3.1-70b 100.0% 83.5% 30.0% 70.0%
few_shot--llama3.1-70b 100.0% 84.0% 50.0% 90.0%
metaprompting--llama3.1-70b 100.0% 90.0% 30.0% 95.0%現在は、緊急度およびカテゴリの精度が向上していますが、センチメントの場合は精度が低下します。
Meta-prompt と Few-shot プロンプトの組み合わせ
以下のコードを使用して、メタプロンプトとfew-shot プロンプトを組み合わせることができます。
1234567891011121314151617181920212223242526272829303132333435363738
prompt_13 = Template(
messages=[
SystemMessage(
"""You are an intelligent assistant. Your task is to classify messages.
Here are some examples:
---
{{?few_shot_examples}}
---
This is an explanation of `urgency` labels:
---
{{?guide_urgency}}
---
This is an explanation of `sentiment` labels:
---
{{?guide_sentiment}}
---
This is an explanation of `support` categories:
---
{{?guide_categories}}
---
Giving the following message:
extract and return a json with the follwoing keys and values:
- "urgency" as one of {{?urgency}}
- "sentiment" as one of {{?sentiment}}
- "categories" list of the best matching support category tags from: {{?categories}}
Your complete message should be a valid json string that can be read directly and only contain the keys mentioned in the list above. Never enclose it in ```json...```, no newlines, no unnessacary whitespaces.
"""
),
UserMessage("{{?input}}")
]
)
f_13 = partial(send_request, prompt=prompt_13, **option_lists, few_shot_examples=examples, **guides)
response = f_13(input=mail["message"])
このコードにより、緊急度、センチメント、およびサポートカテゴリに基づいてメッセージを分類するインテリジェントアシスタントのテンプレートが定義されます。部分アプリケーションを使用して特定の例およびガイドラインで要求処理をカスタマイズし、入力メッセージを処理して構造化された JSON 応答を返します。これにより、正確で効率的なメッセージ分類が可能になります。
いくつかの例をガイドと組み合わせて、メタプロンプトで生成します。
以下のコードを使用して、このプロンプトとその応答を評価します。
1234
overall_result["metaprompting_and_few_shot--llama3.1-70b"] = evalulation_full_dataset(test_set_small, f_13)
pretty_print_table(overall_result)
以下の出力が表示されます。
12345670%| | 0/20 [00:00<?, ?it/s]
is_valid_json correct_categories correct_sentiment correct_urgency
===========================================================================================================
basic--llama3.1-70b 100.0% 83.5% 30.0% 70.0%
few_shot--llama3.1-70b 100.0% 84.0% 50.0% 90.0%
metaprompting--llama3.1-70b 100.0% 90.0% 30.0% 95.0%
metaprompting_and_few_shot--llama3.1-70b 100.0% 88.5% 50.0% 90.0%これで、ほぼすべてのカテゴリの精度が類似しているか、低下していることがわかります。さらに、より多くのリソースを必要とする、より高価なプロンプトです。
注記
ここに表示される応答と、この Learning Journey に表示されるモデルの残りのすべての応答に対して、若干異なる応答が表示される場合があります。
マシンで同じプロンプトを実行すると、LLM はその確率的性質、温度設定、および非決定的アーキテクチャによりさまざまな出力を生成するため、わずかな設定変更や内部状態変化でも応答が異なります。
評価サマリー
モデルの全体的な精度と品質、およびそのコストとスケールを考慮する必要があります。
場合によっては、より小さなモデルや単純な手法の方が良い結果をもたらすことがあります。
前述の出力では、few-shot により低コストのプロンプトで最適なパフォーマンスが得られるのがわかります。
これまでのビジネス上の問題を解決するために何を行ったかをまとめましょう。
- オープンソースモデルを使用して、SAP AI Launchpad で基本プロンプトを作成しました。
- AI 向け SAP Cloud SDK (Python) を使用してプロンプトを再作成し、ソリューションをスケーリングしました。
- 簡易プロンプトのベースライン評価方法を作成しました。
- 最後に、少数のショットやメタプロンプトなどの手法を使用して、プロンプトをさらに拡張しました。
- 結果は、高度な技術を実装した後の速報応答の質の向上を示している。
レッスンのまとめ
Few-shot LLM にコンテキストリッチな例を提供するためのプロンプトと、一貫した動作のための明示的な指示とガイドを生成するためのメタプロンプトなど、主要なプロンプトエンジニアリング手法の実装と評価が完了しました。また、これらの方法の組み合わせについても考察しました。反復的な評価を通じて、AI 向け SAP Cloud SDK で使用されるこれらの手法が LLM 回答の精度と品質を大幅に向上させ、ソリューションをビジネス対応アプリケーションにより近づけると同時に、複雑さとコストに関するトレードオフを理解している様子をご覧いただきました。























