Current section
Files
Jump to
Current section
Files
src/openrouter_client.erl
-module(openrouter_client).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([new/3, send/2]).
-export_type([client/0]).
-type client() :: {client, binary(), binary(), gleam@option:option(binary())}.
-file("/home/simon/projects/openrouter_client/src/openrouter_client.gleam", 18).
-spec new(binary(), binary(), gleam@option:option(binary())) -> client().
new(Api_key, Model, System_prompt) ->
{client, Api_key, Model, System_prompt}.
-file("/home/simon/projects/openrouter_client/src/openrouter_client.gleam", 49).
-spec openrouter_request_to_json_string(
binary(),
gleam@option:option(binary()),
binary()
) -> binary().
openrouter_request_to_json_string(Model, System_prompt, Prompt) ->
Messages = case System_prompt of
{some, System_prompt@1} ->
[[{<<"role"/utf8>>, gleam@json:string(<<"system"/utf8>>)},
{<<"content"/utf8>>, gleam@json:string(System_prompt@1)}]];
none ->
[]
end,
Messages@1 = begin
_pipe = Messages,
lists:append(
_pipe,
[[{<<"role"/utf8>>, gleam@json:string(<<"user"/utf8>>)},
{<<"content"/utf8>>, gleam@json:string(Prompt)}]]
)
end,
_pipe@1 = gleam@json:object(
[{<<"model"/utf8>>, gleam@json:string(Model)},
{<<"messages"/utf8>>,
gleam@json:array(Messages@1, fun gleam@json:object/1)}]
),
gleam@json:to_string(_pipe@1).
-file("/home/simon/projects/openrouter_client/src/openrouter_client.gleam", 22).
-spec send(client(), binary()) -> {ok,
openrouter_client@internal:openrouter_response()} |
{error, openrouter_client@internal:openrouter_error()}.
send(Client, Prompt) ->
gleam@result:'try'(
begin
_pipe = gleam@http@request:to(
<<"https://openrouter.ai/api/v1/chat/completions"/utf8>>
),
gleam@result:map_error(_pipe, fun(_) -> misc end)
end,
fun(Base_req) ->
Req = begin
_pipe@1 = Base_req,
_pipe@2 = gleam@http@request:set_body(
_pipe@1,
openrouter_request_to_json_string(
erlang:element(3, Client),
erlang:element(4, Client),
Prompt
)
),
_pipe@3 = gleam@http@request:set_method(_pipe@2, post),
_pipe@4 = gleam@http@request:set_header(
_pipe@3,
<<"content-type"/utf8>>,
<<"application/json"/utf8>>
),
gleam@http@request:set_header(
_pipe@4,
<<"Authorization"/utf8>>,
<<"Bearer "/utf8, (erlang:element(2, Client))/binary>>
)
end,
gleam@result:'try'(
begin
_pipe@5 = gleam@httpc:send(Req),
gleam@result:map_error(
_pipe@5,
fun(_) ->
{http_request_error,
<<"Could not make request to OpenRouter"/utf8>>}
end
)
end,
fun(Resp) ->
openrouter_client@internal:decode_openrouter_response(
erlang:element(4, Resp)
)
end
)
end
).