bluemix 23th meetup 실습 자료

22
[튜토리얼] Watson Conversation으로 쉽게 만드는 챗봇 IBM Developer Outreach Team

Upload: -

Post on 21-Jan-2018

663 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: Bluemix 23th meetup 실습 자료

[튜토리얼]

WatsonConversation으로쉽게만드는챗봇

IBMDeveloperOutreachTeam

Page 2: Bluemix 23th meetup 실습 자료

ContactUs

#building-with-watson#watson-korea

facebook.com/groups/BluemixStudy

wdc-slack-inviter.mybluemix.net

http://stackoverflow.com/questions/tagged/watson-conversation

https://developer.ibm.com/answers/topics/watson-conversation.html

WatsonConversation관련문서목록

WatsonConversation소개문서https://www.ibm.com/watson/developercloud/doc/conversation/index.htmlAPI문서https://www.ibm.com/watson/developercloud/conversation/api/v1/#introductionAPI테스트https://watson-api-explorer.mybluemix.net/apis/conversation-v1개발툴,SDK,StarterKithttps://www.ibm.com/watson/developercloud/developer-tools.html튜토리얼https://developer.ibm.com/kr/cloud/bluemix/watsonservice/2017/01/13/watsonchatbot-1-watson-conversation/샘플코드https://github.com/watson-developer-cloud/conversation-simple

https://developer.ibm.com/kr

Page 3: Bluemix 23th meetup 실습 자료

튜토리얼소개

1. WCS시작하기

2.메신저와연동하기

3.질문수집하기

4. Intent분류하고학습시키기

5. Entity와Dialog설정하기

6.Backend서비스와연동하기

사용자

인터페이스

어플리케이션

워크스페이스

ConversationService 백엔드시스템

Architecture

Page 4: Bluemix 23th meetup 실습 자료

사전준비사항

Bluemix Account생성및 CLI설치1 2

3 GIT설치

Node.js설치

https://github.com/cloudfoundry/cli#downloads

https://console.ng.mybluemix.net https://nodejs.org/en/#download

https://git-scm.com/book/ko/v1/%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0-Git-%EC%84%A4%EC%B9%98

Page 5: Bluemix 23th meetup 실습 자료

목차

1. WCS시작하기• Bluemix에서WCS(WatsonConversationService)인스턴스생성하기• WCS툴에접근하기• 내Workspace생성하기• 내 Credential정보확인하기• #Greeting작성하기

2. 챗봇노출하기• WebClient로노출하기 (필수)• 카카오톡으로노출하기 (선택)• 텔레그램으로노출하기 (선택)

3. 질문수집하기

4. Intent분류하고학습시키기

5. Entity와 Dialog설정하기

6. Backend서비스와연동하기

Page 6: Bluemix 23th meetup 실습 자료

튜토리얼 1.WCS시작하기WatsonConversationService (이하WCS)는 Bluemix(IBMPaaSPlatform)을통해서제공되는클라우드서비스입니다. Bluemix에서WCS인스턴스를생성하여사용할수있습니다.

이튜토리얼은 Bluemix의가입과정은생략합니다.

1) bluemix.net에접속합니다.2) Catalog에서 Conversation서비스를작성합니다.왼쪽카테고리에서Watson을선택하면서비스를더

빨리찾을수있습니다.

3) 서비스를작성하면아래와같은화면이나타납니다.다른메뉴로이동했다가다시이화면을보려면좌측상단의 햄버거버튼을눌러 Service/Dashboard를선택하고작성한 Conversation인스턴스를클릭합니다.

4) LaunchTool버튼을눌러WCS툴로이동합니다.

Page 7: Bluemix 23th meetup 실습 자료

5) ConversationTool의 URL을편의를위해북마크에추가합니다.브라우저별방법은상이합니다.

