カテゴリー【IBM Watson、Node.js】
Watson AssistantをGUIで作成しAPIから呼び出す(Node.js編)
POSTED BY
2024-04-28
2024-04-28

Watson AssistantをGUIで作成しAPIから呼び出す(準備編)
Watson AssistantをGUIで作成しAPIから呼び出す(Python編)
最後に、Node.js版です。書式がPythonからNodeに変わっただけで、入出力データは全く同じとなります。
Node.jsのインストールなどはこちら。
Watson SDK for Node.jsをインストール
npm install ibm-watson@^5.1.0
プロキシ環境下固有の修正
プロキシサーバを利用していない場合、飛ばしてください。現バージョンではプロキシ環境下では、SDKを直接修正する必要があります。
tunnelを入れる
npm install tunnel
node_modules/ibm-cloud-sdk-core/lib/request-wrapper.js を直接編集する。
ファイル先頭部にtunnelをrequireする。
"use strict";
var tunnel = require("tunnel");
70行目あたり~
// merge valid Axios Config into default.
extend(true, axiosConfig, allowedAxiosConfig.reduce(function (reducedConfig, key) {
reducedConfig[key] = axiosOptions[key];
return reducedConfig;
}, {}));
this.axiosInstance = axios_1.default.create(axiosConfig);
となっているところ、間に以下プロキシ記述を追加する。
プロキシサーバーのURLが http://proxy.local.example1155.jp:3128/ であるとすると、
// merge valid Axios Config into default.
extend(true, axiosConfig, allowedAxiosConfig.reduce(function (reducedConfig, key) {
reducedConfig[key] = axiosOptions[key];
return reducedConfig;
}, {}));
var agent = tunnel.httpsOverHttp({
proxy: {
host: 'proxy.local.example1155.jp',
port: 3128,
},
});
axiosConfig.httpsAgent = agent;
axiosConfig.proxy = false;
this.axiosInstance = axios_1.default.create(axiosConfig);
と、修正します。
あとは、前回のWatson AssistantをGUIで作成しAPIから呼び出す(Python編)のPythonソースがNode.jsソースになるだけですので、以下、ソースと出力のみ置いておきます。
Assistant ID,API Key,Session IDは自分のものに差し替えてください。
API接続しセッションIDを取得
| JavaScript | watson_create_session.js | GitHub Source |
const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');
const service = new AssistantV2({
version: '2019-02-28',
authenticator: new IamAuthenticator({
apikey: 'GGGGGG-KKKKKKKK-VVVVVV-XXXXXX',
}),
url: 'https://gateway-tok.watsonplatform.net/assistant/api',
});
service.createSession({
assistantId: 'aaaaaaaa-bbbbbbb-cccccc-ddddddd'
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
})
.catch(err => {
console.log(err);
});
node watson_create_session.js
| JSON | watson_create_session.js.json | GitHub Source |
{
"status": 201,
"statusText": "Created",
"headers": {
"content-type": "application/json; charset=utf-8",
"content-length": "53",
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS",
"access-control-allow-headers": "Content-Type, Content-Length, Authorization, X-Watson-Authorization-Token, X-WDC-PL-OPT-OUT, X-Watson-UserInfo, X-Watson-Learning-Opt-Out, X-Watson-Metadata",
"access-control-max-age": "3600",
"content-security-policy": "default-src 'none'",
"x-dns-prefetch-control": "off",
"x-frame-options": "SAMEORIGIN",
"strict-transport-security": "max-age=31536000; includeSubDomains;",
"x-download-options": "noopen",
"x-content-type-options": "nosniff",
"x-xss-protection": "1; mode=block",
"x-response-time": "12.757ms",
"x-global-transaction-id": "d82240d4719a15b86be4321f8fcef3b7",
"x-dp-watson-tran-id": "d82240d4719a15b86be4321f8fcef3b7",
"x-edgeconnect-midmile-rtt": "8",
"x-edgeconnect-origin-mex-latency": "66",
"date": "Sun, 01 Dec 2019 10:50:16 GMT",
"connection": "close"
},
"result": {
"session_id": "b2553333-2ace-4999-855c-da8cb666f39f"
}
}
会話してみる
| JavaScript | watson_send_message_1.js | GitHub Source |
const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');
const service = new AssistantV2({
version: '2019-02-28',
authenticator: new IamAuthenticator({
apikey: 'GGGGGG-KKKKKKKK-VVVVVV-XXXXXX',
}),
url: 'https://gateway-tok.watsonplatform.net/assistant/api',
});
service.message({
assistantId: 'aaaaaaaa-bbbbbbb-cccccc-ddddddd',
sessionId: 'b2553333-2ace-4999-855c-da8cb666f39f',
input: {
'message_type': 'text',
'text': '旅行に行きたい',
'options': {
'return_context': true
}
},
context: {
'skills': {
'main skill': {
'user_defined': {
'username': '太郎'
}
}
}
}
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
})
.catch(err => {
console.log(err);
});
node watson_send_message_1.js
| JSON | watson_recv_message_1.js.json | GitHub Source |
{
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json; charset=utf-8",
"content-length": "312",
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS",
"access-control-allow-headers": "Content-Type, Content-Length, Authorization, X-Watson-Authorization-Token, X-WDC-PL-OPT-OUT, X-Watson-UserInfo, X-Watson-Learning-Opt-Out, X-Watson-Metadata",
"access-control-max-age": "3600",
"content-security-policy": "default-src 'none'",
"x-dns-prefetch-control": "off",
"x-frame-options": "SAMEORIGIN",
"strict-transport-security": "max-age=31536000; includeSubDomains;",
"x-download-options": "noopen",
"x-content-type-options": "nosniff",
"x-xss-protection": "1; mode=block",
"x-watson-session-timeout": "session_timeout=300",
"x-response-time": "62.473ms",
"x-global-transaction-id": "b8b0c4fed970307e208399419c2163d7",
"x-dp-watson-tran-id": "b8b0c4fed970307e208399419c2163d7",
"x-edgeconnect-midmile-rtt": "8",
"x-edgeconnect-origin-mex-latency": "114",
"date": "Sun, 01 Dec 2019 10:50:39 GMT",
"connection": "close"
},
"result": {
"output": {
"generic": [
{
"response_type": "text",
"text": "太郎さん、国内ですか?海外ですか?"
}
],
"intents": [
{
"intent": "旅行",
"confidence": 0.9467347621917725
}
],
"entities": []
},
"context": {
"skills": {
"main skill": {
"user_defined": {
"username": "太郎"
},
"system": {}
}
},
"global": {
"system": {
"turn_count": 1
}
}
}
}
}
質問に答えてみる
| JavaScript | watson_send_message_2.js | GitHub Source |
const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');
const service = new AssistantV2({
version: '2019-02-28',
authenticator: new IamAuthenticator({
apikey: 'GGGGGG-KKKKKKKK-VVVVVV-XXXXXX',
}),
url: 'https://gateway-tok.watsonplatform.net/assistant/api',
});
service.message({
assistantId: 'aaaaaaaa-bbbbbbb-cccccc-ddddddd',
sessionId: 'b2553333-2ace-4999-855c-da8cb666f39f',
input: {
'message_type': 'text',
'text': '行くなら国内がいいです。',
'options': {
'return_context': true
}
}
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
})
.catch(err => {
console.log(err);
});
node watson_send_message_2.js
| JSON | watson_recv_message_2.js.json | GitHub Source |
{
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json; charset=utf-8",
"content-length": "372",
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS",
"access-control-allow-headers": "Content-Type, Content-Length, Authorization, X-Watson-Authorization-Token, X-WDC-PL-OPT-OUT, X-Watson-UserInfo, X-Watson-Learning-Opt-Out, X-Watson-Metadata",
"access-control-max-age": "3600",
"content-security-policy": "default-src 'none'",
"x-dns-prefetch-control": "off",
"x-frame-options": "SAMEORIGIN",
"strict-transport-security": "max-age=31536000; includeSubDomains;",
"x-download-options": "noopen",
"x-content-type-options": "nosniff",
"x-xss-protection": "1; mode=block",
"x-watson-session-timeout": "session_timeout=300",
"x-response-time": "89.074ms",
"x-global-transaction-id": "327b5a1cf3bcb014dd3be1f1b0637d03",
"x-dp-watson-tran-id": "327b5a1cf3bcb014dd3be1f1b0637d03",
"x-edgeconnect-midmile-rtt": "8",
"x-edgeconnect-origin-mex-latency": "120",
"date": "Sun, 01 Dec 2019 10:52:43 GMT",
"connection": "close"
},
"result": {
"output": {
"generic": [
{
"response_type": "text",
"text": "そうですか、国内に行きたいんですね太郎さん"
}
],
"intents": [],
"entities": [
{
"entity": "旅行の種類",
"location": [
4,
6
],
"value": "国内",
"confidence": 1
}
]
},
"context": {
"skills": {
"main skill": {
"user_defined": {
"username": "太郎",
"traveltype": "国内"
},
"system": {}
}
},
"global": {
"system": {
"turn_count": 2
}
}
}
}
}
以上です。お疲れ様でした。
Watson AssistantをGUIで作成しAPIから呼び出す(準備編) Watson AssistantをGUIで作成しAPIから呼び出す(Python編)
Android
iPhone/iPad
Flutter
MacOS
Windows
Debian
Ubuntu
CentOS
FreeBSD
RaspberryPI
HTML/CSS
C/C++
PHP
Java
JavaScript
Node.js
Swift
Python
MatLab
Amazon/AWS
CORESERVER
Google
仮想通貨
LINE
OpenAI/ChatGPT
IBM Watson
Microsoft Azure
Xcode
VMware
MySQL
PostgreSQL
Redis
Groonga
Git/GitHub
Apache
nginx
Postfix
SendGrid
Hackintosh
Hardware
Fate/Grand Order
ウマ娘
将棋
ドラレコ
※本記事は当サイト管理人の個人的な備忘録です。本記事の参照又は付随ソースコード利用後にいかなる損害が発生しても当サイト及び管理人は一切責任を負いません。
※本記事内容の無断転載を禁じます。
※本記事内容の無断転載を禁じます。
【WEBMASTER/管理人】
自営業プログラマーです。お仕事ください!ご連絡は以下アドレスまでお願いします★
【キーワード検索】
【最近の記事】【全部の記事】
LetsEncrypt/certbotの証明書自動更新がエラーになる場合Wav2Lipのオープンソース版を改造して外部から呼べるAPI化する
Wav2Lipのオープンソース版で静止画の口元のみを動かして喋らせる
【iOS】アプリアイコン・ロゴ画像の作成・設定方法
オープンソースリップシンクエンジンSadTalkerをAPI化してアプリから呼ぶ【2】
オープンソースリップシンクエンジンSadTalkerをAPI化してアプリから呼ぶ【1】
【Xcode】iPhone is not available because it is unpairedの対処法
【Let's Encrypt】Failed authorization procedure 503の対処法
【Debian】古いバージョンでapt updateしたら404 not foundでエラーになる場合
ファイアウォール内部のWindows11 PCにmacOS Sequoiaからリモートデスクトップする
【人気の記事】【全部の記事】
【Windows10】リモートデスクトップ間のコピー&ペーストができなくなった場合の対処法進研ゼミチャレンジタッチをAndroid端末化する
Windows11+WSL2でUbuntuを使う【2】ブリッジ接続+固定IPの設定
【Apache】サーバーに同時接続可能なクライアント数を調整する
Windows11のコマンドプロンプトでテキストをコピーする
Androidホームで左にスワイプすると出てくるニュース共を一切表示させない方法
【Linux】mkfsコマンドでProceed anyway?と確認を求められるのを回避する
VirtualBoxの仮想マシンをWindows起動時に自動起動し終了時に自動サスペンドする
タスクスケジューラで変更を適用できません。ユーザーアカウントが不明であるか、パスワードが正しくないか、またはユーザーアカウントにタスクを変更する許可がありません。と出た
Googleスプレッドシートを編集したら自動で更新日時を入れる
【カテゴリーリンク】
Android
iPhone/iPad
Flutter
MacOS
Windows
Debian
Ubuntu
CentOS
FreeBSD
RaspberryPI
HTML/CSS
C/C++
PHP
Java
JavaScript
Node.js
Swift
Python
MatLab
Amazon/AWS
CORESERVER
Google
仮想通貨
LINE
OpenAI/ChatGPT
IBM Watson
Microsoft Azure
Xcode
VMware
MySQL
PostgreSQL
Redis
Groonga
Git/GitHub
Apache
nginx
Postfix
SendGrid
Hackintosh
Hardware
Fate/Grand Order
ウマ娘
将棋
ドラレコ