2024年8月、OpenaiはAPIで強力な新機能を発表しました。これは構造化された出力です。この機能を使用すると、名前が示すように、LLMSが指定した形式でのみ応答を生成するようにすることができます。この機能により、正確なデータフォーマットが必要なアプリケーションの構築が大幅に容易になります。
このチュートリアルでは、OpenAI構造化された出力を開始する方法を学び、その新しい構文を理解し、その主要なアプリケーションを調査します。決定論的応答、つまり、一貫したフォーマットの応答は、データ入力、情報検索、質問回答、マルチステップワークフローなど、多くのタスクにとって重要です。プロンプトが同じであっても、LLMSが非常に異なる形式で出力を生成する方法を経験した可能性があります。 たとえば、
GPT-4O:output:
最初の2つの応答は同じ単一ワード形式でしたが、最後の応答は文全体です。他の下流のアプリケーションが上記のコードの出力に依存している場合、単一単語の応答が予想されていたため、クラッシュしていたでしょう。
# List of hotel reviews reviews = [ "The room was clean and the staff was friendly.", "The location was terrible and the service was slow.", "The food was amazing but the room was too small.", ] # Classify sentiment for each review and print the results for review in reviews: sentiment = classify_sentiment(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
Review: The room was clean and the staff was friendly. Sentiment: Positive Review: The location was terrible and the service was slow. Sentiment: Negative Review: The food was amazing but the room was too small. Sentiment: The sentiment of the review is neutral.
新しい関数、classify_sentiment_with_structured_outputsを使用すると、応答はすべて同じ形式です。
言語モデルを厳格な形式で強制するこの機能は重要であり、他のオープンソースツールへの迅速なエンジニアリングまたは依存の数え切れないほどの時間を節約します。def classify_sentiment_with_structured_outputs(review): """Sentiment classifier with Structured Outputs""" ... # Classify sentiment for each review with Structured Outputs for review in reviews: sentiment = classify_sentiment_with_structured_outputs(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
このセクションでは、センチメントアナライザー関数の例を使用して、構造化された出力を分類します。
環境のセットアップReview: The room was clean and the staff was friendly. Sentiment: {"sentiment":"positive"} Review: The location was terrible and the service was slow. Sentiment: {"sentiment":"negative"} Review: The food was amazing but the room was too small. Sentiment: {"sentiment":"neutral"}
前提条件
開始する前に、次のことを確認してください
OpenAI API
をセットアップします3。インストールの確認:シンプルなPythonスクリプトを作成して、インストールを確認してください:
# List of hotel reviews reviews = [ "The room was clean and the staff was friendly.", "The location was terrible and the service was slow.", "The food was amazing but the room was too small.", ] # Classify sentiment for each review and print the results for review in reviews: sentiment = classify_sentiment(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
スクリプトを実行して、すべてが正しくセットアップされるようにします。モデルの応答が端末に印刷されているのが表示されます。
OpenAIパッケージに加えて、構造化された出力のJSONスキーマを定義および検証するためにPydantic Libraryが必要です。 PIPを使用してインストールします:
Review: The room was clean and the staff was friendly. Sentiment: Positive Review: The location was terrible and the service was slow. Sentiment: Negative Review: The food was amazing but the room was too small. Sentiment: The sentiment of the review is neutral.
この例では、
def classify_sentiment_with_structured_outputs(review): """Sentiment classifier with Structured Outputs""" ... # Classify sentiment for each review with Structured Outputs for review in reviews: sentiment = classify_sentiment_with_structured_outputs(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
モデルには単一のフィールド感情があり、「ポジティブ」、「ネガティブ」、または「ニュートラル」の3つのリテラル値のいずれかしか取ることができません。
気づいた場合、client.chat.completions.createを使用する代わりに、client.beta.chat.completions.parseメソッドを使用しています。 .Parse()は、構造化された出力用に特別に記述されたチャット完了APIの新しい方法です。
さあ、レビューのセンチメント分類器を構造化された出力で書き換えて、すべてをまとめましょう。まず、必要な輸入を作成し、Pydanticモデル、システムプロンプト、およびプロンプトテンプレートを定義します。
関数の重要な線はresponse_format = sentimentResponseです。これは、実際に構造化された出力を有効にするものです。
Review: The room was clean and the staff was friendly. Sentiment: {"sentiment":"positive"} Review: The location was terrible and the service was slow. Sentiment: {"sentiment":"negative"} Review: The food was amazing but the room was too small. Sentiment: {"sentiment":"neutral"}
ここで、結果はメッセージオブジェクトです:
$ pip install -U openai
ご覧のとおり、sentimentResponseクラスのインスタンスがあります。これは、.sentiment属性を使用して辞書の代わりに文字列としてセンチメントにアクセスできることを意味します。
# List of hotel reviews reviews = [ "The room was clean and the staff was friendly.", "The location was terrible and the service was slow.", "The food was amazing but the room was too small.", ] # Classify sentiment for each review and print the results for review in reviews: sentiment = classify_sentiment(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
名前、連絡先の詳細、アドレスのリストなど、詳細なユーザー情報を抽出する必要がある例を考えてみましょう。各アドレスには、通り、都市、州、郵便番号のフィールドを含める必要があります。これには、正しいスキーマを構築するには複数のPydanticモデルが必要です。
ステップ1:Pydanticモデルを定義します最初に、アドレスとユーザー情報のPydanticモデルを定義します。
Review: The room was clean and the staff was friendly. Sentiment: Positive Review: The location was terrible and the service was slow. Sentiment: Negative Review: The food was amazing but the room was too small. Sentiment: The sentiment of the review is neutral.
userInfoは、ユーザーの名前、電子メール、電話番号のフィールドとともに、アドレスオブジェクトのリストを含むPydanticモデルです。
新しい言語モデルの広範な機能の1つは、関数呼び出し(ツール呼び出しとも呼ばれます)です。この機能により、言語モデルをユーザー定義関数に接続し、効果的に(モデル)外部の世界へのアクセスを提供できます。
def classify_sentiment_with_structured_outputs(review): """Sentiment classifier with Structured Outputs""" ... # Classify sentiment for each review with Structured Outputs for review in reviews: sentiment = classify_sentiment_with_structured_outputs(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
リアルタイムデータの取得(たとえば、天気、株価、スポーツスコア)
Review: The room was clean and the staff was friendly. Sentiment: {"sentiment":"positive"} Review: The location was terrible and the service was slow. Sentiment: {"sentiment":"negative"} Review: The food was amazing but the room was too small. Sentiment: {"sentiment":"neutral"}
計算またはデータ分析の実行
データベースまたはapisのクエリ 画像またはその他のメディアを生成する言語間でテキストを翻訳します
スマートホームデバイスまたはIoTシステムの制御 カスタムビジネスロジックまたはワークフローの実行知っておくべき重要なのは、構造化された出力を使用すると、OpenAIモデルで関数呼び出しを使用することが非常に簡単であることです。過去には、OpenAIモデルに渡す機能には、複雑なJSONスキーマを作成し、すべての関数パラメーターをタイプのヒントで概説する必要があります。例は次のとおりです。
# List of hotel reviews reviews = [ "The room was clean and the staff was friendly.", "The location was terrible and the service was slow.", "The food was amazing but the room was too small.", ] # Classify sentiment for each review and print the results for review in reviews: sentiment = classify_sentiment(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
get_current_weather関数には2つのパラメーターがありますが、そのjsonスキーマは巨大になり、エラーが発生しなくなります。
これは、Pydanticモデルを再度使用することにより、構造化された出力で解決されます:
Review: The room was clean and the staff was friendly. Sentiment: Positive Review: The location was terrible and the service was slow. Sentiment: Negative Review: The food was amazing but the room was too small. Sentiment: The sentiment of the review is neutral.
次に、Pydanticモデルを互換性のあるJSONスキーマに変換するには、pydantic_function_tool:
を呼び出しますこのツールをリクエストの一部として使用する方法は次のとおりです。
def classify_sentiment_with_structured_outputs(review): """Sentiment classifier with Structured Outputs""" ... # Classify sentiment for each review with Structured Outputs for review in reviews: sentiment = classify_sentiment_with_structured_outputs(review) print(f"Review: {review}\nSentiment: {sentiment}\n")
互換性のあるJSON形式でPydanticモデルを渡し、Chat Completions APIのツールパラメーターに渡します。次に、クエリに応じて、モデルはツールを呼び出すかどうかを決定します。 上記の例でのクエリは「東京の天気は何ですか?」であるため、返されたメッセージオブジェクトのtool_callsに呼び出しが表示されます。
覚えておいてください、モデルはget_weather関数を呼び出すのではなく、私たちが提供したpydanticスキーマに基づいてそれについての引数を生成します:Review: The room was clean and the staff was friendly. Sentiment: {"sentiment":"positive"} Review: The location was terrible and the service was slow. Sentiment: {"sentiment":"negative"} Review: The food was amazing but the room was too small. Sentiment: {"sentiment":"neutral"}
提供された引数で関数を呼び出すのは私たち次第です:
モデルに関数の引数を生成して同時に呼び出す場合は、AIエージェントを探しています。
$ pip install -U openai
OpenAI構造化された出力を使用する場合のベストプラクティス
$ export OPENAI_API_KEY='your-api-key'
Pydanticモデルを使用して出力スキーマを定義します。これは、予想される出力構造を定義するためのクリーンでタイプの安全な方法を提供するためです。
スキーマをシンプルかつ具体的に保ち、最も正確な結果を得る。enumsにリテラルタイプを使用して、フィールドの特定の許可された値を定義します。
モデルの拒否を処理します。 new .Parse()メソッドを使用する場合、メッセージオブジェクトには拒否を示す新しい.Refusal属性があります:ここにあなたの理解を高めるためのいくつかの関連するソースがあります:
OpenAI APIコースの操作
以上がOpenAI構造化された出力を開始しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。