6) Create버튼을눌러Workspace를생성합니다. Workspace는챗봇을빌드하기위해 Intent등을트레이닝시키기위한단위입니다.우측에 Import버튼이있습니다.추후에Workspace단위로 Import/Export할수도있음을참조하십시오.

7) Name필드에자유롭게이름을입력하고, Language로 English를선택하십시오.

Page 8: Bluemix 23th meetup 실습 자료

8) Workspace가생성되었습니다 !

9) 마지막으로앞으로어플리케이션연동에필요한 Credential정보를확인합니다. 좌측상단에있는햄버거메뉴를누른후 Deploy>Credentials메뉴를클릭합니다.

10) Username,Password및WorkspaceID를선호하는에디터에 Copy합니다.

Workspace는어플리케이션이사용하는단위입니다.하나의WatsonConversationService인스턴스안에여러Workspace를생성할수있습니다.Workspace는다음과같은타입의 artifact로이루어집니다.

• Intent:Intent는사용자가하려는말의목적을의미합니다.따라서우리는서비스에서제공하고자하는요청의모든타입을 Intent로정의하게됩니다.예를들어회의실예약은하나의 Intent가될수있습니다.WatsonConversation에서 Intent를지칭할때에는 #을 prefix로사용합니다.Intent를정의할때에는사용자가이 Intent를목적으로말을할때사용할가능성이있는최대한많은예시를제공하는것이좋습니다.예를들어회의실예약이라는 Intent에는 “회의실예약해주세요.”,“지금빈회의실이있나요?”등의예시를제공할수있습니다.

• Entity :Entity는 Intent와관련된용어또는목적어를의미합니다.Entity는 Intent에대해구체적인문맥(Context)을제공하는데에쓰입니다.예를들어회의실예약이라는 Intent를사용하기위해서는회의실이라는 Entity를정의할수있습니다.회의실 Entity에는실제로보유중인회의실이름을담으면됩니다.이렇게 Entity를정의하면사용자가 “진달래회의실지금비어있어?”라고했을때회의실 Entity의값이“진달래”로리턴되게됩니다.

• Dialog :Dialog는대화의흐름을분기하는것으로어플리케이션이정의된 Intent와 Entity를인식했을때어떠한응답을할것인지를정의합니다.다시말하면사용자가대화를시도했을때이대화의 Intent와Entity를파악한후어떠한응답을할것인지를정의합니다.

Page 9: Bluemix 23th meetup 실습 자료

11) 첫번째 Intent로 #Greeting을작성해보겠습니다.상단의메뉴에서 Intents를클릭하여이동합니다.

12) Createnew버튼을클릭하여인텐트를작성합니다.

13) 작성후에 Create버튼을클릭합니다.

Page 10: Bluemix 23th meetup 실습 자료

14) Watson의첫번째응답메세지를작성해보겠습니다.상단메뉴에서 Dialog로이동합니다.

15) Create버튼을눌러 Dialog작성을시작합니다.먼저Welcome메세지를작성합니다. Trigger조건에conversation_start를입력하면나오는드롭다운메뉴에서 createnewcondition을클릭합니다.

16) 노드의이름에Welcome을입력합니다.

17) 다음과같이 Response를입력합니다.

Goodtoseeyou!Icanhelpyoubookormanageyourmeetingroom.

Page 11: Bluemix 23th meetup 실습 자료

18) Welcome노드하위의 +버튼을눌러새노드를작성합니다.

19) 아래와같이노드를작성합니다.

20) 지금까지작성한챗봇을테스트해보겠습니다. 우측상단에위치한메세지아이콘을선택합니다.

21) 대화창을이용하여테스트합니다. Watson이예측한 Intent가맞지않는경우바로보정할수있습니다.

튜토리얼 1. WCS시작하기를모두마치셨습니다 !J

Page 12: Bluemix 23th meetup 실습 자료

튜토리얼 2.챗봇노출하기두번째단계로,내챗봇을어플리케이션을통해외부로노출하는단계입니다.

