Cohere Command チャット モデルの使用方法

重要

この記事で説明する機能の一部は、プレビューでのみ使用できる場合があります。 このプレビューはサービス レベル アグリーメントなしで提供されており、運用環境ではお勧めしません。 特定の機能はサポート対象ではなく、機能が制限されることがあります。 詳しくは、Microsoft Azure プレビューの追加使用条件に関するページをご覧ください。

この記事では、Cohere Command チャット モデルとその使用方法について説明します。 Cohere のモデル ファミリには、チャット入力候補、埋め込み、再ランク付けなど、さまざまなユース ケースに最適化されたモデルがあります。 Cohere のモデルは、推論、要約、質問応答など、さまざまなユース ケースに最適化されています。

Cohere Command チャット モデル

Cohere Command チャット モデルには、次のようなモデルが含まれます。

Command R+ は、推論、要約、質問応答など、さまざまなユース ケース向けに最適化された、生成の大規模言語モデルです。

  • モデル アーキテクチャ: Command R と Command R+ はどちらも、最適化されたトランスフォーマー アーキテクチャを使用する自己回帰言語モデルです。 事前トレーニング後、これらのモデルでは、教師あり微調整 (SFT) と優先トレーニングを使用して、モデルの動作を人間の好みに合わせて調整し、有用性と安全性を確保します。
  • 対象言語: これらのモデルは、英語、フランス語、スペイン語、イタリア語、ドイツ語、ポルトガル語 (ブラジル)、日本語、韓国語、簡体中国語、アラビア語の言語で適切に動作するように最適化されています。
  • 事前トレーニング データには、次の 13 言語も含まれています: ロシア語、ポーランド語、トルコ語、ベトナム語、オランダ語、チェコ語、インドネシア語、ウクライナ語、ルーマニア語、ギリシャ語、ヒンディー語、ヘブライ語、ペルシャ語。
  • コンテキストの長さ: Command R と Command R+ では、コンテキストの長さ 128 K をサポートしています。

複雑な取得拡張生成 (RAG) 機能や複数ステップ ツールの使用 (エージェント) が必要なワークフローには、Command R+ の使用をお勧めします。

以下のモデルが使用可能です:

ヒント

さらに、Cohere は、モデルの特定の機能で使用するためにカスタマイズされた API の使用をサポートしています。 モデル プロバイダー固有の API を使用するには、Cohere ドキュメントを確認するか、コード例への推論の例セクションを参照してください。

前提条件

Azure AI Studio で Cohere Command チャット モデルを使用するには、次の前提条件を満たす必要があります。

モデル デプロイ

サーバーレス API へのデプロイ

Cohere Command チャット モデルは、従量課金制でサーバーレス API エンドポイントにデプロイできます。 この種類のデプロイは、組織が必要とする企業レベルのセキュリティとコンプライアンスを維持しながら、サブスクリプションでホストせずに API としてモデルを使用する方法を提供します。

サーバーレス API エンドポイントへのデプロイでは、サブスクリプションからのクォータは必要ありません。 モデルがまだデプロイされていない場合は、Azure AI Studio、Azure Machine Learning SDK for Python、Azure CLI、または ARM テンプレートを使用して、モデルをサーバーレス API としてデプロイします。

インストールされている推論パッケージ

Python で azure-ai-inference パッケージを使用して、このモデルから予測を実行できます。 このパッケージをインストールするには、次の前提条件を満たす必要があります。

  • Python 3.8 以降 (PIP を含む) がインストールされている
  • エンドポイント URL。 クライアント ライブラリを構築するには、エンドポイント URL を渡す必要があります。 エンドポイント URL の形式は https://your-host-name.your-azure-region.inference.ai.azure.com です。ここで、your-host-name は一意のモデル デプロイ ホスト名、your-azure-region はモデルがデプロイされている Azure リージョン (eastus2 など) です。
  • モデル デプロイと認証の設定に応じて、サービスに対する認証キーまたは Microsoft Entra ID 認証情報が必要です。 キーは 32 文字の文字列です。

これらの前提条件が満たされたら、次のコマンドを使用して Azure AI 推論パッケージをインストールします。

pip install azure-ai-inference

Azure AI 推論パッケージとリファレンスに関する詳細をご覧ください。

チャット入力候補を使用する

このセクションでは、Azure AI モデル推論 API をチャットのチャット入力候補モデルで使用します。

ヒント

Azure AI モデル推論 API を使用すると、Cohere Command チャット モデルなど、同じコードと構造で Azure AI Studio にデプロイされたほとんどのモデルと対話できます。

モデルを実行するクライアントを作成する

まず、モデルを実行するクライアントを作成します。 次のコードでは、環境変数に格納されているエンドポイント URL とキーを使用しています。

import os
from azure.ai.inference import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential

client = ChatCompletionsClient(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["AZURE_INFERENCE_CREDENTIAL"]),
)

モデルの機能を取得する

/info ルートは、エンドポイントにデプロイされたモデルに関する情報を返します。 次のメソッドを呼び出してモデルの情報を返します。

model_info = client.get_model_info()

応答は次のとおりです。

print("Model name:", model_info.model_name)
print("Model type:", model_info.model_type)
print("Model provider name:", model_info.model_provider_name)
Model name: Cohere-command-r-plus
Model type: chat-completions
Model provider name: Cohere

チャット入力候補要求を作成する

次の例に、モデルに対する基本的なチャット入力候補要求を作成する方法を示します。

from azure.ai.inference.models import SystemMessage, UserMessage

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many languages are in the world?"),
    ],
)

応答は次のとおりです。モデルの使用状況の統計情報が表示されます。

print("Response:", response.choices[0].message.content)
print("Model:", response.model)
print("Usage:")
print("\tPrompt tokens:", response.usage.prompt_tokens)
print("\tTotal tokens:", response.usage.total_tokens)
print("\tCompletion tokens:", response.usage.completion_tokens)
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: Cohere-command-r-plus
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

応答の usage セクションを調べて、プロンプトに使用されたトークンの数、生成されたトークンの合計数、入力候補に使用されたトークンの数を確認します。

コンテンツのストリーミング

既定では、入力候補 API は生成されたコンテンツ全体を 1 つの応答で返します。 長い入力候補を生成する場合、応答が得られるまでに数秒かかることがあります。

コンテンツをストリーミングして、コンテンツが生成されるにつれ返されるようにできます。 コンテンツをストリーミングすると、コンテンツが使用可能になったときに入力候補の処理を開始できます。 このモードは、データのみのサーバー送信イベントとして応答をストリーム バックするオブジェクトを返します。 メッセージ フィールドではなく、デルタ フィールドからチャンクを抽出します。

result = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many languages are in the world?"),
    ],
    temperature=0,
    top_p=1,
    max_tokens=2048,
    stream=True,
)

入力候補をストリーミングするには、モデルを呼び出すときに stream=True を設定します。

出力を視覚化するには、ストリームを出力するヘルパー関数を定義します。

def print_stream(result):
    """
    Prints the chat completion with streaming.
    """
    import time
    for update in result:
        if update.choices:
            print(update.choices[0].delta.content, end="")

ストリーミングでコンテンツがどのように生成されるかを視覚化できます。

print_stream(result)

推論クライアントでサポートされているその他のパラメーターを確認する

推論クライアントで指定できるその他のパラメーターを確認します。 サポートされているすべてのパラメーターとそれらのドキュメントの完全な一覧については、Azure AI モデル推論 API リファレンスを参照してください。

from azure.ai.inference.models import ChatCompletionsResponseFormatText

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many languages are in the world?"),
    ],
    presence_penalty=0.1,
    frequency_penalty=0.8,
    max_tokens=2048,
    stop=["<|endoftext|>"],
    temperature=0,
    top_p=1,
    response_format=ChatCompletionsResponseFormatText(),
)

サポートされているパラメーターの一覧にないパラメーターを渡す場合は、追加のパラメーターを使用して、基になるモデルに渡すことができます。 「モデルに追加のパラメーターを渡す」を参照してください。

