0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

watsonx.aiをAPIで使うサンプル(シェルスクリプト版)

Posted at

概要

ネット上にPythonを使ったサンプルコードは見かけるのですが、ちょこっと動かすのに環境準備が最も楽なのはシェルスクリプトだなってことで、サンプルコードを備忘録しておきます。

準備

1. 環境

  • curl
  • jq

2. IBM Cloud

  • API keyの取得
    もしなければ、ここから作れる

3. watsonx.ai

  • プロジェクトIDの取得
    image.png

実行

API keyとプロジェクトIDの部分を置き換えて、以下をシェルスクリプトにして実行します。
watsonx.aiのリージョン(例ではus-south=ダラス)、LLMのモデル名(例ではibm/granite-3-8b-instruct)、その他のパラメータは必要に応じて置き換えてください。

#!/bin/bash

#### 以下の値は各自の環境に合わせて修正 ####
APIKEY=自分のAPIkey
PROJECT_ID=自分のプロジェクトID
#### ここまで ####

echo -n "プロンプトを入力してください:"
read INPUT

access_token=$(curl -s -X POST 'https://iam.cloud.ibm.com/identity/token' -H 'Content-Type: application/x-www-form-urlencoded' -d 'grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey='"$APIKEY" | jq -r '.access_token')

data="{\"model_id\": \"ibm/granite-3-8b-instruct\",
  \"project_id\": \"$PROJECT_ID\",
  \"input\": \"$INPUT\",
  \"parameters\": {
    \"decoding_method\": \"greedy\",
    \"max_new_tokens\": 200,
    \"min_new_tokens\": 0,
    \"stop_sequences\": [],
    \"repetition_penalty\": 1.1
}}"

curl -s -X POST 'https://us-south.ml.cloud.ibm.com/ml/v1/text/generation?version=2023-05-29' \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H "Authorization: Bearer $access_token" \
  -d "$data" | jq -r '.results'
  • 実行例
% ./watsonx_test.sh
プロンプトを入力してください:IBMはどのような会社ですか?

[
  {
    "generated_text": "\nIBMは、アメリカ合衆国の大手情報技術(IT)企業であり、1911年に設立されました。IBMは、ハードウェア、ソフトウェア、サービスを提供する多岐にわたるビジネスを持っています。これには、クラウドコンピューティング、人工知能(AI)、データ分析などが含まれます。また、IBMは世界中の企業や政府機関と協力して、イノベーションと変革を推進しています。\n\nIBMの歴史は、1911年にコンピューター・タブレット記録機(Tabulating Machine Company)、計算機(Computing-Tabulating-Recording Company, CTR)、およびインターナショナル・ビジネスマシ",
    "generated_token_count": 200,
    "input_token_count": 11,
    "stop_reason": "max_tokens"
  }
]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?