summaryrefslogtreecommitdiff
path: root/lib/open_ai.ex
blob: 2b8783fa3e44e32371bda89b3c2b61c2a5af8cb4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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")}
    ]

    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