JSON 出力を作成する

Cohere Command チャット モデルでは JSON 出力を作成できます。 response_formatjson_object に設定すると JSON モードが有効になり、モデルが生成するメッセージが有効な JSON であることが保証されます。 システムまたはユーザー メッセージを使って、ユーザー自身が JSON を生成することをモデルに指示する必要もあります。 また、生成が max_tokens を超えたか、会話がコンテキストの最大長を超えたことを示す finish_reason="length" の場合、メッセージの内容が部分的に切り取られる可能性があります。

from azure.ai.inference.models import ChatCompletionsResponseFormatJSON

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant that always generate responses in JSON format, using."
                      " the following format: { ""answer"": ""response"" }."),
        UserMessage(content="How many languages are in the world?"),
    ],
    response_format=ChatCompletionsResponseFormatJSON()
)

モデルに追加のパラメーターを渡す

Azure AI モデル推論 API を使用すると、モデルに追加のパラメーターを渡すことができます。 次のコード例に、モデルに追加のパラメーター logprobs を渡す方法を示します。

Azure AI モデル推論 API に追加のパラメーターを渡す前に、モデルでこれらの追加パラメーターがサポートされていることを確認してください。 基になるモデルに要求を行うと、ヘッダー extra-parameters が値 pass-through でモデルに渡されます。 この値は、追加のパラメーターをモデルに渡すようエンドポイントに指示します。 モデルで追加のパラメーターを使用しても、モデルで実際に処理できるとは限りません。 モデルのドキュメントを参照して、サポートされている追加パラメーターを確認してください。

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many languages are in the world?"),
    ],
    model_extras={
        "logprobs": True
    }
)

ツールの使用

Cohere Command チャット モデルではツールの使用がサポートされており、言語モデルから特定のタスクをオフロードし、より決定論的なシステムや別の言語モデルに依存する必要がある場合に、特別なリソースになります。 Azure AI Model Inference API では、次のようにツールを定義できます。

次のコード例では、2 つの異なる都市からのフライト情報を検索できるツール定義を作成します。

from azure.ai.inference.models import FunctionDefinition, ChatCompletionsFunctionToolDefinition

flight_info = ChatCompletionsFunctionToolDefinition(
    function=FunctionDefinition(
        name="get_flight_info",
        description="Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
        parameters={
            "type": "object",
            "properties": {
                "origin_city": {
                    "type": "string",
                    "description": "The name of the city where the flight originates",
                },
                "destination_city": {
                    "type": "string",
                    "description": "The flight destination city",
                },
            },
            "required": ["origin_city", "destination_city"],
        },
    )
)

tools = [flight_info]

この例では、関数の出力では選択されたルートで利用可能なフライトがないため、ユーザーは電車に乗ることを検討する必要があります。

def get_flight_info(loc_origin: str, loc_destination: str):
    return { 
        "info": f"There are no flights available from {loc_origin} to {loc_destination}. You should take a train, specially if it helps to reduce CO2 emissions."
    }

Note

Cohere-command-r-plus および Cohere-command-r では、ツールの応答が文字列として書式設定された有効な JSON コンテンツであることが必要です。 Tool 型のメッセージを構築する場合、応答が有効な JSON 文字列であることを確認してください。

この機能を使用して、モデルにフライトの予約を求めます。

messages = [
    SystemMessage(
        content="You are a helpful assistant that help users to find information about traveling, how to get"
                " to places and the different transportations options. You care about the environment and you"
                " always have that in mind when answering inqueries.",
    ),
    UserMessage(
        content="When is the next flight from Miami to Seattle?",
    ),
]

response = client.complete(
    messages=messages, tools=tools, tool_choice="auto"
)

ツールを呼び出す必要があるかどうかを調べるために、応答を検査できます。 ツールを呼び出す必要があるか判断するために、終了した理由を検査します。 複数のツールの種類を指定できることを忘れないでください。 この例は、種類 function のツールを示しています。

response_message = response.choices[0].message
tool_calls = response_message.tool_calls

print("Finish reason:", response.choices[0].finish_reason)
print("Tool call:", tool_calls)

続行するには、このメッセージをチャット履歴に追加します。

messages.append(
    response_message
)

ここで、ツール呼び出しを処理するための適切な関数を呼び出します。 次のコード スニペットは、応答に示されたすべてのツール呼び出しを反復処理し、適切なパラメーターを指定して対応する関数を呼び出します。 応答はチャット履歴にも追加されます。

import json
from azure.ai.inference.models import ToolMessage

for tool_call in tool_calls:

    # Get the tool details:

    function_name = tool_call.function.name
    function_args = json.loads(tool_call.function.arguments.replace("\'", "\""))
    tool_call_id = tool_call.id

    print(f"Calling function `{function_name}` with arguments {function_args}")

    # Call the function defined above using `locals()`, which returns the list of all functions 
    # available in the scope as a dictionary. Notice that this is just done as a simple way to get
    # the function callable from its string name. Then we can call it with the corresponding
    # arguments.

    callable_func = locals()[function_name]
    function_response = callable_func(**function_args)

    print("->", function_response)

    # Once we have a response from the function and its arguments, we can append a new message to the chat 
    # history. Notice how we are telling to the model that this chat message came from a tool:

    messages.append(
        ToolMessage(
            tool_call_id=tool_call_id,
            content=json.dumps(function_response)
        )
    )

モデルからの応答を表示します。

response = client.complete(
    messages=messages,
    tools=tools,
)

コンテンツの安全性を適用する

Azure AI モデル推論 API は、Azure AI Content Safety をサポートしています。 Azure AI Content Safety をオンにしてデプロイを使用すると、入力と出力は、有害なコンテンツの出力を検出して防ぐことを目的とした一連の分類モデルを通過します。 コンテンツ フィルタリング システムは、入力プロンプトと (出力される) 入力候補の両方で、有害な可能性があるコンテンツ特有のカテゴリを検出し、アクションを実行します。

次の例に、モデルが入力プロンプトで有害なコンテンツを検出し、コンテンツの安全性が有効になっている場合にイベントを処理する方法を示しています。

from azure.ai.inference.models import AssistantMessage, UserMessage, SystemMessage

try:
    response = client.complete(
        messages=[
            SystemMessage(content="You are an AI assistant that helps people find information."),
            UserMessage(content="Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."),
        ]
    )

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

except HttpResponseError as ex:
    if ex.status_code == 400:
        response = ex.response.json()
        if isinstance(response, dict) and "error" in response:
            print(f"Your request triggered an {response['error']['code']} error:\n\t {response['error']['message']}")
        else:
            raise
    raise

ヒント

Azure AI Content Safety 設定を構成および制御する方法の詳細については、Azure AI Content Safety のドキュメントを参照してください。

Cohere Command チャット モデル

Cohere Command チャット モデルには、次のようなモデルが含まれます。

Command R+ は、推論、要約、質問応答など、さまざまなユース ケース向けに最適化された、生成の大規模言語モデルです。

  • モデル アーキテクチャ: Command R と Command R+ はどちらも、最適化されたトランスフォーマー アーキテクチャを使用する自己回帰言語モデルです。 事前トレーニング後、これらのモデルでは、教師あり微調整 (SFT) と優先トレーニングを使用して、モデルの動作を人間の好みに合わせて調整し、有用性と安全性を確保します。
  • 対象言語: これらのモデルは、英語、フランス語、スペイン語、イタリア語、ドイツ語、ポルトガル語 (ブラジル)、日本語、韓国語、簡体中国語、アラビア語の言語で適切に動作するように最適化されています。
  • 事前トレーニング データには、次の 13 言語も含まれています: ロシア語、ポーランド語、トルコ語、ベトナム語、オランダ語、チェコ語、インドネシア語、ウクライナ語、ルーマニア語、ギリシャ語、ヒンディー語、ヘブライ語、ペルシャ語。
  • コンテキストの長さ: Command R と Command R+ では、コンテキストの長さ 128 K をサポートしています。