2.1웹어플리케이션으로노출하기 (필수)

웹어플리케이션으로노출하기위해먼저아래튜토리얼을따르십시오.

https://developer.ibm.com/kr/cloud/bluemix/watsonservice/2017/01/20/watsonchatbot-2-watson-conversation/

-텔테그램또는카카오톡에서 Context를저장하기위해 Cloudant를사용합니다.2.1에서어플리케이션을블루믹스에올릴때 Cloudant인스턴스가생성되었을것입니다.블루믹스의대쉬보드에서생성된 Cloudant서비스를선택하고 “ServiceCredentials”탭에서 url을복사하여어플리케이션의 .env에 CLOUDANT_URL값으로복사합니다.

2.2카카오톡으로노출하기 (선택,옐로아이디가이미있는경우에만 !)

카카오톡으로노출하기위해아래튜토리얼을따르십시오.단, tutorial4를 checkout하지않고, 2.1에서작업하신내용에이어서작성합니다.

https://developer.ibm.com/kr/cloud/bluemix/watsonservice/2017/02/19/watsonchatbot-4-watson-conversation/

2.3텔레그램으로노출하기 (선택)

1)아래튜토리얼의 1번과정(1.텔레그램에 Bot생성하기)을따라하여텔레그램 bottoken을얻습니다.

https://developer.ibm.com/kr/developer-%EA%B8%B0%EC%88%A0-%ED%8F%AC%EB%9F%BC/2017/03/11/node-js-%EC%96%B4%ED%94%8C%EB%A6%AC%EC%BC%80%EC%9D%B4%EC%85%98-%ED%85%94%EB%A0%88%EA%B7%B8%EB%9E%A8%EA%B3%BC-%EC%97%B0%EB%8F%99%ED%95%98%EA%B8%B0/

2) 다음명령을사용하여 api모듈을설치합니다.

3) .env파일에다음환경변수를추가합니다.

4) /api밑에 telegram폴더를생성하고message.js를생성합니다.

>npm install–savenode-telegram-bot

#TelegramTELEGRAM_TOKEN=376884728:AAH0EcH3tPqBZ6G30tI8nEZCrchXXXXXXXX

chatbot-tutorial- api

- telegram- message.js

Page 13: Bluemix 23th meetup 실습 자료

5) /api/telegram/message.js를통해텔레그램메신저와대화서비스를연동합니다.먼저필요한모듈및값을가져옵니다.

'usestrict';

const conversation=require('../message');const config =require('../../util/config');const cloudant =require('../../util/db');const TelegramBot =require('node-telegram-bot');

const db =cloudant.db;const token=process.env.TELEGRAM_TOKEN;

6) 발급받은 token으로 Telegrambot을생성합니다.

letbot=newTelegramBot({'token':token

});

Page 14: Bluemix 23th meetup 실습 자료

7) bot.on이벤트를생성합니다.

bot.on('message',msg =>{letuser_key =msg.chat.id;letcontent={

text:msg.text};db.get(user_key).then(doc=>{

conversation.getConversationResponse(content,doc.context).then(data=>{db.insert(Object.assign(doc,{

'context':Object.assign(data.context,{'timezone':"Asia/Seoul”

}),}));bot.sendMessage({

'chat_id':user_key,'text':getOutputText(data)

});}).catch(err => {

bot.sendMessage({'chat_id':user_key,'text':JSON.stringify(err.message)

});});

}).catch(err=>{//firstcommunicationconversation.getConversationResponse(content,{}).then(data=>{

db.insert({'_id':user_key+"",//cloudant의 docid는반드시 string타입이어야합니다.'user_key':user_key+"",'context':data.context,'type':'telegram’

});bot.sendMessage({

'chat_id':user_key,'text':getOutputText(data)

});}).catch(err=>{

bot.sendMessage({'chat_id':user_key,'text':JSON.stringify(err.message)

});});

});});

