如何使用 Cohere Command 聊天模型

重要

本文所述的部分功能可能僅適用於預覽版。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款

在此文章中,您將了解 Cohere Command 聊天模型,以及如何使用這些模型。 Cohere 系列的模型包含已針對不同使用案例 (包括聊天完成、內嵌及重新排名) 最佳化的各種模型。 Cohere 模型已針對各種使用案例 (包括推理、摘要及問題解答) 進行最佳化。

Cohere Command 聊天模型

Cohere Command 聊天模型包含下列模型:

Command R+ 08-2024 是一種生成式大型語言模型,已針對各種使用案例 (包括推理、摘要及問題解答) 進行最佳化。

  • 模型結構:Command R+ 08-2024 是使用最佳化轉換器結構的自動迴歸語言模型。 預先訓練後,模型便會使用監督式微調 (SFT) 和偏好訓練來使模型行為與人類偏好保持一致,以實現有用性和安全性。
  • 涵蓋的語言:模型已最佳化,可在下列語言中順利執行: 英文、法文、西班牙文、義大利文、德文、巴西葡萄牙文、日文、韓文、簡體中文和阿拉伯文。
  • 預先訓練的資料還包括下列 13 種語言:俄文、波蘭文、土耳其文、越南文、荷蘭文、捷克文、印尼文、烏克蘭文、羅馬尼亞文、希臘文、印度文、希伯來文和波斯文。
  • 內容長度:Command R+ 08-2024 支援 128 K 的內容長度。
  • 輸入:僅文字。
  • 輸出:僅文字。

我們建議針對依賴複雜擷取擴增生成 (RAG) 功能、多步驟工具使用 (代理程式) 和結構化輸出的那些工作流程使用 Command R+ 08-2024。

有下列模型可用:

提示

此外,Cohere 支援使用量身打造的 API,以搭配模型的特定功能使用。 若要使用模型提供者特定的 API,請參閱 Cohere 文件 (英文),或參閱推斷範例小節中的程式碼範例。

必要條件

若要搭配 Azure AI Studio 使用 Cohere Command 聊天模型,您需要下列必要條件:

模型部署

部署至無伺服器 API

您可以透過隨用隨付計費,將 Cohere Command 聊天模型部署至無伺服器 API 端點。 這種部署可讓您以 API 的形式取用模型,而不必在您的訂用帳戶上裝載模型,同時讓組織保持所需的企業安全性和合規性。

部署至無伺服器 API 端點不需要您訂用帳戶的配額。 如果您的模型尚未部署,請使用 Azure AI Studio、適用於 Python 的 Azure Machine Learning SDK、Azure CLI 或 ARM 範本來將模型部署為無伺服器 API (英文)。

已安裝推斷套件

您可以透過使用 azure-ai-inference 套件搭配 Python,從此模型取用預測。 若要安裝此套件,您需要下列先決條件:

  • 已安裝 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 (英文) 可讓您與在 Azure AI Studio 中部署、具有相同程式碼和結構相同的大部分模型交談,包括 Cohere Command 聊天模型。

建立用戶端以取用模型

首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 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-08-2024
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-08-2024
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

檢查回應中的 usage 區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。

串流內容

根據預設,完成 API 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。

您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。

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={ "type": ChatCompletionsResponseFormatText() },
)

如果您想要傳遞不在所支援參數清單中的參數,您可以使用「額外的參數」,將其傳遞至基礎模型。 請參閱將額外的參數傳遞至模型

建立 JSON 輸出

Cohere Command 聊天模型可以建立 JSON 輸出。 將 response_format 設定為 json_object 以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length",則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens 或交談超過了最大內容長度。

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={ "type": 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 模型推斷 API 可讓您以下列方式定義工具。

下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。

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."
    }

注意

Cohere-command-r-plus-08-2024、Cohere-command-r-08-2024、Cohere-command-r-plus 和 Cohere-command-r 需要工具的回應是格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 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 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。

下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。

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 內容安全設定,請參閱 Azure AI 內容安全文件

Cohere Command 聊天模型

Cohere Command 聊天模型包含下列模型:

Command R+ 08-2024 是一種生成式大型語言模型,已針對各種使用案例 (包括推理、摘要及問題解答) 進行最佳化。

  • 模型結構:Command R+ 08-2024 是使用最佳化轉換器結構的自動迴歸語言模型。 預先訓練後,模型便會使用監督式微調 (SFT) 和偏好訓練來使模型行為與人類偏好保持一致,以實現有用性和安全性。
  • 涵蓋的語言:模型已最佳化,可在下列語言中順利執行: 英文、法文、西班牙文、義大利文、德文、巴西葡萄牙文、日文、韓文、簡體中文和阿拉伯文。
  • 預先訓練的資料還包括下列 13 種語言:俄文、波蘭文、土耳其文、越南文、荷蘭文、捷克文、印尼文、烏克蘭文、羅馬尼亞文、希臘文、印度文、希伯來文和波斯文。
  • 內容長度:Command R+ 08-2024 支援 128 K 的內容長度。
  • 輸入:僅文字。
  • 輸出:僅文字。

我們建議針對依賴複雜擷取擴增生成 (RAG) 功能、多步驟工具使用 (代理程式) 和結構化輸出的那些工作流程使用 Command R+ 08-2024。

有下列模型可用:

提示

此外,Cohere 支援使用量身打造的 API,以搭配模型的特定功能使用。 若要使用模型提供者特定的 API,請參閱 Cohere 文件 (英文),或參閱推斷範例小節中的程式碼範例。

必要條件

若要搭配 Azure AI Studio 使用 Cohere Command 聊天模型,您需要下列必要條件:

模型部署

部署至無伺服器 API

您可以透過隨用隨付計費,將 Cohere Command 聊天模型部署至無伺服器 API 端點。 這種部署可讓您以 API 的形式取用模型,而不必在您的訂用帳戶上裝載模型,同時讓組織保持所需的企業安全性和合規性。

部署至無伺服器 API 端點不需要您訂用帳戶的配額。 如果您的模型尚未部署,請使用 Azure AI Studio、適用於 Python 的 Azure Machine Learning SDK、Azure CLI 或 ARM 範本來將模型部署為無伺服器 API (英文)。

已安裝推斷套件

您可以使用 npm@azure-rest/ai-inference 套件來取用此模型的預測。 若要安裝此套件,您需要下列先決條件:

  • 具有 npmNode.js LTS 版本。
  • 端點 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 (英文) 可讓您與在 Azure AI Studio 中部署、具有相同程式碼和結構相同的大部分模型交談,包括 Cohere Command 聊天模型。

建立用戶端以取用模型

首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 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-08-2024
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-08-2024
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

檢查回應中的 usage 區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。

串流內容

根據預設,完成 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,
    }
}).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_format 設定為 json_object 以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length",則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens 或交談超過了最大內容長度。

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 模型推斷 API 可讓您以下列方式定義工具。

下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。

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."
    }
}

注意

Cohere-command-r-plus-08-2024、Cohere-command-r-08-2024、Cohere-command-r-plus 和 Cohere-command-r 需要工具的回應是格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 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 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。

下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。

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 內容安全設定,請參閱 Azure AI 內容安全文件

Cohere Command 聊天模型

Cohere Command 聊天模型包含下列模型:

Command R+ 08-2024 是一種生成式大型語言模型,已針對各種使用案例 (包括推理、摘要及問題解答) 進行最佳化。

  • 模型結構:Command R+ 08-2024 是使用最佳化轉換器結構的自動迴歸語言模型。 預先訓練後,模型便會使用監督式微調 (SFT) 和偏好訓練來使模型行為與人類偏好保持一致,以實現有用性和安全性。
  • 涵蓋的語言:模型已最佳化,可在下列語言中順利執行: 英文、法文、西班牙文、義大利文、德文、巴西葡萄牙文、日文、韓文、簡體中文和阿拉伯文。
  • 預先訓練的資料還包括下列 13 種語言:俄文、波蘭文、土耳其文、越南文、荷蘭文、捷克文、印尼文、烏克蘭文、羅馬尼亞文、希臘文、印度文、希伯來文和波斯文。
  • 內容長度:Command R+ 08-2024 支援 128 K 的內容長度。
  • 輸入:僅文字。
  • 輸出:僅文字。

我們建議針對依賴複雜擷取擴增生成 (RAG) 功能、多步驟工具使用 (代理程式) 和結構化輸出的那些工作流程使用 Command R+ 08-2024。

有下列模型可用:

提示

此外,Cohere 支援使用量身打造的 API,以搭配模型的特定功能使用。 若要使用模型提供者特定的 API,請參閱 Cohere 文件 (英文),或參閱推斷範例小節中的程式碼範例。

必要條件

若要搭配 Azure AI Studio 使用 Cohere Command 聊天模型,您需要下列必要條件:

模型部署

部署至無伺服器 API

您可以透過隨用隨付計費,將 Cohere Command 聊天模型部署至無伺服器 API 端點。 這種部署可讓您以 API 的形式取用模型,而不必在您的訂用帳戶上裝載模型,同時讓組織保持所需的企業安全性和合規性。

部署至無伺服器 API 端點不需要您訂用帳戶的配額。 如果您的模型尚未部署,請使用 Azure AI Studio、適用於 Python 的 Azure Machine Learning SDK、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 (英文) 可讓您與在 Azure AI Studio 中部署、具有相同程式碼和結構相同的大部分模型交談,包括 Cohere Command 聊天模型。

建立用戶端以取用模型

首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 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-08-2024
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-08-2024
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

檢查回應中的 usage 區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。

串流內容

根據預設,完成 API 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。

您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。

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_format 設定為 json_object 以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length",則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens 或交談超過了最大內容長度。

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 模型推斷 API 可讓您以下列方式定義工具。

下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。

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."
    });
}

注意

Cohere-command-r-plus-08-2024、Cohere-command-r-08-2024、Cohere-command-r-plus 和 Cohere-command-r 需要工具的回應是格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 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 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。

下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。

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 內容安全設定,請參閱 Azure AI 內容安全文件

Cohere Command 聊天模型

Cohere Command 聊天模型包含下列模型:

Command R+ 08-2024 是一種生成式大型語言模型,已針對各種使用案例 (包括推理、摘要及問題解答) 進行最佳化。

  • 模型結構:Command R+ 08-2024 是使用最佳化轉換器結構的自動迴歸語言模型。 預先訓練後,模型便會使用監督式微調 (SFT) 和偏好訓練來使模型行為與人類偏好保持一致,以實現有用性和安全性。
  • 涵蓋的語言:模型已最佳化,可在下列語言中順利執行: 英文、法文、西班牙文、義大利文、德文、巴西葡萄牙文、日文、韓文、簡體中文和阿拉伯文。
  • 預先訓練的資料還包括下列 13 種語言:俄文、波蘭文、土耳其文、越南文、荷蘭文、捷克文、印尼文、烏克蘭文、羅馬尼亞文、希臘文、印度文、希伯來文和波斯文。
  • 內容長度:Command R+ 08-2024 支援 128 K 的內容長度。
  • 輸入:僅文字。
  • 輸出:僅文字。

我們建議針對依賴複雜擷取擴增生成 (RAG) 功能、多步驟工具使用 (代理程式) 和結構化輸出的那些工作流程使用 Command R+ 08-2024。

有下列模型可用:

提示

此外,Cohere 支援使用量身打造的 API,以搭配模型的特定功能使用。 若要使用模型提供者特定的 API,請參閱 Cohere 文件 (英文),或參閱推斷範例小節中的程式碼範例。

必要條件

