v1-embeddings API の Ruby クイックスタートガイド
この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
最終更新日 2025年01月27日(月)
Table of Contents
Heroku Managed Inference and Agent アドオンは現在パイロット段階です。パイロットの一環として提供される製品は本番環境での使用を目的としたものではなく、ベータサービスとみなされています。また、https://www.salesforce.com/company/legal/agreements.jsp のベータサービス条件が適用されます。
Cohere Embed Multilingual (cohere-embed-multilingual
) モデルは、提供されたテキスト入力に対するベクトル埋め込み (数値のリスト) を生成します。これらの埋め込みは、検索、分類、クラスタリングなどのさまざまなアプリケーションで使用できます。このガイドでは、Ruby を使用して 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 the embedding model to your app, $APP_NAME. heroku ai:models:create -a $APP_NAME cohere-multilingual --as EMBEDDING
Ruby のサンプルコード
# frozen_string_literal: true
require 'net/http'
require 'json'
require 'uri'
EMBEDDING_URL = ENV.fetch('EMBEDDING_URL') do
raise <<~ERROR
Environment variable 'EMBEDDING_URL' is missing.
Set it using:
export EMBEDDING_URL=$(heroku config:get -a $APP_NAME EMBEDDING_URL)
ERROR
end
EMBEDDING_KEY = ENV.fetch('EMBEDDING_KEY') do
raise <<~ERROR
Environment variable 'EMBEDDING_KEY' is missing.
Set it using:
export EMBEDDING_KEY=$(heroku config:get -a $APP_NAME EMBEDDING_KEY)
ERROR
end
EMBEDDING_MODEL_ID = ENV.fetch('EMBEDDING_MODEL_ID') do
raise <<~ERROR
Environment variable 'EMBEDDING_MODEL_ID' is missing.
Set it using:
export EMBEDDING_MODEL_ID=$(heroku config:get -a $APP_NAME EMBEDDING_MODEL_ID)
ERROR
end
##
# Parses and prints the API response for the embedding request.
#
# @param response [Net::HTTPResponse] The response object from the API call.
def parse_embedding_output(response)
if response.is_a?(Net::HTTPSuccess)
result = JSON.parse(response.body)
puts "Embeddings: #{result['data']}"
else
puts "Request failed: #{response.code}, #{response.body}"
end
end
##
# Generates embeddings using the Stability AI Embeddings model.
#
# @param payload [Hash] Hash containing parameters for the embedding generation.
def generate_embeddings(payload)
uri = URI.join(EMBEDDING_URL, '/v1/embeddings')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{EMBEDDING_KEY}"
request['Content-Type'] = 'application/json'
request.body = payload.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
http.request(request)
end
parse_embedding_output(response)
end
# Example payload
payload = {
model: 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)