summaryrefslogtreecommitdiff
path: root/lib/open_ai.ex
diff options
context:
space:
mode:
Diffstat (limited to 'lib/open_ai.ex')
-rw-r--r--lib/open_ai.ex21
1 files changed, 17 insertions, 4 deletions
diff --git a/lib/open_ai.ex b/lib/open_ai.ex
index cc0de27..da54e3a 100644
--- a/lib/open_ai.ex
+++ b/lib/open_ai.ex
@@ -1,19 +1,32 @@
defmodule OpenAi do
+ require Logger
+
def post(path, data, options \\ []) do
config = Application.get_env(:nola, :openai, [])
- url = "https://api.openai.com#{path}"
+ base_url = Keyword.get(config, :base_url, "https://api.openai.com")
+ url = "#{base_url}#{path}"
headers = [{"user-agent", "internal private experiment bot, href@random.sh"},
{"content-type", "application/json"},
{"authorization", "Bearer " <> Keyword.get(config, :key, "unset-api-key")}]
- options = options ++ [timeout: :timer.seconds(180), recv_timeout: :timer.seconds(180)]
+ options = options ++ [timeout: :timer.seconds(30), recv_timeout: :timer.seconds(30)]
+ Logger.debug("openai: post: #{url} #{inspect data}")
with {:ok, json} <- Poison.encode(data),
{:ok, %HTTPoison.Response{status_code: 200, body: body}} <- HTTPoison.post(url, json, headers, options),
{:ok, data} <- Poison.decode(body) do
{:ok, data}
else
- {:ok, %HTTPoison.Response{status_code: code}} -> {:error, Plug.Conn.Status.reason_atom(code)}
- {:error, %HTTPoison.Error{reason: reason}} -> {:error, reason}
+ {:ok, %HTTPoison.Response{status_code: code, body: body}} ->
+ Logger.error("OpenAI: HTTP #{code} #{inspect body}")
+ status = Plug.Conn.Status.reason_atom(code)
+ case Poison.decode(body) do
+ {:ok, %{"error" => %{"message" => message, "code" => code}}} ->
+ {:error, {status, message}}
+ kek ->
+ {:error, status}
+ end
+ {:error, %HTTPoison.Error{reason: reason}} ->
+ {:error, reason}
end
end