关于这个例子的完整介绍,请参考公众号 “汪子熙”的两篇文章:
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模型里维护的回复之一:
本文来自云栖社区合作伙伴“汪子熙”,了解相关信息可以关注微信公众号"汪子熙"。