SAP人工智能服務Recast.AI的一個簡單例子

關於這個例子的完整介紹,請參考公衆號 「汪子熙」的兩篇文章:java

SAP C/4HANA與人工智能和加強現實(AR)技術結合的又一個創新案例express

和使用Recast.AI建立具備人工智能的聊天機器人:json

本文介紹如何用Java代碼同recast.AI網站上建立好的模型交互。api

我建立了一個名爲get-product-infomation的機器學習模型,用"Add an expression"下面的這麼多句子去喂這個模型:app

一會測試時,我會用這個句子進行測試 " I am looking for some materials", 因此先記下來。機器學習

若是任意輸入一句話,recast.AI識別出來意圖爲get-product-infomation, 我但願AI自動返回一些句子,這些句子定義在recast.AI模型的Actions標籤頁下面:post

好比這個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的原創文章,請關注公衆號"汪子熙":

相關文章
相關標籤/搜索