Table of Contents [expand]
この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
最終更新日 2025年01月24日(金)
Heroku Managed Inference and Agent アドオンは現在パイロット段階です。パイロットの一環として提供される製品は本番環境での使用を目的としたものではなく、ベータサービスとみなされています。また、https://www.salesforce.com/company/legal/agreements.jsp のベータサービス条件が適用されます。
Cohere Embed Multilingual (cohere-embed-multilingual) モデルは、提供されたテキスト入力に対するベクトル埋め込み (数値のリスト) を生成します。これらの埋め込みは、検索、分類、クラスタリングなどのさまざまなアプリケーションで使用できます。このガイドでは、Python を使用してv1-embeddings API にアクセスする方法について説明します。
前提条件
リクエストを行う前に、選択したモデルへのアクセスをプロビジョニングします。
- まだインストールされていない場合は、Heroku CLI をインストールします。次に、Heroku AI プラグインをインストールします。 - heroku plugins:install @heroku/plugin-ai
- 埋め込みモデルをアプリにアタッチします。 - # If you don't have an app yet, you can create one with: heroku create $APP_NAME # specify the name you want for your app (or skip this step to use an existing app you have) # Create and attach one of our chat models to your app, $APP_NAME: heroku ai:models:create -a $APP_NAME cohere-multilingual --as EMBEDDING
- 必要な - requests パッケージをインストールします。- pip install requests
Python のサンプルコード
import requests
import json
import os
# Global variables for API endpoint, authorization key, and model ID from Heroku config variables
ENV_VARS = {
    "EMBEDDING_URL": None,
    "EMBEDDING_KEY": None,
    "EMBEDDING_MODEL_ID": None
}
# Assert the existence of required environment variables, with helpful messages if they're missing.
for env_var in ENV_VARS.keys():
    value = os.environ.get(env_var)
    assert value is not None, (
        f"Environment variable '{env_var}' is missing. Set it using:\n"
        f"export {env_var}=$(heroku config:get -a $APP_NAME {env_var})"
    )
    ENV_VARS[env_var] = value
def parse_embedding_output(response):
    """
    Parses and prints the API response for the embedding request.
    Parameters:
        - response (requests.Response): The response object from the API call.
    """
    if response.status_code == 200:
        result = response.json()
        print("Embeddings:", result["data"])
    else:
        print(f"Request failed: {response.status_code}, {response.text}")
def generate_embeddings(payload):
    """
    Generates embeddings using the Stability AI Embeddings model.
    Parameters:
        - payload (dict): dictionary containing parameters for the embedding generation
    Returns:
        - Prints the generated embeddings.
    """
    # Set headers using the global API key
    HEADERS = {
        "Authorization": f"Bearer {ENV_VARS['EMBEDDING_KEY']}",
        "Content-Type": "application/json"
    }
    endpoint_url = ENV_VARS['EMBEDDING_URL'] + "/v1/embeddings"
    response = requests.post(endpoint_url, headers=HEADERS, data=json.dumps(payload))
    parse_embedding_output(response=response)
# Example payload
payload = {
    "model": ENV_VARS["EMBEDDING_MODEL_ID"],
    "input": ["Hello, I am a blob of text.", "How's the weather in Portland?"],
    "input_type": "search_document",
    "truncate": "END",
    "encoding_format": "float"
}
# Generate embeddings with the given payload
generate_embeddings(payload)