Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Soporte para manejar multiples proyectos de Dialogflow #14

Merged
merged 1 commit into from
Dec 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ erl_crash.dump

*.env
*_credentials.json
*_info.json
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,33 +54,33 @@ mix deps.get
Obtiene el agente al que está asociado el project_id. [(📘)](https://dialogflow.com/docs/reference/api-v2/rest/v2/projects/getAgent)

```elixir
get()
get(project)
```

### Flowex.Service.Intents

Lista los de intents de un agente. [(📘)](https://dialogflow.com/docs/reference/api-v2/rest/v2/projects.agent.intents/list)

```elixir
list(language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED", pageSize \\ 100, token \\ nil)
list(project, language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED", pageSize \\ 100, token \\ nil)
```

Obtiene un intent buscando por id. [(📘)](https://dialogflow.com/docs/reference/api-v2/rest/v2/projects.agent.intents/get)

```elixir
get(id, languageCode \\ "es", intentView \\ "INTENT_VIEW_UNSPECIFIED")
get(project, id, languageCode \\ "es", intentView \\ "INTENT_VIEW_UNSPECIFIED")
```

Añade un frase de entrenamiento a un intent. [(📘)](https://dialogflow.com/docs/reference/api-v2/rest/v2/projects.agent.intents/patch)

```elixir
add_training_phrase(id, language \\ "es", text)
add_training_phrase(project, id, language \\ "es", text)
```

### Flowex.Service.Sessions

Procesa una consulta en lenguaje natural para detectar un intent con la respuesta apropiada [(📘)](https://dialogflow.com/docs/reference/api-v2/rest/v2/projects.agent.sessions/detectIntent)

```elixir
get()
detect_intent(project, text, session_id, languageCode \\ "es",)
```
6 changes: 2 additions & 4 deletions config/dev.exs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use Mix.Config

config :flowex, host: System.get_env("DIALOGFLOW_URL")
config :flowex, project_id: System.get_env("DIALOGFLOW_PROJECT_ID")
config :flowex, client_email: System.get_env("CLIENT_EMAIL")
config :flowex, projects_info: System.get_env("PROJECTS_INFO") |> File.read!

config :goth,
json: System.get_env("GOOGLE_CREDENTIALS") |> File.read!
config :goth, json: System.get_env("GOOGLE_CREDENTIALS") |> File.read!
6 changes: 2 additions & 4 deletions config/prod.exs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use Mix.Config

config :flowex, host: "${DIALOGFLOW_URL}"
config :flowex, project_id: "${DIALOGFLOW_PROJECT_ID}"
config :flowex, client_email: "${CLIENT_EMAIL}"
config :flowex, project_info: "${PROJECTS_INFO}"

config :goth,
json: "${GOOGLE_CREDENTIALS}" |> File.read!
config :goth, json: "${GOOGLE_CREDENTIALS}" |> File.read!
8 changes: 4 additions & 4 deletions config/test.exs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use Mix.Config

config :flowex, host: "api.dialogflow.com"
config :flowex, project_id: "LBot"
config :flowex, client_email: "client-access@lbot-170198.iam.gserviceaccount.com"
config :flowex, projects_info: "[\n{\n\"email\": \"client-access@lbot-8992.iam.gserviceaccount.com\"" <>
",\n\"id\":\"lbot-170198\"\n}\n]\n"

config :goth,
json: "{\n \"type\": \"test_service_account\",\n \"project_id\": "<>
json: "[{\n \"type\": \"test_service_account\",\n \"project_id\": "<>
"\"test_project\",\n \"private_key_id\": \"0000\",\n \"private_key\""<>
": \"-----BEGIN PRIVATE KEY-----\\ntestPrivateKey\\n-----END PRIVATE KEY-----\\n\""<>
",\n \"client_email\": \"resuelve-bot-api@test_project.test.com\",\n "<>
" \"client_id\": \"0000\",\n \"auth_uri\": \"fakeurl\",\n \"token_uri\":"<>
" \"fakeurl\",\n \"auth_provider_x509_cert_url\": \"fakeurl\",\n "<>
"\"client_x509_cert_url\": \"fakeurl\"\n}\n"
"\"client_x509_cert_url\": \"fakeurl\"\n}]\n"
31 changes: 20 additions & 11 deletions lib/flowex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ defmodule Flowex do

alias Goth.Token

def request(method, path, body) do
host = Application.get_env(:flowex, :host)
project_id = Application.get_env(:flowex, :project_id)
@spec request(String.t(), atom, String.t(), String.t()) :: tuple
def request(project, method, path, body) do
%{"id" => id, "email" => email} = project_info(project)

url = "#{host}/v2/projects/#{project_id}/agent/#{path}"
host = Application.get_env(:flowex, :host)
url = "#{host}/v2/projects/#{id}/agent/#{path}"

case HTTPoison.request(method, url, body, headers()) do
case HTTPoison.request(method, url, body, headers(email)) do
{:ok, %HTTPoison.Response{status_code: status, body: body}} when status in 200..299 ->
{:ok, Poison.decode!(body)}
{:ok, %HTTPoison.Response{status_code: status, body: body}} when status in 400..499 ->
Expand All @@ -23,15 +24,23 @@ defmodule Flowex do
end
end

# ---------------------------------------------------------------------------
# Obtiene el id y email de un proyecto de dialogflow.
# ---------------------------------------------------------------------------
@spec project_info(String.t) :: map
defp project_info(project_id) do
:flowex
|> Application.get_env(:projects_info)
|> Poison.decode!()
|> Enum.find(fn project -> project["id"] == project_id end)
end

# ---------------------------------------------------------------------------
# Headers de la petición.
# ---------------------------------------------------------------------------
@spec headers() :: list
defp headers() do
{:ok, token} = Token.for_scope({
Application.get_env(:flowex, :client_email),
"https://www.googleapis.com/auth/cloud-platform"
})
@spec headers(String.t()) :: list
defp headers(email) do
{:ok, token} = Token.for_scope({email, "https://www.googleapis.com/auth/cloud-platform"})

[
{"Authorization", "Bearer #{token.token}"},
Expand Down
10 changes: 5 additions & 5 deletions lib/flowex/service/agent.ex
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
defmodule Flowex.Service.Agent do
@moduledoc """
Helper para agent.
Helper para información del agente.
"""

alias Flowex

@doc """
Obtiene el agente al que está asociado el project_id.
Obtiene el agente al que está asociado el projecto.
"""
@spec get() :: tuple
def get do
Flowex.request(:get, "", "")
@spec get(Strint.t) :: tuple
def get(project) do
Flowex.request(project, :get, "", "")
end
end
36 changes: 17 additions & 19 deletions lib/flowex/service/intents.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@ defmodule Flowex.Service.Intents do
@doc """
Lista todos los intents de un agente por pageToken.
"""
@spec list(String.t, String.t, String.t | nil, list) :: tuple
def list(language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED",
token \\ nil, acc \\ []) do
case list_by_page(language, view, 100, token) do
@spec list(String.t, String.t, String.t, String.t | nil, list) :: tuple
def list(project, language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED", token \\ nil, acc \\ []) do
case list_by_page(project, language, view, 100, token) do
{:ok, %{"intents" => intents, "nextPageToken" => nextPageToken}} ->
list(language, view, nextPageToken, acc ++ intents)
list(project, language, view, nextPageToken, acc ++ intents)
{:ok, %{"intents" => intents}} ->
{:ok, acc ++ intents}
{:error, error} ->
Expand All @@ -24,34 +23,33 @@ defmodule Flowex.Service.Intents do
@doc """
Lista los de intents de un agente por pageToken y definiendo tamaño de pagina.
"""
@spec list_by_page(String.t, String.t, integer, String.t | nil) :: tuple
def list_by_page(language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED",
pageSize \\ 100, token \\ nil) do
@spec list_by_page(String.t, String.t, String.t, integer, String.t | nil) :: tuple
def list_by_page(project, language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED", pageSize \\ 100, token \\ nil) do
url =
"intents?languageCode=#{language}&intentView=#{view}&" <>
"pageSize=#{pageSize}&pageToken=#{token}"

Flowex.request(:get, url, "")
Flowex.request(project, :get, url, "")
end

@doc """
Obtiene un intent buscando por id.
"""
@spec get(String.t, String.t, String.t) :: tuple
def get(id, language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED") do
@spec get(String.t, String.t, String.t, String.t) :: tuple
def get(project, id, language \\ "es", view \\ "INTENT_VIEW_UNSPECIFIED") do
url = "intents/#{id}?languageCode=#{language}&intentView=#{view}"

Flowex.request(:get, url, "")
Flowex.request(project, :get, url, "")
end

@doc """
Añade un frase de entrenamiento a un intent.
"""
@spec add_training_phrase(String.t, String.t, String.t) :: tuple
def add_training_phrase(id, text, language \\ "es") do
@spec add_training_phrase(String.t, String.t, String.t, String.t) :: tuple
def add_training_phrase(project, id, text, language \\ "es") do
url = "intents/#{id}?languageCode=#{language}&intentView=INTENT_VIEW_FULL"

{:ok, intent} = get(id, language, "INTENT_VIEW_FULL")
{:ok, intent} = get(project, id, language, "INTENT_VIEW_FULL")

intent =
[%{
Expand All @@ -63,16 +61,16 @@ defmodule Flowex.Service.Intents do
|> (&Map.put(intent, "trainingPhrases", &1)).()
|> Poison.encode!

Flowex.request(:patch, url, intent)
Flowex.request(project, :patch, url, intent)
end

@doc """
Actualiza un intent view full.
"""
@spec update(String.t, map, String.t) :: tuple
def update(id, intent, language \\ "es") do
@spec update(String.t, String.t, map, String.t) :: tuple
def update(project, id, intent, language \\ "es") do
url = "intents/#{id}?languageCode=#{language}&intentView=INTENT_VIEW_FULL"

Flowex.request(:patch, url, Poison.encode!(intent))
Flowex.request(project, :patch, url, Poison.encode!(intent))
end
end
6 changes: 3 additions & 3 deletions lib/flowex/service/sessions.ex
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ defmodule Flowex.Service.Sessions do
Procesa una consulta en lenguaje natural para detectar un intent con la respuesta
apropiada.
"""
@spec detect_intent(String.t, String.t, String.t) :: tuple
def detect_intent(text, session_id, language \\ "es") do
@spec detect_intent(String.t, String.t, String.t, String.t) :: tuple
def detect_intent(project, text, session_id, language \\ "es") do
body =
%{
queryInput: %{
Expand All @@ -22,6 +22,6 @@ defmodule Flowex.Service.Sessions do
}
|> Poison.encode!

Flowex.request(:post, "sessions/#{session_id}:detectIntent", body)
Flowex.request(project, :post, "sessions/#{session_id}:detectIntent", body)
end
end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ defmodule Flowex.Mixfile do
[
{:credo, "~> 0.8", only: [:dev, :test]},
{:elixir_uuid, "~> 1.2" },
{:excoveralls, "~> 0.7", only: :test},
{:excoveralls, "~> 0.10", only: :test},
{:goth, "~> 0.9.0"},
{:httpoison, "~> 0.13"},
{:mock, "~> 0.3.0", only: :test},
Expand Down
15 changes: 8 additions & 7 deletions mix.lock
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
%{
"bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [:mix], [], "hexpm"},
"certifi": {:hex, :certifi, "2.3.1", "d0f424232390bf47d82da8478022301c561cf6445b5b5fb6a84d49a9e76d2639", [:rebar3], [{:parse_trans, "3.2.0", [hex: :parse_trans, repo: "hexpm", optional: false]}], "hexpm"},
"certifi": {:hex, :certifi, "2.4.2", "75424ff0f3baaccfd34b1214184b6ef616d89e420b258bb0a5ea7d7bc628f7f0", [:rebar3], [{:parse_trans, "~>3.3", [hex: :parse_trans, repo: "hexpm", optional: false]}], "hexpm"},
"credo": {:hex, :credo, "0.9.3", "76fa3e9e497ab282e0cf64b98a624aa11da702854c52c82db1bf24e54ab7c97a", [:mix], [{:bunt, "~> 0.2.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:poison, ">= 0.0.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
"elixir_uuid": {:hex, :elixir_uuid, "1.2.0", "ff26e938f95830b1db152cb6e594d711c10c02c6391236900ddd070a6b01271d", [:mix], [], "hexpm"},
"excoveralls": {:hex, :excoveralls, "0.8.2", "b941a08a1842d7aa629e0bbc969186a4cefdd035bad9fe15d43aaaaaeb8fae36", [:mix], [{:exjsx, ">= 3.0.0", [hex: :exjsx, repo: "hexpm", optional: false]}, {:hackney, ">= 0.12.0", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm"},
"excoveralls": {:hex, :excoveralls, "0.10.3", "b090a3fbcb3cfa136f0427d038c92a9051f840953ec11b40ee74d9d4eac04d1e", [:mix], [{:hackney, "~> 1.13", [hex: :hackney, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm"},
"exjsx": {:hex, :exjsx, "4.0.0", "60548841e0212df401e38e63c0078ec57b33e7ea49b032c796ccad8cde794b5c", [:mix], [{:jsx, "~> 2.8.0", [hex: :jsx, repo: "hexpm", optional: false]}], "hexpm"},
"goth": {:hex, :goth, "0.9.0", "92b30293623d8bd970693ec2aa497651e02542f6fb760d2eb49f30ff08346f59", [:mix], [{:httpoison, "~> 0.11 or ~> 1.0", [hex: :httpoison, repo: "hexpm", optional: false]}, {:json_web_token, "~> 0.2.10", [hex: :json_web_token, repo: "hexpm", optional: false]}, {:poison, "~> 2.1 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
"hackney": {:hex, :hackney, "1.12.1", "8bf2d0e11e722e533903fe126e14d6e7e94d9b7983ced595b75f532e04b7fdc7", [:rebar3], [{:certifi, "2.3.1", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "5.1.1", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "1.0.1", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "1.1.1", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm"},
"hackney": {:hex, :hackney, "1.14.3", "b5f6f5dcc4f1fba340762738759209e21914516df6be440d85772542d4a5e412", [:rebar3], [{:certifi, "2.4.2", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "6.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "1.0.1", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "1.1.4", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm"},
"httpoison": {:hex, :httpoison, "0.13.0", "bfaf44d9f133a6599886720f3937a7699466d23bb0cd7a88b6ba011f53c6f562", [:mix], [{:hackney, "~> 1.8", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm"},
"idna": {:hex, :idna, "5.1.1", "cbc3b2fa1645113267cc59c760bafa64b2ea0334635ef06dbac8801e42f7279c", [:rebar3], [{:unicode_util_compat, "0.3.1", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm"},
"idna": {:hex, :idna, "6.0.0", "689c46cbcdf3524c44d5f3dde8001f364cd7608a99556d8fbd8239a5798d4c10", [:rebar3], [{:unicode_util_compat, "0.4.1", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm"},
"jason": {:hex, :jason, "1.1.2", "b03dedea67a99223a2eaf9f1264ce37154564de899fd3d8b9a21b1a6fd64afe7", [:mix], [{:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm"},
"json_web_token": {:hex, :json_web_token, "0.2.10", "61041d56369422c5e3a770cf7d7bf27224b3c4c12d3a7d79b43a002df766db22", [:mix], [{:poison, "~> 3.1", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
"jsx": {:hex, :jsx, "2.8.3", "a05252d381885240744d955fbe3cf810504eb2567164824e19303ea59eef62cf", [:mix, :rebar3], [], "hexpm"},
"meck": {:hex, :meck, "0.8.9", "64c5c0bd8bcca3a180b44196265c8ed7594e16bcc845d0698ec6b4e577f48188", [:rebar3], [], "hexpm"},
"metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm"},
"mimerl": {:hex, :mimerl, "1.0.2", "993f9b0e084083405ed8252b99460c4f0563e41729ab42d9074fd5e52439be88", [:rebar3], [], "hexpm"},
"mock": {:hex, :mock, "0.3.1", "994f00150f79a0ea50dc9d86134cd9ebd0d177ad60bd04d1e46336cdfdb98ff9", [:mix], [{:meck, "~> 0.8.8", [hex: :meck, repo: "hexpm", optional: false]}], "hexpm"},
"parse_trans": {:hex, :parse_trans, "3.2.0", "2adfa4daf80c14dc36f522cf190eb5c4ee3e28008fc6394397c16f62a26258c2", [:rebar3], [], "hexpm"},
"parse_trans": {:hex, :parse_trans, "3.3.0", "09765507a3c7590a784615cfd421d101aec25098d50b89d7aa1d66646bc571c1", [:rebar3], [], "hexpm"},
"poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [:mix], [], "hexpm"},
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.1", "28a4d65b7f59893bc2c7de786dec1e1555bd742d336043fe644ae956c3497fbe", [:make, :rebar], [], "hexpm"},
"unicode_util_compat": {:hex, :unicode_util_compat, "0.3.1", "a1f612a7b512638634a603c8f401892afbf99b8ce93a45041f8aaca99cadb85e", [:rebar3], [], "hexpm"},
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.4", "f0eafff810d2041e93f915ef59899c923f4568f4585904d010387ed74988e77b", [:make, :mix, :rebar3], [], "hexpm"},
"unicode_util_compat": {:hex, :unicode_util_compat, "0.4.1", "d869e4c68901dd9531385bb0c8c40444ebf624e60b6962d95952775cac5e90cd", [:rebar3], [], "hexpm"},
}
2 changes: 1 addition & 1 deletion test/service/agent_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ defmodule Flowex.Service.AgentTest do
end]
}
]) do
assert Agent.get == {:ok, @agent}
assert Agent.get("lbot-170198") == {:ok, @agent}
end
end
end
6 changes: 3 additions & 3 deletions test/service/intents_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ defmodule Flowex.Service.IntentsTest do
end]
}
]) do
assert Intents.list == {:ok, @intents["intents"]}
assert Intents.list("lbot-170198") == {:ok, @intents["intents"]}
end
end

Expand All @@ -87,7 +87,7 @@ defmodule Flowex.Service.IntentsTest do
end]
}
]) do
assert Intents.get("5eec5344-8a09-40ba-8f46-1d2ed3f7b0df") == {:ok, @intent}
assert Intents.get("lbot-170198", "5eec5344-8a09-40ba-8f46-1d2ed3f7b0df") == {:ok, @intent}
end
end

Expand All @@ -107,7 +107,7 @@ defmodule Flowex.Service.IntentsTest do
end]
}
]) do
assert Intents.update("5eec5344-8a09-40ba-8f46-1d2ed3f7b0df",
assert Intents.update("lbot-170198", "5eec5344-8a09-40ba-8f46-1d2ed3f7b0df",
@intent_view_full) == {:ok, @intent_view_full}
end
end
Expand Down
2 changes: 1 addition & 1 deletion test/service/sessions_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ defmodule Flowex.Service.SessionsTest do
end]
}
]) do
assert Sessions.detect_intent("Hola", "1e8118272e2f69ea6ec98acbb71ab959") == {:ok, @query}
assert Sessions.detect_intent("lbot-170198", "Hola", "1e8118272e2f69ea6ec98acbb71ab959") == {:ok, @query}
end
end

Expand Down