若要搭配 Azure AI Studio 使用 Cohere Command 聊天模型,您需要下列必要條件:

模型部署

部署至無伺服器 API

您可以透過隨用隨付計費,將 Cohere Command 聊天模型部署至無伺服器 API 端點。 這種部署可讓您以 API 的形式取用模型,而不必在您的訂用帳戶上裝載模型,同時讓組織保持所需的企業安全性和合規性。

部署至無伺服器 API 端點不需要您訂用帳戶的配額。 如果您的模型尚未部署,請使用 Azure AI Studio、適用於 Python 的 Azure Machine Learning SDK、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 (英文) 可讓您與在 Azure AI Studio 中部署、具有相同程式碼和結構相同的大部分模型交談,包括 Cohere Command 聊天模型。

建立用戶端以取用模型

首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 URL 和金鑰。

取得模型的功能

/info 路由會傳回部署至端點之模型的相關資訊。 透過呼叫下列方法,以傳回模型的資訊:

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

回應如下:

{
    "model_name": "Cohere-command-r-plus-08-2024",
    "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-08-2024",
    "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 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。

您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。

{
    "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-08-2024",
    "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-08-2024",
    "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-08-2024",
    "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_format 設定為 json_object 以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length",則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens 或交談超過了最大內容長度。

{
    "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-08-2024",
    "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 模型推斷 API 可讓您以下列方式定義工具。

下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。

{
    "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"
            ]
        }
    }
}

在此範例中,函式的輸出是所選路線沒有適合的航班,但使用者應考慮進行訓練。

注意

Cohere-command-r-plus-08-2024、Cohere-command-r-08-2024、Cohere-command-r-plus 和 Cohere-command-r 需要工具的回應是格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 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-08-2024",
    "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 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。

下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。

{
    "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 內容安全設定,請參閱 Azure AI 內容安全文件

更多推斷範例

如需如何使用 Cohere 模型的更多範例,請參閱下列範例和教學課程:

描述 語言 範例
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) 和工具使用範例

描述 Packages 範例
使用 Cohere 內嵌建立本機 Facebook AI 相似性搜尋 (FAISS) 向量索引 - Langchain langchain, langchain_cohere cohere_faiss_langchain_embed.ipynb (英文)
使用 Cohere Command R/R+ 回答本機 FAISS 向量索引的資料問題 - Langchain langchain, langchain_cohere command_faiss_langchain.ipynb (英文)
使用 Cohere Command R/R+ 回答 AI 搜尋向量索引的資料問題 - Langchain langchain, langchain_cohere cohere-aisearch-langchain-rag.ipynb (英文)
使用 Cohere Command R/R+ 回答 AI 搜尋向量索引的資料問題 - Cohere SDK cohere, azure_search_documents cohere-aisearch-rag.ipynb (英文)
使用 LangChain 呼叫 Command R+ 工具/函式 coherelangchainlangchain_cohere command_tools-langchain.ipynb (英文)

部署為無伺服器 API 端點的 Cohere 模型成本和配額考量

配額會根據每個部署管理。 每個部署的速率限制為每分鐘 200,000 個權杖,每分鐘 1,000 個 API 要求。 不過,我們目前限制每個專案的每個模型為一個部署。 如果目前的速率限制無法滿足您的情節,請連絡 Microsoft Azure 支援。

部署為無伺服器 API 的 Cohere 模型是由 Cohere 透過 Azure Marketplace 提供,並與 Azure AI Studio 整合以供使用。 您可以在部署模型時找到 Azure Marketplace 價格。

每次專案訂閱來自 Azure Marketplace 的指定供應項目時,都會建立新的資源,以便追蹤與其使用量相關聯的成本。 使用相同的資源來追蹤與推斷相關聯的成本;不過,可以使用多個計量獨立追蹤每個案例。

如需如何追蹤成本的詳細資訊,請參閱監視透過 Azure Marketplace 提供的模型成本 (部分機器翻譯)。