Move api_key resolution to OpenAI module
This commit is contained in:
+6
-1
@@ -4,7 +4,7 @@ defmodule OpenAI do
|
||||
def gpt(completion) do
|
||||
{:ok, collector} = Agent.start_link(fn -> "" end)
|
||||
|
||||
API.gpt_stream(completion, fn data ->
|
||||
API.gpt_stream(completion, api_key(), fn data ->
|
||||
case get_in(data, ["choices", Access.at(0), "delta", "content"]) do
|
||||
nil -> :ok
|
||||
data -> Agent.update(collector, fn current -> current <> data end)
|
||||
@@ -15,4 +15,9 @@ defmodule OpenAI do
|
||||
Agent.stop(collector)
|
||||
{:ok, result}
|
||||
end
|
||||
|
||||
defp api_key do
|
||||
Application.get_env(:music_library, __MODULE__)
|
||||
|> Keyword.fetch!(:api_key)
|
||||
end
|
||||
end
|
||||
|
||||
+4
-9
@@ -1,6 +1,6 @@
|
||||
defmodule OpenAI.API do
|
||||
# Lifted from https://fly.io/phoenix-files/streaming-openai-responses/
|
||||
def gpt_stream(completion, cb) do
|
||||
def gpt_stream(completion, api_key, cb) do
|
||||
fun = fn request, finch_request, finch_name, finch_options ->
|
||||
fun = fn
|
||||
{:status, status}, response ->
|
||||
@@ -39,19 +39,19 @@ defmodule OpenAI.API do
|
||||
stream: true,
|
||||
temperature: completion.temperature
|
||||
},
|
||||
auth: {:bearer, api_key()},
|
||||
auth: {:bearer, api_key},
|
||||
finch_request: fun
|
||||
)
|
||||
end
|
||||
|
||||
def get_embeddings(text) do
|
||||
def get_embeddings(text, api_key) do
|
||||
resp =
|
||||
Req.post!("https://api.openai.com/v1/embeddings",
|
||||
json: %{
|
||||
input: text,
|
||||
model: "text-embedding-3-small"
|
||||
},
|
||||
auth: {:bearer, api_key()}
|
||||
auth: {:bearer, api_key}
|
||||
)
|
||||
|
||||
if resp.status == 200 do
|
||||
@@ -65,9 +65,4 @@ defmodule OpenAI.API do
|
||||
defp decode_body("", _), do: :ok
|
||||
defp decode_body("[DONE]", _), do: :ok
|
||||
defp decode_body(json, cb), do: cb.(JSON.decode!(json))
|
||||
|
||||
defp api_key do
|
||||
Application.get_env(:music_library, OpenAI)
|
||||
|> Keyword.fetch!(:api_key)
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user