1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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
|