複雑な取得拡張生成 (RAG) 機能や複数ステップ ツールの使用 (エージェント) が必要なワークフローには、Command R+ の使用をお勧めします。

以下のモデルが使用可能です:

ヒント

さらに、Cohere は、モデルの特定の機能で使用するためにカスタマイズされた API の使用をサポートしています。 モデル プロバイダー固有の API を使用するには、Cohere ドキュメントを確認するか、コード例への推論の例セクションを参照してください。

前提条件

Azure AI Studio で Cohere Command チャット モデルを使用するには、次の前提条件を満たす必要があります。

モデル デプロイ

サーバーレス API へのデプロイ

Cohere Command チャット モデルは、従量課金制でサーバーレス API エンドポイントにデプロイできます。 この種類のデプロイは、組織が必要とする企業レベルのセキュリティとコンプライアンスを維持しながら、サブスクリプションでホストせずに API としてモデルを使用する方法を提供します。

サーバーレス API エンドポイントへのデプロイでは、サブスクリプションからのクォータは必要ありません。 モデルがまだデプロイされていない場合は、Azure AI Studio、Azure Machine Learning SDK for Python、Azure CLI、または ARM テンプレートを使用して、モデルをサーバーレス API としてデプロイします。

インストールされている推論パッケージ

npm から @azure-rest/ai-inference パッケージを使用して、このモデルから予測を実行できます。 このパッケージをインストールするには、次の前提条件を満たす必要があります。

  • Node.js の LTS バージョン (npm を含む)
  • エンドポイント URL。 クライアント ライブラリを構築するには、エンドポイント URL を渡す必要があります。 エンドポイント URL の形式は https://your-host-name.your-azure-region.inference.ai.azure.com です。ここで、your-host-name は一意のモデル デプロイ ホスト名、your-azure-region はモデルがデプロイされている Azure リージョン (eastus2 など) です。
  • モデル デプロイと認証の設定に応じて、サービスに対する認証キーまたは Microsoft Entra ID 認証情報が必要です。 キーは 32 文字の文字列です。

これらの前提条件が満たされたら、次のコマンドを使用して JavaScript 用 Azure 推論ライブラリ パッケージをインストールします。

npm install @azure-rest/ai-inference

チャット入力候補を使用する

このセクションでは、Azure AI モデル推論 API をチャットのチャット入力候補モデルで使用します。

ヒント

Azure AI モデル推論 API を使用すると、Cohere Command チャット モデルなど、同じコードと構造で Azure AI Studio にデプロイされたほとんどのモデルと対話できます。

モデルを実行するクライアントを作成する

まず、モデルを実行するクライアントを作成します。 次のコードでは、環境変数に格納されているエンドポイント URL とキーを使用しています。

import ModelClient from "@azure-rest/ai-inference";
import { isUnexpected } from "@azure-rest/ai-inference";
import { AzureKeyCredential } from "@azure/core-auth";

const client = new ModelClient(
    process.env.AZURE_INFERENCE_ENDPOINT, 
    new AzureKeyCredential(process.env.AZURE_INFERENCE_CREDENTIAL)
);

モデルの機能を取得する

/info ルートは、エンドポイントにデプロイされたモデルに関する情報を返します。 次のメソッドを呼び出してモデルの情報を返します。

var model_info = await client.path("/info").get()

応答は次のとおりです。

console.log("Model name: ", model_info.body.model_name)
console.log("Model type: ", model_info.body.model_type)
console.log("Model provider name: ", model_info.body.model_provider_name)
Model name: Cohere-command-r-plus
Model type: chat-completions
Model provider name: Cohere

チャット入力候補要求を作成する

次の例に、モデルに対する基本的なチャット入力候補要求を作成する方法を示します。

var messages = [
    { role: "system", content: "You are a helpful assistant" },
    { role: "user", content: "How many languages are in the world?" },
];

var response = await client.path("/chat/completions").post({
    body: {
        messages: messages,
    }
});

応答は次のとおりです。モデルの使用状況の統計情報が表示されます。

if (isUnexpected(response)) {
    throw response.body.error;
}

console.log("Response: ", response.body.choices[0].message.content);
console.log("Model: ", response.body.model);
console.log("Usage:");
console.log("\tPrompt tokens:", response.body.usage.prompt_tokens);
console.log("\tTotal tokens:", response.body.usage.total_tokens);
console.log("\tCompletion tokens:", response.body.usage.completion_tokens);
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: Cohere-command-r-plus
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

応答の usage セクションを調べて、プロンプトに使用されたトークンの数、生成されたトークンの合計数、入力候補に使用されたトークンの数を確認します。

コンテンツのストリーミング

既定では、入力候補 API は生成されたコンテンツ全体を 1 つの応答で返します。 長い入力候補を生成する場合、応答が得られるまでに数秒かかることがあります。

コンテンツをストリーミングして、コンテンツが生成されるにつれ返されるようにできます。 コンテンツをストリーミングすると、コンテンツが使用可能になったときに入力候補の処理を開始できます。 このモードは、データのみのサーバー送信イベントとして応答をストリーム バックするオブジェクトを返します。 メッセージ フィールドではなく、デルタ フィールドからチャンクを抽出します。

var messages = [
    { role: "system", content: "You are a helpful assistant" },
    { role: "user", content: "How many languages are in the world?" },
];

var response = await client.path("/chat/completions").post({
    body: {
        messages: messages,
    }
}).asNodeStream();

入力候補をストリーミングするには、モデルを呼び出すときに .asNodeStream() を使用します。

ストリーミングでコンテンツがどのように生成されるかを視覚化できます。

var stream = response.body;
if (!stream) {
    stream.destroy();
    throw new Error(`Failed to get chat completions with status: ${response.status}`);
}

if (response.status !== "200") {
    throw new Error(`Failed to get chat completions: ${response.body.error}`);
}

var sses = createSseStream(stream);

for await (const event of sses) {
    if (event.data === "[DONE]") {
        return;
    }
    for (const choice of (JSON.parse(event.data)).choices) {
        console.log(choice.delta?.content ?? "");
    }
}

推論クライアントでサポートされているその他のパラメーターを確認する

推論クライアントで指定できるその他のパラメーターを確認します。 サポートされているすべてのパラメーターとそれらのドキュメントの完全な一覧については、Azure AI モデル推論 API リファレンスを参照してください。

var messages = [
    { role: "system", content: "You are a helpful assistant" },
    { role: "user", content: "How many languages are in the world?" },
];

var response = await client.path("/chat/completions").post({
    body: {
        messages: messages,
        presence_penalty: "0.1",
        frequency_penalty: "0.8",
        max_tokens: 2048,
        stop: ["<|endoftext|>"],
        temperature: 0,
        top_p: 1,
        response_format: { type: "text" },
    }
});

サポートされているパラメーターの一覧にないパラメーターを渡す場合は、追加のパラメーターを使用して、基になるモデルに渡すことができます。 「モデルに追加のパラメーターを渡す」を参照してください。

JSON 出力を作成する

Cohere Command チャット モデルでは JSON 出力を作成できます。 response_formatjson_object に設定すると JSON モードが有効になり、モデルが生成するメッセージが有効な JSON であることが保証されます。 システムまたはユーザー メッセージを使って、ユーザー自身が JSON を生成することをモデルに指示する必要もあります。 また、生成が max_tokens を超えたか、会話がコンテキストの最大長を超えたことを示す finish_reason="length" の場合、メッセージの内容が部分的に切り取られる可能性があります。

var messages = [
    { role: "system", content: "You are a helpful assistant that always generate responses in JSON format, using."
        + " the following format: { \"answer\": \"response\" }." },
    { role: "user", content: "How many languages are in the world?" },
];

var response = await client.path("/chat/completions").post({
    body: {
        messages: messages,
        response_format: { type: "json_object" }
    }
});

モデルに追加のパラメーターを渡す

