Function Repository Resource:

CreateServiceConnectionPaclet

Source Notebook

Create a new service connection

Contributed by: Giulio Alessandrini

ResourceFunction["CreateServiceConnectionPaclet"][params]

creates a paclet to add a new service connection using params.

Details and Options

The parameters must be specified using an Association.
Required keys for params are:
"ServiceName"the name of the new connection
"RawRequests"the low-level requests to the API
Optional values for params include:
"ProcessedRequests"higher level requests
"ParameterMap"parameter renaming
"ParameterVerification"rules to validate parameters in processed requests
"ParameterProcessing"how to post-process the parameters in processed requests
"AsynchronousParameter"which raw parameter is used to trigger server-event streaming
"TermsURL"URL to the API ToS page
"KeyURL"URL to create/fetch an API key
Each raw request must include the following parameters:
"URL"the endpoint address
"HTTPSMethod"method to use for the HTTPS request
Additionally, raw requests can include the following parameters:
"Parameters"full list of endpoint parameters
"RequiredParameters"required parameters
"PathParameters"parameters used to define "URL"
"Headers"request headers
"ResultsFunction"function to parse the results
Each processed request must include the following parameters:
"RawRequest"function to perform the request
"Parameters"parameters given as an option list
Additionally, processed requests can include the following parameters:
"PreprocessingFunction"how to pre-process the parameters
"PostprocessingFunction"how to post-process the response
The default service name is $PublisherID<>"/"<>params["ServiceName"].
The paclet is created in the directory FileNameJoin[{$WolframDocumentsDirectory,"Paclets"}].
ResourceFunction["CreateServiceConnectionPaclet"] has the following options:
AuthenticationNoneAPI authentication scheme
OverwriteTargetFalsewhether to overwrite previously defined paclets

Examples

Basic Examples (4) 

Define a new service connection:

In[1]:=
$PublisherID = "giulioa";
In[2]:=
ResourceFunction["CreateServiceConnectionPaclet"][<|
  "ServiceName" -> "CatFactsAPI",
  "RawRequests" -> <|"CatFact" -> <|
      "URL" -> "https://catfact.ninja/fact", "HTTPSMethod" -> "GET"|>|>
  |>
 ]
Out[2]=

The service is ready to be used:

In[3]:=
MemberQ[$Services, $PublisherID <> "/CatFactsAPI"]
Out[3]=

Create a new connection:

In[4]:=
catfacts = ServiceConnect[$PublisherID <> "/CatFactsAPI"]
Out[4]=

Perform a request:

In[5]:=
catfacts["CatFact"]
Out[5]=

Applications (12) 

RandomUser (4) 

Create a connection specifying the request parameters:

In[6]:=
params = <|"ServiceName" -> "RandomUser"|>;
params["RawRequests"] = <|"User" -> {
     "URL" -> "https://randomuser.me/api",
     "HTTPSMethod" -> "GET",
     "Parameters" -> {"inc", "exc", "seed", "format", "results", "gender", "password", "nat", "page"}
     }
   |>;
In[7]:=
ResourceFunction["CreateServiceConnectionPaclet"][params]
Out[7]=

Connect:

In[8]:=
randomuser = ServiceConnect[$PublisherID <> "/RandomUser"]
Out[8]=

Make the request passing the parameter values:

In[9]:=
randomuser["User", <|"inc" -> {"name,gender,nat,email"}, "results" -> 3, "seed" -> 1234|>]
Out[9]=

Visualize the result:

In[10]:=
Dataset[%["results"]]
Out[10]=

OpenAI (8) 

Define a custom connection to the OpenAI API:

In[11]:=
params = <||>;
params["ServiceName"] = "MyOpenAI";

Specify how to pass the API key:

In[12]:=
params["AuthFunction"] = Function[
   key, <|"Headers" -> {"Authorization" -> "Bearer " <> key}|>];

Define a POST request:

In[13]:=
params["RawRequests"] = <||>;
params["RawRequests", "RawEmbedding"] = {
   		"URL"               -> "https://api.openai.com/v1/embeddings",
   		"HTTPSMethod"       -> "POST",
   		"Headers"           -> {"Content-Type" -> "application/json"},
   		"Parameters"        -> {"model", "input", "user"},
   		"RequiredParameters" -> {"model", "input"}
   	};

Define a processed request to parse the result automatically:

In[14]:=
params["ProcessedRequests"] = <||>;
params["ProcessedRequests", "TextEmbedding"] = <|
   "RawRequest" -> "RawEmbedding",
   	"Parameters" -> {
     		"input" -> None,
     		"model" -> "text-embedding-ada-002"
     	},
   "PostprocessingFunction" -> Function[response, Enclose[NumericArray[
       Confirm @ Query["data", 1, "embedding"] @ Confirm @response, "Real32"]]]
   |>;

Create the paclet:

In[15]:=
ResourceFunction["CreateServiceConnectionPaclet"][params, Authentication -> "APIKey"]
Out[15]=

Connect:

In[16]:=
openai = ServiceConnect[$PublisherID <> "/MyOpenAI"]
Out[16]=

User the API to compute a string embedding:

In[17]:=
Short /@ openai["RawEmbedding", <|"input" -> "hi there", "model" -> "text-embedding-ada-002"|>]
Out[17]=

Compare with the processed request:

In[18]:=
openai["TextEmbedding", <|"input" -> "hi there"|>]
Out[18]=

Requirements

Wolfram Language 14.0 (January 2024) or above

Version History

  • 1.0.0 – 08 May 2024

Related Resources

License Information