DataRobot LLM Gatewayの使用¶
The DataRobot LLM gateway is a service that unifies and simplifies LLM access across DataRobot. It provides a DataRobot API endpoint to interface with LLMs hosted by external LLM providers. To request LLM responses from the DataRobot LLM gateway, you can use any API client that supports OpenAI-compatible chat completion API, for example, the OpenAI Python API library.
注:LLM Gatewayを使用したLLMのプロビジョニングは、DataRobotが管理する(クラウド)インスタンスと、シングルテナントSaaS(STS)セルフマネージドインスタンスにおいて、対応する料金プランで利用できます。オンプレミス環境では利用できません。詳細はDataRobotの担当者にお問い合わせください。Gateway自体は、LLMを呼び出すためのサービスとして、すべてのプラットフォームで利用可能です。
セットアップ¶
DataRobot LLM Gatewayはプレミアム機能です。この機能を有効にする方法については、DataRobotの担当者または管理者にお問い合わせください。DataRobot LLM GatewayをOpenAI Python APIライブラリで使用するには、まず、OpenAIクライアントパッケージがインストールされ、インポートされていることを確認します。DataRobot Pythonクライアントもインポートする必要があります。
%pip install openai
import datarobot as dr
from openai import OpenAI
from datarobot.models.genai.llm_gateway_catalog import LLMGatewayCatalog
from pprint import pprint
LLM Gatewayへの接続¶
次に、OpenAIクライアントを初期化します。ベースURLはDataRobot LLM Gatewayのエンドポイントです。以下の例では、DataRobot APIエンドポイント(dr_clientから取得)と/genai/llmgwを組み合わせて、このURLを構築しています。通常は、https://app.datarobot.com/api/v2/genai/llmgw、https://app.eu.datarobot.com/api/v2/genai/llmgw、https://app.jp.datarobot.com/api/v2/genai/llmgw、または組織のDataRobot APIエンドポイントのURLに/genai/llmgwを付加したものになります。APIキーはお使いのDataRobot APIキーです。
dr_client = dr.Client()
DR_API_TOKEN = dr_client.token
LLM_GATEWAY_BASE_URL = f"{dr_client.endpoint}/genai/llmgw"
client = OpenAI(
base_url=LLM_GATEWAY_BASE_URL,
api_key=DR_API_TOKEN,
)
print(f"Your LLM gateway URL is {LLM_GATEWAY_BASE_URL}.")
モデルの選択とリクエスト¶
コードでは、サポートされているプロバイダーLLMを指定し、LLMにプロンプトとして送信するメッセージを設定できます。オプションの引数としてclient_idがあり、ここではメータリングに使用する呼び出し元サービスgenai-playground、custom-model、またはmoderationsを指定できます。
この例では、LLM Gatewayのカタログエンドポイントを呼び出して、各プロバイダーからサポートされている最新のLLMの1つを取得します。
# Get catalog entries using the SDK (active, non-deprecated models by default)
catalog_entries = LLMGatewayCatalog.list(limit=20)
first_model_by_provider = {}
# Iterate through the catalog to select the first supported LLM from each provider
for entry in catalog_entries:
# Get the provider name from the provider key
provider_name = entry.provider
# If the provider isn't already recorded, store the full model string
if provider_name not in first_model_by_provider:
model_name = entry.model
first_model_by_provider[provider_name] = model_name
# Store the list of models
models = list(first_model_by_provider.values())
print(f"Selected models from {len(first_model_by_provider)} providers:")
pprint(first_model_by_provider, sort_dicts=False)
client、models、messageを定義したら、LLM Gatewayにチャット補完リクエストを行うことができます。認証には、DataRobotが提供する資格情報が使用されます。
from IPython.display import display, Markdown
# Store a message to send to the LLM
message = [{"role": "user", "content": "Hello! What is your name and who made you?"}]
for model in models:
response = client.chat.completions.create(
model=model,
messages=message,
)
response_text = response.choices[0].message.content
output_as_markdown = f"""
**{model}:**
{response_text}
---
"""
display(Markdown(output_as_markdown));
LLM gatewayを直接呼び出す際にチャット補完リクエストをさらに設定するには、temperatureやmax_completion_tokensなどのLLMパラメーター設定を指定します。これらのパラメーターはカスタムモデルでもサポートされています。使用可能なパラメーターの詳細については、OpenAIのチャット補完に関するドキュメントを参照してください。
model2 = models[0] if len(models) > 0 else "openai/gpt-4o" # Use first model or fallback
message2 = [{"role": "user", "content": "Hello! What is your name and who made you? How do you feel about Agentic AI"}]
extra_body2 = {
"temperature": 0.8,
"max_completion_tokens": 2000,
}
response2 = client.chat.completions.create(
model=model2,
messages=message2,
extra_body=extra_body2,
)
response_text2 = response2.choices[0].message.content
output_as_markdown2 = f"""
**{model2}:**
{response_text2}
---
"""
display(Markdown(output_as_markdown2));
サポートされているLLMの特定¶
LLM GatewayでサポートされているLLMのリストを提供するために、この例ではLLM Gateway Catalog SDKを使用して利用可能なモデルを取得します。
# Get all available models using the SDK convenience method
supported_llms = LLMGatewayCatalog.get_available_models()
print(f"Found {len(supported_llms)} available models:")
pprint(supported_llms[:10]) # Show first 10 models
if len(supported_llms) > 10:
print(f"... and {len(supported_llms) - 10} more models")
サポートされていないLLMを使用しようとすると、LLM Gatewayはエラーメッセージを返し、指定されたLLMがLLMカタログにないことを伝えます。
# Verify model availability
unsupported_model = "unsupported-provider/random-llm"
try:
# Check if the model is available before making the request
model_entry = LLMGatewayCatalog.verify_model_availability(unsupported_model)
print(f"Model {unsupported_model} is available: {model_entry.name}")
except ValueError as e:
print(f"Model {unsupported_model} is not available: {e}")
# Alternative: still show the original error handling for comparison
messages3 = [
{"role": "user", "content": "Hello!"}
]
try:
response = client.chat.completions.create(
model=unsupported_model,
messages=messages3,
)
response.choices[0].message.content
except Exception as e:
print(f"Direct API call error: {str(e)}")
特定のモデルを使用する前に、そのモデルが利用可能かどうかを確認することもできます。これは、エラー処理や検証に役立ちます。
# Test different model IDs
test_models = [
"azure/gpt-4o-2024-11-20", # Example Azure model
"openai/gpt-4o", # Example OpenAI model
"non-existent-model" # This should fail
]
for model_id in test_models:
try:
model_entry = LLMGatewayCatalog.verify_model_availability(model_id)
print(f"✓ {model_id} is available:")
pprint({
"name": model_entry.name,
"provider": model_entry.provider,
"context_size": f"{model_entry.context_size:,} tokens",
"active": model_entry.is_active,
"deprecated": model_entry.is_deprecated
}, sort_dicts=False)
except ValueError as e:
print(f"✗ {model_id} is not available: {e}")
print()
高度なフィルター¶
LLM Gateway Catalog SDKは、高度なフィルター機能を備えており、ニーズに合ったモデルを見つけることができます。
# Get all models including deprecated ones
all_entries = LLMGatewayCatalog.list(
only_active=False,
only_non_deprecated=False,
limit=20
)
active_count = sum(1 for entry in all_entries if entry.is_active)
deprecated_count = sum(1 for entry in all_entries if entry.is_deprecated)
print(f"Found {len(all_entries)} total entries:")
print(f" - Active: {active_count}")
print(f" - Deprecated: {deprecated_count}")
# Show deprecated models with replacement info
deprecated_models = [e for e in all_entries if e.is_deprecated]
if deprecated_models:
print("\nDeprecated models with replacements (first 3 models):")
for entry in deprecated_models[:3]:
deprecated_info = {
"model": entry.model,
"name": entry.name,
"provider": entry.provider
}
if entry.retirement_date:
deprecated_info["retirement_date"] = entry.retirement_date
if entry.suggested_replacement:
deprecated_info["suggested_replacement"] = entry.suggested_replacement
pprint(deprecated_info, sort_dicts=False)
print()
# Get detailed catalog entries with rich information
catalog_entries = LLMGatewayCatalog.list(limit=5)
print("Detailed catalog entries:")
for entry in catalog_entries:
entry_info = {
"name": entry.name,
"model": entry.model,
"provider": entry.provider,
"context_size": f"{entry.context_size:,} tokens",
"active": entry.is_active,
"deprecated": entry.is_deprecated
}
pprint(entry_info, sort_dicts=False)
print()