Skip to content

Instantly share code, notes, and snippets.

@christopheranderson
Last active November 6, 2017 11:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christopheranderson/879252457a11e61980a6bfe660ccca04 to your computer and use it in GitHub Desktop.
Save christopheranderson/879252457a11e61980a6bfe660ccca04 to your computer and use it in GitHub Desktop.
Functions with Cognitive Services

Demo!

Setup

  1. Create a cognitive services resource, grab the key
  2. Create a Function App via functions.azure.com (or use an existing one)
  3. Create a node Generic WebHook function (I named mine "sentiment")
  4. Copy index.js into the function
  5. Install request and node-uuid (Function App Settings -> Advanced Settings -> Tools -> Console; cd ./sentiment; npm install request node-uuid)
  6. Test via the test box below the fold - Input data: { text: "Azure Functions is freaking AMAZING!!!" }
  7. Create a Logic App
  8. You can try using the LogicApp.json in the code view, but you need to set up the Connectors and change the ARM resource tag to your Function App. Alternatively, you can recreate it manually, described below.
  9. Add Twitter connector, based on search, I did mine on "azure functions"
  10. Add new step, click on the carrot on the top of the card and choose "Functions". Find your Function App and "Sentiment" function
  11. Input should be {"text": " "}
  12. Add slack output (or email, or whatever)

The only odd thing is that if you return a JSON object (as I did in my sample code, you can't have logic apps "discover" it in the designer, so you need to do it manually. You can see in line 23, I add ['score'] after @body('sentiment'). We'll be adding swagger support sometime later on to make that smoother.

Steps

  1. Open the portal
  2. Show cognitive services
  3. Show the Logic App flow
  4. Show the Function Code
  5. Show the output in Slack

Links

var request = require('request');
var uuid = require('node-uuid');
/* Requires a Cognitive Services Text Analytics */
/* Be sure to install the request and node-uuid packages and add the "COG_URL" and "COG_KEY" App Settings before running */
module.exports = function(context, req) {
context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', req.originalUrl);
// Make a call out to Cognitive Services
if (req.body && req.body.text) {
var reqId = uuid.v4();
request.post({
url: process.env.COG_URL + "/sentiment",
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": process.env.COG_KEY
},
json: true,
body: {
"documents": [
{
"id": reqId,
"text": req.body.text
}
]
}
}, function(err, res, body) {
context.log("Response from Cog API (err, res, body)");
context.log(JSON.stringify(err, null, " "));
context.log(JSON.stringify(res, null, " "));
context.log(JSON.stringify(body, null, " "));
// Check to see if we succeeded.
if(err || res.statusCode != 200) {
context.log(err);
context.res = {
status: 500,
body: err
}
context.done();
return
}
context.res = {
// status: 200, /* Defaults to 200 */
// Send back the score we got from the Cog API
body: {
score: body.documents[0].score
}
};
context.done();
});
}
else {
// Bad request - Missing property on body
context.res = {
status: 400,
body: "Expected 'text' property on body contents"
};
context.done();
}
};
{
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2015-08-01-preview/workflowdefinition.json#",
"actions": {
"Post_Message": {
"conditions": [
{
"dependsOn": "sentiment"
}
],
"inputs": {
"host": {
"api": {
"runtimeUrl": "https://logic-apis-northcentralus.azure-apim.net/apim/slack"
},
"connection": {
"name": "@parameters('$connections')['slack']['connectionId']"
}
},
"method": "post",
"path": "/chat.postMessage",
"queries": {
"channel": "zzz_bot_channel",
"text": "@{triggerBody()['TweetedBy']} tweeted: \"@{triggerBody()['TweetText']}\" - Score of: @{body('sentiment')['score']}",
"username": "Twitter Bot"
}
},
"type": "ApiConnection"
},
"sentiment": {
"conditions": [],
"inputs": {
"body": {
"text": "@{triggerBody()['TweetText']}"
},
"function": {
"id": "< FUNCTION APP ARM RESOURCE TAG >"
}
},
"type": "Function"
}
},
"contentVersion": "1.0.0.0",
"outputs": {},
"parameters": {
"$connections": {
"defaultValue": {},
"type": "Object"
}
},
"triggers": {
"When_a_new_tweet_appears": {
"conditions": [],
"inputs": {
"host": {
"api": {
"runtimeUrl": "https://logic-apis-northcentralus.azure-apim.net/apim/twitter"
},
"connection": {
"name": "@parameters('$connections')['twitter']['connectionId']"
}
},
"method": "get",
"path": "/onnewtweet",
"queries": {
"searchQuery": "azure functions"
}
},
"recurrence": {
"frequency": "Minute",
"interval": 1
},
"splitOn": "@triggerBody()?.value",
"type": "ApiConnection"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment