Current section
Files
Jump to
Current section
Files
src/gloq.erl
-module(gloq).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([default_groq_request/0, new_groq_request/0, with_key/2, with_user/2, with_context/2, with_model/2, send/1]).
-export_type([groq_request_builder/0]).
-type groq_request_builder() :: {groq_request_builder,
binary(),
binary(),
binary(),
binary()}.
-spec default_groq_request() -> groq_request_builder().
default_groq_request() ->
{groq_request_builder,
<<""/utf8>>,
<<"user"/utf8>>,
<<""/utf8>>,
<<"llama3-8b-8192"/utf8>>}.
-spec new_groq_request() -> groq_request_builder().
new_groq_request() ->
{groq_request_builder, <<""/utf8>>, <<""/utf8>>, <<""/utf8>>, <<""/utf8>>}.
-spec with_key(groq_request_builder(), binary()) -> groq_request_builder().
with_key(Builder, Key) ->
erlang:setelement(2, Builder, Key).
-spec with_user(groq_request_builder(), binary()) -> groq_request_builder().
with_user(Builder, User) ->
erlang:setelement(3, Builder, User).
-spec with_context(groq_request_builder(), binary()) -> groq_request_builder().
with_context(Builder, Context) ->
erlang:setelement(4, Builder, Context).
-spec with_model(groq_request_builder(), binary()) -> groq_request_builder().
with_model(Builder, Model) ->
erlang:setelement(5, Builder, Model).
-spec send(groq_request_builder()) -> binary().
send(Builder) ->
Body = gleam@json:object(
[{<<"messages"/utf8>>,
gleam@json:array(
[gleam@json:object(
[{<<"role"/utf8>>,
gleam@json:string(
erlang:element(3, Builder)
)},
{<<"content"/utf8>>,
gleam@json:string(
erlang:element(4, Builder)
)}]
)],
fun(X) -> X end
)},
{<<"model"/utf8>>, gleam@json:string(erlang:element(5, Builder))}]
),
Req = begin
_pipe = gleam@http@request:new(),
_pipe@1 = gleam@http@request:set_method(_pipe, post),
_pipe@2 = gleam@http@request:set_host(_pipe@1, <<"api.groq.com"/utf8>>),
_pipe@3 = gleam@http@request:set_path(
_pipe@2,
<<"/openai/v1/chat/completions"/utf8>>
),
_pipe@4 = gleam@http@request:set_header(
_pipe@3,
<<"Authorization"/utf8>>,
<<"Bearer "/utf8, (erlang:element(2, Builder))/binary>>
),
_pipe@5 = gleam@http@request:set_header(
_pipe@4,
<<"Content-Type"/utf8>>,
<<"application/json"/utf8>>
),
gleam@http@request:set_body(_pipe@5, gleam@json:to_string(Body))
end,
Res = gleam@hackney:send(Req),
case Res of
{ok, R} ->
erlang:element(4, R);
{error, _} ->
<<"Error, Request Failed"/utf8>>
end.