bot.start()

functiongetOutputText(data){var output=data.output;if(output.text &&Array.isArray(output.text)){

returnoutput.text.join('\\n');}elseif(output.text){

returnoutput.text;}elsereturn"";}

Page 15: Bluemix 23th meetup 실습 자료

8)/api/Index.js에텔레그램코드를추가합니다.

const telegram_bot =require('./telegram/message');

9) 어플리케이션을로컬에서테스트하고에러가없으면블루믹스로 push합니다.

10) 텔레그램으로테스트합니다.

>npm start

>cf push

Page 16: Bluemix 23th meetup 실습 자료

튜토리얼 3.질문수집하기카카오톡에서

친구추가하여영문으로회의실예약을진행해주세요.

@camomile_bot

Page 17: Bluemix 23th meetup 실습 자료

튜토리얼 4.Intent분류하고학습시키기1) https://meetup23th.eu-gb.mybluemix.net/csv/questions에접속하여엑셀을다운로드합니다.

2) 엑셀을열어두번째 Column에아래표를참조하여 Intent값을명시합니다.

3) Comma(‘,’)separated형식으로저장해야WCS툴에바로업로드할수있습니다 !!

Intent Example

Greeting Hi

Reservation Wouldyoureservearoomformetomorrow?

PositiveAnswer Yes

기타 기타

Page 18: Bluemix 23th meetup 실습 자료

튜토리얼 5.Entity와 Dialog설정하기2.1SystemEntity사용하기

1) WCS툴의상단메뉴에서 Entities를선택합니다.

2) Systementities를사용하도록설정합니다.Systementities는날짜,숫자,통화등을핸들링할때매우유용합니다.회의실예약시에는날짜와시간이필요합니다.따라서이두 Entity를 Enable합니다.

Page 19: Bluemix 23th meetup 실습 자료

2.2 Dialog설정하기

이단계에서는사용자와의대화에서Watson이어떻게대답할것인지를결정하고분기하게됩니다.Dialog는 Intent와 Entity를사용하여사용자인풋을분석하며정보를수집하고유용한대답을하게만듭니다.Dialog는트리형태를가지는데각인텐트를최상위노드로놓고가지를치며적절한대답을할수있도록유도하면됩니다.이 Recipe에서는아래그림처럼 4개의최상위노드를만들것이며 Reservation노드가가장중요한비즈니스역할을할것입니다.

1) WCS툴의상단메뉴에서 Dialog를클릭하고 Create버튼을클릭합니다.

노드를생성하기앞서 Dialog에서사용하는용어를설명드리겠습니다.

• 노드(Node):노드는 Dialog를구성하는요소입니다.사용자와의대화에서 1번의상호작용을의미합니다.

• 컨디션(Condition):노드를구성하는요소로사용자의인풋등을바탕으로조건에맞는경우해당내용을응답합니다.

• 응답(Response):노드를구성하는요소로사용자의인풋이컨디션에매치되면활성화됩니다.간단한문자열을리턴할수도있고좀더복잡한프로세스를실행시킬수도있습니다.

• 브랜치(Branch):사용자와의대화를의미한일련의 DialogNode를브랜치라고합니다.사용자의인풋이기본노드의컨디션에맞을때브랜치가사용되게됩니다.

• 턴(Turn):사용자가인풋을하고이에응답하는하나의사이클을턴이라고합니다.브랜치는하나이상의턴을가질수있습니다.

• 기본노드(Basenode):브랜치의최상위노드(첫번째노드)를기본노드라고합니다.• 자식노드(Childnode):기본노드가아닌노드를자식노드라고합니다.자식노드는이전노드가최종응답을주기위해더많은사용자인풋또는프로세스를필요로할때사용됩니다.

• 동기노드또는자매노드(PeernodeorSiblingnode):다른노드의대안책이되는노드입니다.모든기본노드는다른기본노드의동기노드입니다.