Azure AI モデル推論 API を使用すると、モデルに追加のパラメーターを渡すことができます。 次のコード例に、モデルに追加のパラメーター logprobs を渡す方法を示します。

Azure AI モデル推論 API に追加のパラメーターを渡す前に、モデルでこれらの追加パラメーターがサポートされていることを確認してください。 基になるモデルに要求を行うと、ヘッダー extra-parameters が値 pass-through でモデルに渡されます。 この値は、追加のパラメーターをモデルに渡すようエンドポイントに指示します。 モデルで追加のパラメーターを使用しても、モデルで実際に処理できるとは限りません。 モデルのドキュメントを参照して、サポートされている追加パラメーターを確認してください。

var messages = [
    { role: "system", content: "You are a helpful assistant" },
    { role: "user", content: "How many languages are in the world?" },
];

var response = await client.path("/chat/completions").post({
    headers: {
        "extra-params": "pass-through"
    },
    body: {
        messages: messages,
        logprobs: true
    }
});

ツールの使用

Cohere Command チャット モデルではツールの使用がサポートされており、言語モデルから特定のタスクをオフロードし、より決定論的なシステムや別の言語モデルに依存する必要がある場合に、特別なリソースになります。 Azure AI Model Inference API では、次のようにツールを定義できます。

次のコード例では、2 つの異なる都市からのフライト情報を検索できるツール定義を作成します。

const flight_info = {
    name: "get_flight_info",
    description: "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
    parameters: {
        type: "object",
        properties: {
            origin_city: {
                type: "string",
                description: "The name of the city where the flight originates",
            },
            destination_city: {
                type: "string",
                description: "The flight destination city",
            },
        },
        required: ["origin_city", "destination_city"],
    },
}

const tools = [
    {
        type: "function",
        function: flight_info,
    },
];

この例では、関数の出力では選択されたルートで利用可能なフライトがないため、ユーザーは電車に乗ることを検討する必要があります。

function get_flight_info(loc_origin, loc_destination) {
    return {
        info: "There are no flights available from " + loc_origin + " to " + loc_destination + ". You should take a train, specially if it helps to reduce CO2 emissions."
    }
}

Note

Cohere-command-r-plus および Cohere-command-r では、ツールの応答が文字列として書式設定された有効な JSON コンテンツであることが必要です。 Tool 型のメッセージを構築する場合、応答が有効な JSON 文字列であることを確認してください。

この機能を使用して、モデルにフライトの予約を求めます。

var result = await client.path("/chat/completions").post({
    body: {
        messages: messages,
        tools: tools,
        tool_choice: "auto"
    }
});

ツールを呼び出す必要があるかどうかを調べるために、応答を検査できます。 ツールを呼び出す必要があるか判断するために、終了した理由を検査します。 複数のツールの種類を指定できることを忘れないでください。 この例は、種類 function のツールを示しています。

const response_message = response.body.choices[0].message;
const tool_calls = response_message.tool_calls;

console.log("Finish reason: " + response.body.choices[0].finish_reason);
console.log("Tool call: " + tool_calls);

続行するには、このメッセージをチャット履歴に追加します。

messages.push(response_message);

ここで、ツール呼び出しを処理するための適切な関数を呼び出します。 次のコード スニペットは、応答に示されたすべてのツール呼び出しを反復処理し、適切なパラメーターを指定して対応する関数を呼び出します。 応答はチャット履歴にも追加されます。

function applyToolCall({ function: call, id }) {
    // Get the tool details:
    const tool_params = JSON.parse(call.arguments);
    console.log("Calling function " + call.name + " with arguments " + tool_params);

    // Call the function defined above using `window`, which returns the list of all functions 
    // available in the scope as a dictionary. Notice that this is just done as a simple way to get
    // the function callable from its string name. Then we can call it with the corresponding
    // arguments.
    const function_response = tool_params.map(window[call.name]);
    console.log("-> " + function_response);

    return function_response
}

for (const tool_call of tool_calls) {
    var tool_response = tool_call.apply(applyToolCall);

    messages.push(
        {
            role: "tool",
            tool_call_id: tool_call.id,
            content: tool_response
        }
    );
}

モデルからの応答を表示します。

var result = await client.path("/chat/completions").post({
    body: {
        messages: messages,
        tools: tools,
    }
});

コンテンツの安全性を適用する

Azure AI モデル推論 API は、Azure AI Content Safety をサポートしています。 Azure AI Content Safety をオンにしてデプロイを使用すると、入力と出力は、有害なコンテンツの出力を検出して防ぐことを目的とした一連の分類モデルを通過します。 コンテンツ フィルタリング システムは、入力プロンプトと (出力される) 入力候補の両方で、有害な可能性があるコンテンツ特有のカテゴリを検出し、アクションを実行します。

次の例に、モデルが入力プロンプトで有害なコンテンツを検出し、コンテンツの安全性が有効になっている場合にイベントを処理する方法を示しています。

try {
    var messages = [
        { role: "system", content: "You are an AI assistant that helps people find information." },
        { role: "user", content: "Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills." },
    ];

    var response = await client.path("/chat/completions").post({
        body: {
            messages: messages,
        }
    });

    console.log(response.body.choices[0].message.content);
}
catch (error) {
    if (error.status_code == 400) {
        var response = JSON.parse(error.response._content);
        if (response.error) {
            console.log(`Your request triggered an ${response.error.code} error:\n\t ${response.error.message}`);
        }
        else
        {
            throw error;
        }
    }
}

ヒント

Azure AI Content Safety 設定を構成および制御する方法の詳細については、Azure AI Content Safety のドキュメントを参照してください。

Cohere Command チャット モデル

Cohere Command チャット モデルには、次のようなモデルが含まれます。

Command R+ は、推論、要約、質問応答など、さまざまなユース ケース向けに最適化された、生成の大規模言語モデルです。

  • モデル アーキテクチャ: Command R と Command R+ はどちらも、最適化されたトランスフォーマー アーキテクチャを使用する自己回帰言語モデルです。 事前トレーニング後、これらのモデルでは、教師あり微調整 (SFT) と優先トレーニングを使用して、モデルの動作を人間の好みに合わせて調整し、有用性と安全性を確保します。
  • 対象言語: これらのモデルは、英語、フランス語、スペイン語、イタリア語、ドイツ語、ポルトガル語 (ブラジル)、日本語、韓国語、簡体中国語、アラビア語の言語で適切に動作するように最適化されています。
  • 事前トレーニング データには、次の 13 言語も含まれています: ロシア語、ポーランド語、トルコ語、ベトナム語、オランダ語、チェコ語、インドネシア語、ウクライナ語、ルーマニア語、ギリシャ語、ヒンディー語、ヘブライ語、ペルシャ語。
  • コンテキストの長さ: Command R と Command R+ では、コンテキストの長さ 128 K をサポートしています。

複雑な取得拡張生成 (RAG) 機能や複数ステップ ツールの使用 (エージェント) が必要なワークフローには、Command R+ の使用をお勧めします。

以下のモデルが使用可能です:

ヒント

さらに、Cohere は、モデルの特定の機能で使用するためにカスタマイズされた API の使用をサポートしています。 モデル プロバイダー固有の API を使用するには、Cohere ドキュメントを確認するか、コード例への推論の例セクションを参照してください。

前提条件

Azure AI Studio で Cohere Command チャット モデルを使用するには、次の前提条件を満たす必要があります。

モデル デプロイ

サーバーレス API へのデプロイ

Cohere Command チャット モデルは、従量課金制でサーバーレス API エンドポイントにデプロイできます。 この種類のデプロイは、組織が必要とする企業レベルのセキュリティとコンプライアンスを維持しながら、サブスクリプションでホストせずに API としてモデルを使用する方法を提供します。

サーバーレス API エンドポイントへのデプロイでは、サブスクリプションからのクォータは必要ありません。 モデルがまだデプロイされていない場合は、Azure AI Studio、Azure Machine Learning SDK for Python、Azure CLI、または ARM テンプレートを使用して、モデルをサーバーレス API としてデプロイします。

