Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can pass custom headers to config. Allow using alternative endpoints configuration #53

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion lib/openai/client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ defmodule OpenAI.Client do
alias OpenAI.{Config, Stream}
use HTTPoison.Base

def process_url(url), do: Config.api_url() <> url
def process_url(url), do: Config.api_url(url)

def process_response_body(body) do
try do
Expand Down Expand Up @@ -60,12 +60,18 @@ defmodule OpenAI.Client do
end
end

def add_custom_headers(headers, config) do
custom_headers = config.custom_headers || Config.custom_headers()
headers ++ custom_headers
end

def request_headers(config) do
[
bearer(config),
{"Content-type", "application/json"}
]
|> add_organization_header(config)
|> add_custom_headers(config)
end

def bearer(config), do: {"Authorization", "Bearer #{config.api_key || Config.api_key()}"}
Expand All @@ -79,6 +85,16 @@ defmodule OpenAI.Client do
end

def api_post(url, params \\ [], config) do
IO.inspect config, label: "API_POST_CONFIG"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably remove this inspect


url = case config.api_url do
nil ->
url

_ ->
config.api_url <> url
end

body =
params
|> Enum.into(%{})
Expand Down
16 changes: 14 additions & 2 deletions lib/openai/config.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ defmodule OpenAI.Config do
defstruct api_key: nil,
organization_key: nil,
http_options: nil,
api_url: nil
api_url: nil,
custom_headers: nil

use GenServer

Expand All @@ -16,7 +17,8 @@ defmodule OpenAI.Config do
@config_keys [
:api_key,
:organization_key,
:http_options
:http_options,
:api_url
]

def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
Expand All @@ -38,9 +40,19 @@ defmodule OpenAI.Config do
# API Url
def api_url, do: get_config_value(:api_url, @openai_url)

def api_url(url) do
uri = URI.parse(url)
case uri.host do
nil -> api_url() <> url
_ -> url
end
end

# HTTP Options
def http_options, do: get_config_value(:http_options, [])

def custom_headers, do: get_config_value(:custom_headers, [])

defp get_config_value(key, default \\ nil) do
value =
:openai
Expand Down