witai_agent.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. module Agents
  2. class WitaiAgent < Agent
  3. cannot_be_scheduled!
  4. description <<-MD
  5. The `wit.ai` agent receives events, sends a text query to your `wit.ai` instance and generates outcome events.
  6. Fill in `Server Access Token` of your `wit.ai` instance. Use [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) to fill query field.
  7. `expected_receive_period_in_days` is the expected number of days by which agent should receive events. It helps in determining if the agent is working.
  8. MD
  9. event_description <<-MD
  10. Every event have `outcomes` key with your payload as value. Sample event:
  11. {"outcome" : [
  12. {"_text" : "set temperature to 34 degrees at 11 PM",
  13. "intent" : "get_temperature",
  14. "entities" : {
  15. "temperature" : [
  16. {
  17. "type" : "value",
  18. "value" : 34,
  19. "unit" : "degree"
  20. }],
  21. "datetime" : [
  22. {
  23. "grain" : "hour",
  24. "type" : "value",
  25. "value" : "2015-03-26T21:00:00.000-07:00"
  26. }]},
  27. "confidence" : 0.556
  28. }]}
  29. MD
  30. def default_options
  31. {
  32. 'server_access_token' => 'xxxxx',
  33. 'expected_receive_period_in_days' => 2,
  34. 'query' => '{{xxxx}}'
  35. }
  36. end
  37. def working?
  38. !recent_error_logs? && most_recent_event && event_created_within?(interpolated['expected_receive_period_in_days'])
  39. end
  40. def validate_options
  41. unless %w[server_access_token query expected_receive_period_in_days].all? { |field| options[field].present? }
  42. errors.add(:base, 'All fields are required')
  43. end
  44. end
  45. def receive(incoming_events)
  46. incoming_events.each do |event|
  47. interpolated_event = interpolated event
  48. response = HTTParty.get query_url(interpolated_event[:query]), headers
  49. create_event 'payload' => {
  50. 'outcomes' => JSON.parse(response.body)['outcomes']
  51. }
  52. end
  53. end
  54. private
  55. def api_endpoint
  56. 'https://api.wit.ai/message?v=20141022&q='
  57. end
  58. def query_url(query)
  59. api_endpoint + URI.encode(query)
  60. end
  61. def headers
  62. #oauth
  63. {:headers => {'Authorization' => 'Bearer ' + interpolated[:server_access_token]}}
  64. end
  65. end
  66. end