關於這個例子的完整介紹,請參考公眾號 「汪子熙」的兩篇文章:
SAP C/4HANA與人工智慧和增強現實(AR)技術結合的又一個創新案例
和使用Recast.AI創建具有人工智慧的聊天機器人:
本文介紹如何用Java代碼同recast.AI網站上創建好的模型交互。
我創建了一個名為get-product-infomation的機器學習模型,用"Add an expression"下面的這麼多句子去喂這個模型:
一會測試時,我會用這個句子進行測試 " I am looking for some materials", 所以先記下來。
如果任意輸入一句話,recast.AI識別出來意圖為get-product-infomation, 我希望AI自動返回一些句子,這些句子定義在recast.AI模型的Actions標籤頁下面:
比如這個Actions模型的意思是,從Sure, what type of product are you going to produce?和Cool, what products do you want to produce?裏隨機挑選一句返回。
下圖右半部份是recast.AI的測試控制檯。
下面是用Java代碼方式消費這個人工智慧模型的例子:
public class RecastAIService {
private final static String RECAST_AI_URL = "https://api.recast.ai/build/v1/dialog";
private final static String DEVELOPER_TOKEN = "Token feb6b413a1a8cf8efdd53f48ba1d4";
public Answer dialog(final String content, final String conversationId) throws ClientProtocolException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost postRequest = new HttpPost(RECAST_AI_URL);
postRequest.addHeader("Authorization", DEVELOPER_TOKEN);
postRequest.addHeader("Content-Type", "application/json");
String body = "{"message": {"content":"" + content + "","type":"text"}, "conversation_id": "" + conversationId +""}";
HttpEntity entity = new StringEntity(body);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
if(response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity());
JSONObject resultJsonObj = JSON.parseObject(result);
JSONObject results = (JSONObject) resultJsonObj.get("results");
JSONArray messages = results.getJSONArray("messages");
JSONObject nlp = (JSONObject) results.get("nlp");
JSONArray intents = nlp.getJSONArray("intents");
Answer answer = new Answer();
if (null != messages && messages.size() > 0){
JSONObject messageJson = messages.getJSONObject(0);
answer.setContent(messageJson.getString("content"));
}
if (null != intents && intents.size() > 0){
JSONObject intentJson = intents.getJSONObject(0);
answer.setIntent(intentJson.getString("slug"));
return answer;
logger.debug("Failed to access recastai. The response code is" + response.getStatusLine().getStatusCode());
return null;
測試代碼:
傳入I am looking for some materials,recast.AI解析出這個句子的意圖有99%的可能性是get-product-information:
Java代碼返回的句子也確實是recast.AI模型裏維護的回復之一:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
推薦閱讀: