カスタマイズ可能な大規模言語モデルを開発してシンプルなユースケースを解決するための初心者向けガイド
著者: レイチェル・マルティネス | 役割: デベロッパー | タグ: AI エージェント
はじめに
私たちのテクニカルブログへようこそ。ここでは、誰でも理解できるように複雑な概念を紹介しています。今日は、タスクに適応できる大規模言語モデル(LLM)エージェントの開発について取り上げます。
各タスクに最も適したLLMを選択するための堅牢な検索、増強、生成(RAG)インフラストラクチャを作成します。H2OやHuggingFaceのような企業はすでに同様のシステムを立ち上げており、スタートアップ企業から私たちのAIテクノロジーをアプリケーションに統合したいという要望があります。
私たちの特定のユースケースでは、単一の入力(ワンショット)または複数のプロンプトを連結してLLMをプロンプトする機能が必要です。これには、さまざまなシナリオ用のカスタマイズ可能でユーザーフレンドリーなLLMモジュールを作成する必要があります。
この旅に同行してください。各ステップをシンプルかつ魅力的な方法で分解していきます.
現在のユースケース
現在のユースケースでは、ユーザーの履歴書の内容を2ステップのプロセスで強化します:
- 入力: ユーザーは、システムに履歴書の「プロフェッショナルサマリー」および「経験」セクションを入力し、LLMを使用してテキストのより洗練されたバージョンを生成します.
- レビュー: ユーザーは、LLMによって生成されたコンテンツをレビューし、出力を改良およびパーソナライズするために追加のプロンプトまたはガイダンスを提供し、ユニークなスキルや経験と一致するようにします.
このアプローチに従うことで、ユーザーは、LLMの力を利用して、潜在的な雇用主に目立つ魅力的な履歴書を作成できます.
ターゲット
ユースケースをサポートし、少なくとも部分的に履歴書作成プロセスを自動化する、完全にカスタマイズ可能なLLMモジュールを構築することを目指しています.
実装
ステップ1:LLMの選択
必要なLLMを選択する際に、オープンソースLLMとプロプライエタリLLMの2つの主要カテゴリを考慮する必要があります。両方のグループから人気のあるオプションを議論し、オープンソースLLMを選択する利点に焦点を当てます.
オープンソースLLM
例: Mistral AI、Phi 3、LLaMa 3.
利点:
- コミュニティサポート: 大規模で活発な開発者やユーザーのコミュニティがガイダンスを提供し、リソースを共有し、改善に協力しています.
- カスタマイズ性: ソースコードへのアクセスにより、特定のユースケースに合わせた修正や適応が可能です.
- 透明性: モデルの内部動作を理解することは、厳格な倫理やプライバシーガイドラインを持つアプリケーションには不可欠です.
独自のLLM
例: GPT-4.
利点: 感銘的なパフォーマンスとユニークな機能.
限界:
- カスタマイズ性の欠如: モデルをそのまま使用することのみに限定されます.
- コスト: 使用量に基づく料金が時間の経過とともに加算される可能性があります.
- 不透明性: 根底にあるメカニズムを理解することが困難であり、透明性と説明可能性を優先する場合には懸念事項となる可能性があります.
まとめると、オープンソースとプロプライエタリのLLMにはそれぞれメリットとデメリットがあるが、Mistral AI、Phi 3、LLaMa 3のようなオープンソースLLMは、幅広いユーザーにとって非常に有益なアクセシビリティ、カスタマイズ性、透明性を提供する。
ステップ2: コストと機能の検討
オープンソースLLMは通常、コスト効率が高いことが特徴であり、自社のサーバーまたはAzureやAWSのようなプロバイダーを使用して、従量課金制でホストできる。ここでは、さまざまなLLMのホスティングに関するコストと機能の概要を示す。
| LLM | 詳細 | コンテキスト長 | コスト |
|---|---|---|---|
| Mixtral 8x7B | MoE LLM by Mistral A | トレーニング: 8192トークン | 1Mトークンあたり$0.7(安価) |
| ミクストラル 8x22B | ミクストラルの後継 | トレーニング: 32768 トークン | 2/100万トークン (利用可能 |
| LLaMa 3 70B | メタによる非MoEモデル | トレーニング: 2048 トークン | $0.02/1千トークン (アズ |
| フィー 3 128K | メーによるマルチモーダルSLM | トレーニングおよび合計: 3 | $0.002/1千トークン (アズ |
| GPT-4 ターボ | O による独自の LLM | 16K デフォルト、より高い | AWS では利用不可 |
ステップ 3: 公開 API を使用したテスト (OpenRouter に準拠)
最適な LLM を選択してテストするには、さまざまなモデルにアクセスして評価するための効率的な方法が必要です。 OpenRouter は、オープンソースの API 標準であり、さまざまな AI モデルやサービスをシームレスに切り替えることができます。私たちは、Fireworks AI をプロバイダーとして選択しました。なぜなら、
- モデル多様性: 人気のオープンソース LLM の Mistral AI、Phi 3、LLaMa 3 を含む、幅広い AI モデルを提供します。
- 統合の容易さ: OpenRouter 標準に準拠しているため、既存のインフラストラクチャへの統合が簡素化されます。
- スケーラビリティ: 高いリクエスト量を処理し、シームレスにスケールするように設計されています。
ここに、同じハードウェアを使用してモデル応答を呼び出し、待ち時間結果を取得するサンプル関数があります:
import json
def get_sanitized_json_response(user_input, guardrail):
final = chain.invoke({"text": f"Sanitize {user_input}. Guardrail: {guardrail}"})
final = chain.invoke({"text": final.content})
return json.loads(final.content.replace("<json>", "").replace("</json>", "").replace("\n",""))| モデル | 待ち時間 | 備考 |
|---|---|---|
| ミクストラル 8x7B | 2.1秒 | 軽量モデル、パフォーマンス |
| ミクストラル 8x22B | 5.3秒 | 後継モデル、シミュレーション |
| LLaMa 3 70B | 2.6秒 | 適切な応答だが |
| ファイ 3 128K | 1.5 分 | マルチモーダルモデル |
上記をテストするために、非常にシンプルなガードレールと入力が使用されました:
guardrail = """Format details as bullets and use the XYZ method to format the relevant detail.
For example:
- I did X boosting Y percent resulting in Z.
"""呼び出された後、以下のサニタイズされたJSONレスポンスが得られました:
get_sanitized_json_response("""I served as Junior as a Software Engineer at TechCorp in Sydney in January 2011 and worked there until December 2018. During my tenure,
先進的なAI駆動の金融分析ツールを開発するチームを率いて、数百万件のレコードを分散環境で処理するためのツールを開発しました。
会社の独自のデータパイプラインの初期バージョンを作成しました。役割として、ソリューションの設計と複数のAPIの実装を担当しました。
ブロックチェーンソリューションに焦点を当てたチームを管理する最後の1年間で、設計と実装を担当しました。
{'experience': [{'title': 'ソフトウェアエンジニア',
'company': 'TechCorp',
'location': 'シドニー',
'start_date': '2011-01',
'end_date': '2018-12',
'highlights': ['- メジャープロジェクトのスケーラブルなデータベースシステムを設計し、クライアントのデータ処理速度を40%向上させた。',
'- AI駆動のソリューションに焦点を当てたチームを率いた。',
'- 分散環境で100M+のレコードを処理するAI駆動の金融分析ツールを開発した。',
'- 会社の独自のデータパイプラインを作成した。'
ブロックチェーンソリューションのチームを最終年間に管理しました。In conclusion, since the response quality was fairly comparable among all these models, it came down to latency and cost. The experiment was run 3 times achieving very similar results. So we chose Mistral AI’s Mixtral 8x7B due to its favorable balance of latency and cost.
Step 4: Building an Orchestration Layer
Managing and coordinating multiple large-scale language models or a single model across various applications is crucial for optimal performance and adaptability. Instead of building from scratch using vanilla PyTorch, employing an orchestration framework is more practical and efficient. Here are three options:
Langchain
Advantages: Vast array of integrations, supports Python and JavaScript, extensive community support.
Drawbacks: Introduces an additional dependency, potential learning curve.
LlamaIndex
Advantages: Backed by Meta, offers interoperability with Langchain.
Drawbacks: Less developer-friendly syntax.
Haystack
Advantages: User-friendly syntax, supported by prominent tech corporations.
Drawbacks: Limited integrations as it’s still maturing.
Using an orchestration framework simplifies development, improves scalability, and provides access to a supportive community, making it a more favorable choice for our project.
Design and Data Flow
The following image shows the design diagram:
The data flow within our AI-driven system is an essential aspect of ensuring a seamless and efficient user experience. While the design diagram provides a visual representation of the process, a detailed explanation can help clarify the steps involved:
- User Input: The journey begins when the user enters their details, such as the “about” and “experience” sections of their resume, into the system.
- Prompt Generation: The user’s input is then processed and transformed into one or more prompts, which will be used to query the Large Language Model (LLM) for a more polished and impressive version of the text.
- LLM Integration via Langchain: The generated prompts are passed to Langchain, our chosen orchestrator framework, which facilitates the interaction with the LLM client. Langchain leverages a Pydantic schema in the form of a class to parse and validate the data using kor, ensuring that it adheres to the required format.
- JSONResponse Generation: Once the data is validated, it is converted into a final JSONResponse, a structured and easy-to-work-with data format that simplifies further processing and manipulation.
- Content Extraction and Indexing: The content part of the JSONResponse is extracted using kor and indexed by computing embeddings, which are mathematical representations of the text. These embeddings are then stored in a vector database, such as Qdrant, for efficient retrieval and comparison during subsequent queries.
- Caching for Context Module: The entire JSONResponse is cached for the context module to function correctly. This ensures that the system can maintain the context of the user’s input and the LLM’s output during follow-up queries.
- Follow-up Queries: When the user provides additional input or requests further refinement of the generated text, the cached JSONResponse is modified according to the new context and chained to the updated prompt. This modified prompt then goes through the entire process again, from LLM integration to content extraction and indexing, to provide the user with a tailored and accurate response.
By understanding the data flow within our system, we can appreciate the importance of each step and the role of the orchestrator framework in streamlining the process, ultimately resulting in an efficient and user-friendly AI-driven solution.
LCELを使用したプロンプトの構築と連結
これは、サンプルのPromptTemplateの例です:
from langchain.core.output_parsers import PydanticOutputParser
prompt = PromptTemplate(
template="Please extract the following information from the given text and format it as a JSON object according to the schema:\n\n{format_instructions}\n{query}\n",
input_variables=["query"],
partial_variables={"format_instructions": output_parser.get_format_instructions()},
)
chain = prompt | chat_model | output_parser典型的なテンプレートは、2つの主な引数(他にもありますが、それはこのブログの範囲外です)で構成されています。つまり、input_variablesとtemplateです。最初の引数は、実行時にプロンプトテンプレートに注入される文字列のリストを受け取ります。この変数は、通常、Jinja2Templateやf文字列のような動作をします。ここでのchat_modelは、使用しているLLMであり、プロンプトに連結されています。|(パイプ)演算子は、BASHの|演算子と同様に、連結を表します。これは、LCEL(LangChain式言語)仕様によって提供される便利なショートハンドです。これにより、1つのプロンプトの応答を別のプロンプトの入力に連結できます。また、関数呼び出しもサポートされており、通常、出力のサニタイズに使用されるラムダ式や関数を連結できます。これにより、コードの複雑性が減り、連結を簡単に記述できます。
ステップ5: VectorDBsの使用
ベクトルデータベース(VectorDBs)は、高次元ベクトル(LLMによって生成されたテキスト埋め込みなど)を格納、管理、および効率的に検索します。ここでは、人気のあるオプションを比較します:
Qdrant
優点: 高性能、簡単な統合、活発なコミュニティ.
欠点: 特にない.
Milvus
優点: 複数の距離尺度、データ視覚化ツール.
欠点: 学習曲線が急です.
クロマ
長所: 簡単に使用できるPython API、モジュラー設計。
短所: 比較的新しい、コミュニティサポートが十分ではない。
PGベクター
長所: PostgreSQLの機能を活用する、SQLベースのクエリー。
短所: 高次元ベクトル検索ではパフォーマンスが低い。
FAISS
長所: 高性能検索、GPUサポート。
短所: 他のデータベースとの統合が必要。
Qdrantのスケーラビリティ、統合の容易さ、活発な開発により、AI駆動ソリューションに適した選択となる。
堅牢なIRソリューションとしてのVectorDBsの活用
VectorDBsを使用した情報検索(IR)ソリューションの作成には:
- テキスト前処理: 生のテキストデータをクリーン化して前処理する。
- テキスト埋め込み生成: 前処理したテキストを高次元ベクトルに変換するLLMを使用する。
- VectorDBへの埋め込みの保存: 検索を効率的に行うために埋め込みをインデックスする。
- クエリ処理: ユーザーのクエリを前処理して埋め込みに変換する。
- 類似性検索: 関連する埋め込みを見つけるためにVectorDBで類似性検索を実行する。
- ランキングと結果の表示: 取得した埋め込みをランク付けしてテキストに戻して表示する。
このプロセスに従ってVectorDBsを利用することで、効率的で効果的なIRシステムを構築できる。