witai_agent.rb 2.4 KB

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