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")}] 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, 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 end