インストールされている推論パッケージ

NuGet から Azure.AI.Inference パッケージを使用して、このモデルから予測を実行できます。 このパッケージをインストールするには、次の前提条件を満たす必要があります。

  • エンドポイント URL。 クライアント ライブラリを構築するには、エンドポイント URL を渡す必要があります。 エンドポイント URL の形式は https://your-host-name.your-azure-region.inference.ai.azure.com です。ここで、your-host-name は一意のモデル デプロイ ホスト名、your-azure-region はモデルがデプロイされている Azure リージョン (eastus2 など) です。
  • モデル デプロイと認証の設定に応じて、サービスに対する認証キーまたは Microsoft Entra ID 認証情報が必要です。 キーは 32 文字の文字列です。

これらの前提条件が満たされたら、次のコマンドを使用して Azure AI 推論ライブラリをインストールします。

dotnet add package Azure.AI.Inference --prerelease

Microsoft Entra ID (旧称 Azure Active Directory) を使用して認証することもできます。 Azure SDK で提供されている認証情報プロバイダーを使用するには、Azure.Identity パッケージをインストールします。

dotnet add package Azure.Identity

次の名前空間をインポートします。

using Azure;
using Azure.Identity;
using Azure.AI.Inference;

この例では次の名前空間も使用しますが、必要でない場合もあります。

using System.Text.Json;
using System.Text.Json.Serialization;
using System.Reflection;

チャット入力候補を使用する

このセクションでは、Azure AI モデル推論 API をチャットのチャット入力候補モデルで使用します。

ヒント

Azure AI モデル推論 API を使用すると、Cohere Command チャット モデルなど、同じコードと構造で Azure AI Studio にデプロイされたほとんどのモデルと対話できます。

モデルを実行するクライアントを作成する

まず、モデルを実行するクライアントを作成します。 次のコードでは、環境変数に格納されているエンドポイント URL とキーを使用しています。

ChatCompletionsClient client = new ChatCompletionsClient(
    new Uri(Environment.GetEnvironmentVariable("AZURE_INFERENCE_ENDPOINT")),
    new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_INFERENCE_CREDENTIAL"))
);

モデルの機能を取得する

/info ルートは、エンドポイントにデプロイされたモデルに関する情報を返します。 次のメソッドを呼び出してモデルの情報を返します。

Response<ModelInfo> modelInfo = client.GetModelInfo();

応答は次のとおりです。

Console.WriteLine($"Model name: {modelInfo.Value.ModelName}");
Console.WriteLine($"Model type: {modelInfo.Value.ModelType}");
Console.WriteLine($"Model provider name: {modelInfo.Value.ModelProviderName}");
Model name: Cohere-command-r-plus
Model type: chat-completions
Model provider name: Cohere

チャット入力候補要求を作成する

次の例に、モデルに対する基本的なチャット入力候補要求を作成する方法を示します。

ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
{
    Messages = {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("How many languages are in the world?")
    },
};

Response<ChatCompletions> response = client.Complete(requestOptions);

応答は次のとおりです。モデルの使用状況の統計情報が表示されます。

Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");
Console.WriteLine($"Model: {response.Value.Model}");
Console.WriteLine("Usage:");
Console.WriteLine($"\tPrompt tokens: {response.Value.Usage.PromptTokens}");
Console.WriteLine($"\tTotal tokens: {response.Value.Usage.TotalTokens}");
Console.WriteLine($"\tCompletion tokens: {response.Value.Usage.CompletionTokens}");
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: Cohere-command-r-plus
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

応答の usage セクションを調べて、プロンプトに使用されたトークンの数、生成されたトークンの合計数、入力候補に使用されたトークンの数を確認します。

コンテンツのストリーミング

既定では、入力候補 API は生成されたコンテンツ全体を 1 つの応答で返します。 長い入力候補を生成する場合、応答が得られるまでに数秒かかることがあります。

コンテンツをストリーミングして、コンテンツが生成されるにつれ返されるようにできます。 コンテンツをストリーミングすると、コンテンツが使用可能になったときに入力候補の処理を開始できます。 このモードは、データのみのサーバー送信イベントとして応答をストリーム バックするオブジェクトを返します。 メッセージ フィールドではなく、デルタ フィールドからチャンクを抽出します。

static async Task StreamMessageAsync(ChatCompletionsClient client)
{
    ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
    {
        Messages = {
            new ChatRequestSystemMessage("You are a helpful assistant."),
            new ChatRequestUserMessage("How many languages are in the world? Write an essay about it.")
        },
        MaxTokens=4096
    };

    StreamingResponse<StreamingChatCompletionsUpdate> streamResponse = await client.CompleteStreamingAsync(requestOptions);

    await PrintStream(streamResponse);
}

入力候補をストリーミングするには、モデルを呼び出すときに CompleteStreamingAsync メソッドを使用します。 この例では、呼び出しが非同期メソッドにラップされていることに注意してください。

出力を視覚化するには、コンソールにストリームを出力する非同期メソッドを定義します。

static async Task PrintStream(StreamingResponse<StreamingChatCompletionsUpdate> response)
{
    await foreach (StreamingChatCompletionsUpdate chatUpdate in response)
    {
        if (chatUpdate.Role.HasValue)
        {
            Console.Write($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
        }
        if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
        {
            Console.Write(chatUpdate.ContentUpdate);
        }
    }
}

ストリーミングでコンテンツがどのように生成されるかを視覚化できます。

StreamMessageAsync(client).GetAwaiter().GetResult();

推論クライアントでサポートされているその他のパラメーターを確認する

推論クライアントで指定できるその他のパラメーターを確認します。 サポートされているすべてのパラメーターとそれらのドキュメントの完全な一覧については、Azure AI モデル推論 API リファレンスを参照してください。

requestOptions = new ChatCompletionsOptions()
{
    Messages = {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("How many languages are in the world?")
    },
    PresencePenalty = 0.1f,
    FrequencyPenalty = 0.8f,
    MaxTokens = 2048,
    StopSequences = { "<|endoftext|>" },
    Temperature = 0,
    NucleusSamplingFactor = 1,
    ResponseFormat = new ChatCompletionsResponseFormatText()
};

response = client.Complete(requestOptions);
Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");

サポートされているパラメーターの一覧にないパラメーターを渡す場合は、追加のパラメーターを使用して、基になるモデルに渡すことができます。 「モデルに追加のパラメーターを渡す」を参照してください。

JSON 出力を作成する

Cohere Command チャット モデルでは JSON 出力を作成できます。 response_formatjson_object に設定すると JSON モードが有効になり、モデルが生成するメッセージが有効な JSON であることが保証されます。 システムまたはユーザー メッセージを使って、ユーザー自身が JSON を生成することをモデルに指示する必要もあります。 また、生成が max_tokens を超えたか、会話がコンテキストの最大長を超えたことを示す finish_reason="length" の場合、メッセージの内容が部分的に切り取られる可能性があります。

requestOptions = new ChatCompletionsOptions()
{
    Messages = {
        new ChatRequestSystemMessage(
            "You are a helpful assistant that always generate responses in JSON format, " +
            "using. the following format: { \"answer\": \"response\" }."
        ),
        new ChatRequestUserMessage(
            "How many languages are in the world?"
        )
    },
    ResponseFormat = new ChatCompletionsResponseFormatJSON()
};

response = client.Complete(requestOptions);
Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");

モデルに追加のパラメーターを渡す

Azure AI モデル推論 API を使用すると、モデルに追加のパラメーターを渡すことができます。 次のコード例に、モデルに追加のパラメーター logprobs を渡す方法を示します。

Azure AI モデル推論 API に追加のパラメーターを渡す前に、モデルでこれらの追加パラメーターがサポートされていることを確認してください。 基になるモデルに要求を行うと、ヘッダー extra-parameters が値 pass-through でモデルに渡されます。 この値は、追加のパラメーターをモデルに渡すようエンドポイントに指示します。 モデルで追加のパラメーターを使用しても、モデルで実際に処理できるとは限りません。 モデルのドキュメントを参照して、サポートされている追加パラメーターを確認してください。

requestOptions = new ChatCompletionsOptions()
{
    Messages = {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("How many languages are in the world?")
    },
    AdditionalProperties = { { "logprobs", BinaryData.FromString("true") } },
};

response = client.Complete(requestOptions, extraParams: ExtraParameters.PassThrough);
Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");

ツールの使用

Cohere Command チャット モデルではツールの使用がサポートされており、言語モデルから特定のタスクをオフロードし、より決定論的なシステムや別の言語モデルに依存する必要がある場合に、特別なリソースになります。 Azure AI Model Inference API では、次のようにツールを定義できます。

次のコード例では、2 つの異なる都市からのフライト情報を検索できるツール定義を作成します。

FunctionDefinition flightInfoFunction = new FunctionDefinition("getFlightInfo")
{
    Description = "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
    Parameters = BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            origin_city = new
            {
                Type = "string",
                Description = "The name of the city where the flight originates"
            },
            destination_city = new
            {
                Type = "string",
                Description = "The flight destination city"
            }
        }
    },
        new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
    )
};

