summaryrefslogtreecommitdiff
path: root/lib/open_ai.ex
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--lib/open_ai.ex23
1 files changed, 15 insertions, 8 deletions
diff --git a/lib/open_ai.ex b/lib/open_ai.ex
index da54e3a..2b8783f 100644
--- a/lib/open_ai.ex
+++ b/lib/open_ai.ex
@@ -1,33 +1,40 @@
defmodule OpenAi do
require Logger
-
def post(path, data, options \\ []) do
config = Application.get_env(:nola, :openai, [])
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")}]
+
+ 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(30), recv_timeout: :timer.seconds(30)]
- Logger.debug("openai: post: #{url} #{inspect data}")
+ 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, %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, body: body}} ->
- Logger.error("OpenAI: HTTP #{code} #{inspect 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
-
end