summaryrefslogblamecommitdiff
path: root/lib/open_ai.ex
blob: cc0de2742c53d1927a30f82a6a62d4080df9f727 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13


                                        
                                                    








                                                                                                                 
        
                                                                                                   
                                                                    



       
defmodule OpenAi do

  def post(path, data, options \\ []) do
    config = Application.get_env(:nola, :openai, [])
    url = "https://api.openai.com#{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)]
    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}
    end
  end

end