ChatCompletionsFunctionToolDefinition getFlightTool = new ChatCompletionsFunctionToolDefinition(flightInfoFunction);

この例では、関数の出力では選択されたルートで利用可能なフライトがないため、ユーザーは電車に乗ることを検討する必要があります。

static string getFlightInfo(string loc_origin, string loc_destination)
{
    return JsonSerializer.Serialize(new
    {
        info = $"There are no flights available from {loc_origin} to {loc_destination}. You " +
        "should take a train, specially if it helps to reduce CO2 emissions."
    });
}

Note

Cohere-command-r-plus および Cohere-command-r では、ツールの応答が文字列として書式設定された有効な JSON コンテンツであることが必要です。 Tool 型のメッセージを構築する場合、応答が有効な JSON 文字列であることを確認してください。

この機能を使用して、モデルにフライトの予約を求めます。

var chatHistory = new List<ChatRequestMessage>(){
        new ChatRequestSystemMessage(
            "You are a helpful assistant that help users to find information about traveling, " +
            "how to get to places and the different transportations options. You care about the" +
            "environment and you always have that in mind when answering inqueries."
        ),
        new ChatRequestUserMessage("When is the next flight from Miami to Seattle?")
    };

requestOptions = new ChatCompletionsOptions(chatHistory);
requestOptions.Tools.Add(getFlightTool);
requestOptions.ToolChoice = ChatCompletionsToolChoice.Auto;

response = client.Complete(requestOptions);

ツールを呼び出す必要があるかどうかを調べるために、応答を検査できます。 ツールを呼び出す必要があるか判断するために、終了した理由を検査します。 複数のツールの種類を指定できることを忘れないでください。 この例は、種類 function のツールを示しています。

var responseMenssage = response.Value.Choices[0].Message;
var toolsCall = responseMenssage.ToolCalls;

Console.WriteLine($"Finish reason: {response.Value.Choices[0].FinishReason}");
Console.WriteLine($"Tool call: {toolsCall[0].Id}");

続行するには、このメッセージをチャット履歴に追加します。

requestOptions.Messages.Add(new ChatRequestAssistantMessage(response.Value.Choices[0].Message));

ここで、ツール呼び出しを処理するための適切な関数を呼び出します。 次のコード スニペットは、応答に示されたすべてのツール呼び出しを反復処理し、適切なパラメーターを指定して対応する関数を呼び出します。 応答はチャット履歴にも追加されます。

foreach (ChatCompletionsToolCall tool in toolsCall)
{
    if (tool is ChatCompletionsFunctionToolCall functionTool)
    {
        // Get the tool details:
        string callId = functionTool.Id;
        string toolName = functionTool.Name;
        string toolArgumentsString = functionTool.Arguments;
        Dictionary<string, object> toolArguments = JsonSerializer.Deserialize<Dictionary<string, object>>(toolArgumentsString);

        // Here you have to call the function defined. In this particular example we use 
        // reflection to find the method we definied before in an static class called 
        // `ChatCompletionsExamples`. Using reflection allows us to call a function 
        // by string name. Notice that this is just done for demonstration purposes as a 
        // simple way to get the function callable from its string name. Then we can call 
        // it with the corresponding arguments.

        var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
        string toolResponse = (string)typeof(ChatCompletionsExamples).GetMethod(toolName, flags).Invoke(null, toolArguments.Values.Cast<object>().ToArray());

        Console.WriteLine("->", toolResponse);
        requestOptions.Messages.Add(new ChatRequestToolMessage(toolResponse, callId));
    }
    else
        throw new Exception("Unsupported tool type");
}

モデルからの応答を表示します。

response = client.Complete(requestOptions);

コンテンツの安全性を適用する

Azure AI モデル推論 API は、Azure AI Content Safety をサポートしています。 Azure AI Content Safety をオンにしてデプロイを使用すると、入力と出力は、有害なコンテンツの出力を検出して防ぐことを目的とした一連の分類モデルを通過します。 コンテンツ フィルタリング システムは、入力プロンプトと (出力される) 入力候補の両方で、有害な可能性があるコンテンツ特有のカテゴリを検出し、アクションを実行します。

次の例に、モデルが入力プロンプトで有害なコンテンツを検出し、コンテンツの安全性が有効になっている場合にイベントを処理する方法を示しています。

try
{
    requestOptions = new ChatCompletionsOptions()
    {
        Messages = {
            new ChatRequestSystemMessage("You are an AI assistant that helps people find information."),
            new ChatRequestUserMessage(
                "Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."
            ),
        },
    };

    response = client.Complete(requestOptions);
    Console.WriteLine(response.Value.Choices[0].Message.Content);
}
catch (RequestFailedException ex)
{
    if (ex.ErrorCode == "content_filter")
    {
        Console.WriteLine($"Your query has trigger Azure Content Safety: {ex.Message}");
    }
    else
    {
        throw;
    }
}

ヒント

Azure AI Content Safety 設定を構成および制御する方法の詳細については、Azure AI Content Safety のドキュメントを参照してください。

Cohere Command チャット モデル

Cohere Command チャット モデルには、次のようなモデルが含まれます。

Command R+ は、推論、要約、質問応答など、さまざまなユース ケース向けに最適化された、生成の大規模言語モデルです。

  • モデル アーキテクチャ: Command R と Command R+ はどちらも、最適化されたトランスフォーマー アーキテクチャを使用する自己回帰言語モデルです。 事前トレーニング後、これらのモデルでは、教師あり微調整 (SFT) と優先トレーニングを使用して、モデルの動作を人間の好みに合わせて調整し、有用性と安全性を確保します。
  • 対象言語: これらのモデルは、英語、フランス語、スペイン語、イタリア語、ドイツ語、ポルトガル語 (ブラジル)、日本語、韓国語、簡体中国語、アラビア語の言語で適切に動作するように最適化されています。
  • 事前トレーニング データには、次の 13 言語も含まれています: ロシア語、ポーランド語、トルコ語、ベトナム語、オランダ語、チェコ語、インドネシア語、ウクライナ語、ルーマニア語、ギリシャ語、ヒンディー語、ヘブライ語、ペルシャ語。
  • コンテキストの長さ: Command R と Command R+ では、コンテキストの長さ 128 K をサポートしています。

複雑な取得拡張生成 (RAG) 機能や複数ステップ ツールの使用 (エージェント) が必要なワークフローには、Command R+ の使用をお勧めします。

以下のモデルが使用可能です:

ヒント

さらに、Cohere は、モデルの特定の機能で使用するためにカスタマイズされた API の使用をサポートしています。 モデル プロバイダー固有の API を使用するには、Cohere ドキュメントを確認するか、コード例への推論の例セクションを参照してください。

前提条件