• 노드메뉴(Nodemenu):노드를구성하느요소로노드를지우거나기능을추가할수있도록해줍니다.

노드를작성할때에는 SpEL(SpringExpressionLanguage)을사용합니다.자세한사용법은WatsonConversation에서사용하는 ExpressionLanguage를참조하세요.

Page 20: Bluemix 23th meetup 실습 자료

2) 4개의최상위노드를아래와같이작성합니다.

3) #Reservation노드의하위노드로아래와같이작성합니다.

Index Triggeredby ResponseCondition Response Jumpto

1 conversation_start Welcome!

2 #Greeting Hi,whatcanIdoforyou?,Hey,whatcanIdoforyou?

3 #Reservation{"context":{"dates":null,"rooms":null,"times":null},"output":{}}

3-1Condition

4 anything_else I’msorry,Idon’tunderstand.Pleasetryagain.

Index Triggeredby ResponseCondition Response Jumpto

3-1 NOT$user

{"context":{"user":{"id":"hjjo\\@kr.ibm.com","name":"HyeonJeongJo","email":"hjjo\\@kr.ibm.com","phone":"01031229436"}},"output":{}}

3-2Condition

3-2 $user

{"context":{"dates":"<?@sys-date?:$dates ?>","rooms":"<?@Room?:$rooms ?>","times":"<?@sys-time?:$times ?>"},"output":{}}

3-2-1Condition

3-2-1 NOT$dates

{"context":{"repeat":1},"output":{"text":{"values":["Whendoyouwanttohaveameeting?"],"selection_policy":"sequential"}}}

3-2-1-1 @sys-date 3-2Condition

3-2-1-2 true

I’msorry.Pleasetellmethedatesthatyouwanttobookaroom.Forexample,youcansayinformat“mm/dd/yyyy”

3-2-1-2-1 @sys-date 3-2Condition

3-2-1-2-2 $repeat<3 {"context":{"repeat":"<?$repeat+1?>"},"output":{}} 3-2-1-2Condition

3-2-1-2-3 true I’msorry.Ican’tunderstandyou.Pleasestartagain.

Page 21: Bluemix 23th meetup 실습 자료

3-2-2 NOT$times

{"context":{"repeat":1},"output":{"text":{"values":["Whattimedoyouprefer?"],"selection_policy":"sequential"}}}

3-2-2-1 @sys-time 3-2Condition

3-2-2-2 trueI’msorry.Pleasetellmethetimes.Youcantellmelikethis.“From13:00To14:00”

3-2-2-2-1 @sys-time 3-2Condition

3-2-2-2-2 $repeat<3 {"context":{"repeat":"<?$repeat+1?>"},"output":{}} 3-2-2-2Condition

3-2-2-2-3 true I’msorry.Ican’tunderstandyou.Pleasestartagain.

3-2-3 true

{"context":{"action":{"command":"check-availability","dates":"$dates","times":"$times"}},"output":{"text":{"values":["$user.name,OKIwillchecktheavailabilty ofroom.$dates,$times,$rooms"],"selection_policy":"sequential"}}}

3-2-3-1 #PositiveAnswer

{"context":{"action":{"dates":"$dates","times":"$times","command":"confirm-reservation"}},"output":{"text":{"values":["OK.<?context.room?>at<?context.times.get(0).value?>,<?context.dates ?>isreservedforyou."],"selection_policy":"sequential"}}}

3-2-3-2 true

{"context":{"action":null},"output":{"text":{"values":["Canceled.pleasestartagain."],"selection_policy":"sequential"}}}

3-3 true I’msorry.You’renotaregistereduserinoursystem.

Page 22: Bluemix 23th meetup 실습 자료

튜토리얼 6.Backend시스템과연동하기

https://developer.ibm.com/kr/cloud/bluemix/watsonservice/2017/02/12/watsonchatbot-3-watson-conversation/