witai_agent.rb 2.3 KB

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