Azure AI Studio で Cohere Command チャット モデルを使用するには、次の前提条件を満たす必要があります。

モデル デプロイ

サーバーレス API へのデプロイ

Cohere Command チャット モデルは、従量課金制でサーバーレス API エンドポイントにデプロイできます。 この種類のデプロイは、組織が必要とする企業レベルのセキュリティとコンプライアンスを維持しながら、サブスクリプションでホストせずに API としてモデルを使用する方法を提供します。

サーバーレス API エンドポイントへのデプロイでは、サブスクリプションからのクォータは必要ありません。 モデルがまだデプロイされていない場合は、Azure AI Studio、Azure Machine Learning SDK for Python、Azure CLI、または ARM テンプレートを使用して、モデルをサーバーレス API としてデプロイします。

REST クライアント

Azure AI モデル推論 API でデプロイされたモデルは、任意の REST クライアントを使用して実行できます。 REST クライアントを使用するには、次の前提条件が満たされている必要があります。

  • リクエストを作成するには、エンドポイント URL を渡す必要があります。 エンドポイント URL の形式は https://your-host-name.your-azure-region.inference.ai.azure.com です。ここで、your-host-name`` is your unique model deployment host name and your-azure-region`` はモデルがデプロイされている Azure リージョン (eastus2 など) です。
  • モデル デプロイと認証の設定に応じて、サービスに対する認証キーまたは Microsoft Entra ID 認証情報が必要です。 キーは 32 文字の文字列です。

チャット入力候補を使用する

このセクションでは、Azure AI モデル推論 API をチャットのチャット入力候補モデルで使用します。

ヒント

Azure AI モデル推論 API を使用すると、Cohere Command チャット モデルなど、同じコードと構造で Azure AI Studio にデプロイされたほとんどのモデルと対話できます。

モデルを実行するクライアントを作成する

まず、モデルを実行するクライアントを作成します。 次のコードでは、環境変数に格納されているエンドポイント URL とキーを使用しています。

モデルの機能を取得する

/info ルートは、エンドポイントにデプロイされたモデルに関する情報を返します。 次のメソッドを呼び出してモデルの情報を返します。

GET /info HTTP/1.1
Host: <ENDPOINT_URI>
Authorization: Bearer <TOKEN>
Content-Type: application/json

応答は次のとおりです。

{
    "model_name": "Cohere-command-r-plus",
    "model_type": "chat-completions",
    "model_provider_name": "Cohere"
}

チャット入力候補要求を作成する

次の例に、モデルに対する基本的なチャット入力候補要求を作成する方法を示します。

{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ]
}

応答は次のとおりです。モデルの使用状況の統計情報が表示されます。

{
    "id": "0a1234b5de6789f01gh2i345j6789klm",
    "object": "chat.completion",
    "created": 1718726686,
    "model": "Cohere-command-r-plus",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.",
                "tool_calls": null
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 19,
        "total_tokens": 91,
        "completion_tokens": 72
    }
}

応答の usage セクションを調べて、プロンプトに使用されたトークンの数、生成されたトークンの合計数、入力候補に使用されたトークンの数を確認します。

コンテンツのストリーミング

既定では、入力候補 API は生成されたコンテンツ全体を 1 つの応答で返します。 長い入力候補を生成する場合、応答が得られるまでに数秒かかることがあります。

コンテンツをストリーミングして、コンテンツが生成されるにつれ返されるようにできます。 コンテンツをストリーミングすると、コンテンツが使用可能になったときに入力候補の処理を開始できます。 このモードは、データのみのサーバー送信イベントとして応答をストリーム バックするオブジェクトを返します。 メッセージ フィールドではなく、デルタ フィールドからチャンクを抽出します。

{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ],
    "stream": true,
    "temperature": 0,
    "top_p": 1,
    "max_tokens": 2048
}

ストリーミングでコンテンツがどのように生成されるかを視覚化できます。

{
    "id": "23b54589eba14564ad8a2e6978775a39",
    "object": "chat.completion.chunk",
    "created": 1718726371,
    "model": "Cohere-command-r-plus",
    "choices": [
        {
            "index": 0,
            "delta": {
                "role": "assistant",
                "content": ""
            },
            "finish_reason": null,
            "logprobs": null
        }
    ]
}

ストリーム内の最後のメッセージには、生成プロセスが停止した理由を示す finish_reason が設定されています。

{
    "id": "23b54589eba14564ad8a2e6978775a39",
    "object": "chat.completion.chunk",
    "created": 1718726371,
    "model": "Cohere-command-r-plus",
    "choices": [
        {
            "index": 0,
            "delta": {
                "content": ""
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 19,
        "total_tokens": 91,
        "completion_tokens": 72
    }
}

推論クライアントでサポートされているその他のパラメーターを確認する

推論クライアントで指定できるその他のパラメーターを確認します。 サポートされているすべてのパラメーターとそれらのドキュメントの完全な一覧については、Azure AI モデル推論 API リファレンスを参照してください。

{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ],
    "presence_penalty": 0.1,
    "frequency_penalty": 0.8,
    "max_tokens": 2048,
    "stop": ["<|endoftext|>"],
    "temperature" :0,
    "top_p": 1,
    "response_format": { "type": "text" }
}
{
    "id": "0a1234b5de6789f01gh2i345j6789klm",
    "object": "chat.completion",
    "created": 1718726686,
    "model": "Cohere-command-r-plus",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.",
                "tool_calls": null
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 19,
        "total_tokens": 91,
        "completion_tokens": 72
    }
}

サポートされているパラメーターの一覧にないパラメーターを渡す場合は、追加のパラメーターを使用して、基になるモデルに渡すことができます。 「モデルに追加のパラメーターを渡す」を参照してください。

JSON 出力を作成する

Cohere Command チャット モデルでは JSON 出力を作成できます。 response_formatjson_object に設定すると JSON モードが有効になり、モデルが生成するメッセージが有効な JSON であることが保証されます。 システムまたはユーザー メッセージを使って、ユーザー自身が JSON を生成することをモデルに指示する必要もあります。 また、生成が max_tokens を超えたか、会話がコンテキストの最大長を超えたことを示す finish_reason="length" の場合、メッセージの内容が部分的に切り取られる可能性があります。

{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant that always generate responses in JSON format, using the following format: { \"answer\": \"response\" }"
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ],
    "response_format": { "type": "json_object" }
}
{
    "id": "0a1234b5de6789f01gh2i345j6789klm",
    "object": "chat.completion",
    "created": 1718727522,
    "model": "Cohere-command-r-plus",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "{\"answer\": \"There are approximately 7,117 living languages in the world today, according to the latest estimates. However, this number can vary as some languages become extinct and others are newly discovered or classified.\"}",
                "tool_calls": null
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 39,
        "total_tokens": 87,
        "completion_tokens": 48
    }
}

モデルに追加のパラメーターを渡す

Azure AI モデル推論 API を使用すると、モデルに追加のパラメーターを渡すことができます。 次のコード例に、モデルに追加のパラメーター logprobs を渡す方法を示します。

Azure AI モデル推論 API に追加のパラメーターを渡す前に、モデルでこれらの追加パラメーターがサポートされていることを確認してください。 基になるモデルに要求を行うと、ヘッダー extra-parameters が値 pass-through でモデルに渡されます。 この値は、追加のパラメーターをモデルに渡すようエンドポイントに指示します。 モデルで追加のパラメーターを使用しても、モデルで実際に処理できるとは限りません。 モデルのドキュメントを参照して、サポートされている追加パラメーターを確認してください。

POST /chat/completions HTTP/1.1
Host: <ENDPOINT_URI>
Authorization: Bearer <TOKEN>
Content-Type: application/json
extra-parameters: pass-through
{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ],
    "logprobs": true
}

ツールの使用

Cohere Command チャット モデルではツールの使用がサポートされており、言語モデルから特定のタスクをオフロードし、より決定論的なシステムや別の言語モデルに依存する必要がある場合に、特別なリソースになります。 Azure AI Model Inference API では、次のようにツールを定義できます。

次のコード例では、2 つの異なる都市からのフライト情報を検索できるツール定義を作成します。

{
    "type": "function",
    "function": {
        "name": "get_flight_info",
        "description": "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
        "parameters": {
            "type": "object",
            "properties": {
                "origin_city": {
                    "type": "string",
                    "description": "The name of the city where the flight originates"
                },
                "destination_city": {
                    "type": "string",
                    "description": "The flight destination city"
                }
            },
            "required": [
                "origin_city",
                "destination_city"
            ]
        }
    }
}

この例では、関数の出力では選択されたルートで利用可能なフライトがないため、ユーザーは電車に乗ることを検討する必要があります。

Note

Cohere-command-r-plus および Cohere-command-r では、ツールの応答が文字列として書式設定された有効な JSON コンテンツであることが必要です。 Tool 型のメッセージを構築する場合、応答が有効な JSON 文字列であることを確認してください。

この機能を使用して、モデルにフライトの予約を求めます。

{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant that help users to find information about traveling, how to get to places and the different transportations options. You care about the environment and you always have that in mind when answering inqueries"
        },
        {
            "role": "user",
            "content": "When is the next flight from Miami to Seattle?"
        }
    ],
    "tool_choice": "auto",
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_flight_info",
                "description": "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "origin_city": {
                            "type": "string",
                            "description": "The name of the city where the flight originates"
                        },
                        "destination_city": {
                            "type": "string",
                            "description": "The flight destination city"
                        }
                    },
                    "required": [
                        "origin_city",
                        "destination_city"
                    ]
                }
            }
        }
    ]
}

ツールを呼び出す必要があるかどうかを調べるために、応答を検査できます。 ツールを呼び出す必要があるか判断するために、終了した理由を検査します。 複数のツールの種類を指定できることを忘れないでください。 この例は、種類 function のツールを示しています。

{
    "id": "0a1234b5de6789f01gh2i345j6789klm",
    "object": "chat.completion",
    "created": 1718726007,
    "model": "Cohere-command-r-plus",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "",
                "tool_calls": [
                    {
                        "id": "abc0dF1gh",
                        "type": "function",
                        "function": {
                            "name": "get_flight_info",
                            "arguments": "{\"origin_city\": \"Miami\", \"destination_city\": \"Seattle\"}",
                            "call_id": null
                        }
                    }
                ]
            },
            "finish_reason": "tool_calls",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 190,
        "total_tokens": 226,
        "completion_tokens": 36
    }
}

続行するには、このメッセージをチャット履歴に追加します。

ここで、ツール呼び出しを処理するための適切な関数を呼び出します。 次のコード スニペットは、応答に示されたすべてのツール呼び出しを反復処理し、適切なパラメーターを指定して対応する関数を呼び出します。 応答はチャット履歴にも追加されます。

モデルからの応答を表示します。

{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant that help users to find information about traveling, how to get to places and the different transportations options. You care about the environment and you always have that in mind when answering inqueries"
        },
        {
            "role": "user",
            "content": "When is the next flight from Miami to Seattle?"
        },
        {
            "role": "assistant",
            "content": "",
            "tool_calls": [
                {
                    "id": "abc0DeFgH",
                    "type": "function",
                    "function": {
                        "name": "get_flight_info",
                        "arguments": "{\"origin_city\": \"Miami\", \"destination_city\": \"Seattle\"}",
                        "call_id": null
                    }
                }
            ]
        },
        {
            "role": "tool",
            "content": "{ \"info\": \"There are no flights available from Miami to Seattle. You should take a train, specially if it helps to reduce CO2 emissions.\" }",
            "tool_call_id": "abc0DeFgH" 
        }
    ],
    "tool_choice": "auto",
    "tools": [
        {
            "type": "function",
            "function": {
            "name": "get_flight_info",
            "description": "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
            "parameters":{
                "type": "object",
                "properties": {
                    "origin_city": {
                        "type": "string",
                        "description": "The name of the city where the flight originates"
                    },
                    "destination_city": {
                        "type": "string",
                        "description": "The flight destination city"
                    }
                },
                "required": ["origin_city", "destination_city"]
            }
            }
        }
    ]
}

コンテンツの安全性を適用する

Azure AI モデル推論 API は、Azure AI Content Safety をサポートしています。 Azure AI Content Safety をオンにしてデプロイを使用すると、入力と出力は、有害なコンテンツの出力を検出して防ぐことを目的とした一連の分類モデルを通過します。 コンテンツ フィルタリング システムは、入力プロンプトと (出力される) 入力候補の両方で、有害な可能性があるコンテンツ特有のカテゴリを検出し、アクションを実行します。

次の例に、モデルが入力プロンプトで有害なコンテンツを検出し、コンテンツの安全性が有効になっている場合にイベントを処理する方法を示しています。

{
    "messages": [
        {
            "role": "system",
            "content": "You are an AI assistant that helps people find information."
        },
                {
            "role": "user",
            "content": "Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."
        }
    ]
}
{
    "error": {
        "message": "The response was filtered due to the prompt triggering Microsoft's content management policy. Please modify your prompt and retry.",
        "type": null,
        "param": "prompt",
        "code": "content_filter",
        "status": 400
    }
}

ヒント

Azure AI Content Safety 設定を構成および制御する方法の詳細については、Azure AI Content Safety のドキュメントを参照してください。

推論のその他の例

Cohere の使用方法のその他の例については、次の例とチュートリアルを参照してください。

説明 Language サンプル
Web 要求 Bash Command-R - Command-R+
JavaScript 用 Azure AI 推論パッケージ JavaScript リンク
Python 用 Azure AI 推論パッケージ Python リンク
OpenAI SDK (試験段階) Python リンク
LangChain Python リンク
Cohere SDK Python リンク
LiteLLM SDK Python リンク

取得拡張生成 (RAG) とツールの使用サンプル

説明 パッケージ サンプル
Cohere 埋め込みを使用してローカルの Facebook AI 類似性検索 (FAISS) ベクター インデックスを作成する - Langchain langchainlangchain_cohere cohere_faiss_langchain_embed.ipynb
Cohere コマンド R/R+ を使用して、ローカルの FAISS ベクター インデックスのデータから質問に回答する - Langchain langchainlangchain_cohere command_faiss_langchain.ipynb
Cohere コマンド R/R+ を使用して、AI 検索ベクター インデックスのデータから質問に回答する - Langchain langchainlangchain_cohere cohere-aisearch-langchain-rag.ipynb
Cohere コマンド R/R+ を使用して、AI 検索ベクター インデックスのデータから質問に回答する - Cohere SDK cohereazure_search_documents cohere-aisearch-rag.ipynb
LangChain を使用したコマンド R+ ツールおよび関数呼び出し coherelangchainlangchain_cohere command_tools-langchain.ipynb

サーバーレス API エンドポイントとしてデプロイされる Cohere ファミリのモデルのコストとクォータに関する考慮事項

クォータはデプロイごとに管理されます。 各デプロイのレート制限は、1 分あたり 200,000 トークン、1 分あたり 1,000 個の API 要求です。 ただし、現在、プロジェクトのモデルごとに 1 つのデプロイに制限しています。 現在のレート制限がシナリオに十分でない場合は、Microsoft Azure サポートにお問い合わせください。

サーバーレス API としてデプロイされた Cohere モデルは、Azure Marketplace を通じて Cohere によって提供され、使用するために Azure AI Studio と統合されます。 モデルをデプロイするときに、Azure Marketplace の価格を確認できます。

プロジェクトが Azure Marketplace から特定のオファーにサブスクライブするたびに、その消費に関連するコストを追跡するための新しいリソースが作成されます。 推論に関連するコストを追跡するために同じリソースが使用されますが、各シナリオを個別に追跡するために複数の測定値を使用できます。

コストを追跡する方法の詳細については、「Azure Marketplace を通じて提供されるモデルのコストを監視する」を参照してください。