Custom Prompter Model
Integrate a prompter model into an LLM workflow
A prompter model is a type of language model specifically designed to craft instructions that guide the output of large language models (LLMs). It helps in prompt engineering, focusing on optimizing the responses of LLMs to prompts.
Let's demonstrate how you can create your own prompter model and connect it to an LLM in a workflow.
The initialization code used in the following examples is outlined in detail on the client installation page.
Create a Prompter Model
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
##########################################################################################
# In this section, we set the user authentication, app ID, model ID, and model type ID.
# Change these strings to run your own example.
#########################################################################################
USER_ID = 'YOUR_USER_ID_HERE'
# Your PAT (Personal Access Token) can be found in the Account's Security section
PAT = 'YOUR_PAT_HERE'
APP_ID = 'YOUR_APP_ID_HERE'
# Change these to create your own model
MODEL_ID = 'my-prompter-model'
MODEL_TYPE_ID = 'prompter'
##########################################################################
# YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
##########################################################################
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2
channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)
metadata = (('authorization', 'Key ' + PAT),)
userDataObject = resources_pb2.UserAppIDSet(user_id=USER_ID, app_id=APP_ID)
post_models_response = stub.PostModels(
service_pb2.PostModelsRequest(
user_app_id=userDataObject,
models=[
resources_pb2.Model(
id=MODEL_ID,
model_type_id=MODEL_TYPE_ID
)
]
),
metadata=metadata
)
if post_models_response.status.code != status_code_pb2.SUCCESS:
print(post_models_response.status)
raise Exception("Post models failed, status: " + post_models_response.status.description)
<!--index.html file-->
<script>
///////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, model ID, and model type ID.
// Change these strings to run your own example.
//////////////////////////////////////////////////////////////////////////////////////////
const USER_ID = 'YOUR_USER_ID_HERE';
// Your PAT (Personal Access Token) can be found in the Account's Security section
const PAT = 'YOUR_PAT_HERE';
const APP_ID = 'YOUR_APP_ID_HERE';
// Change these to create your own model
const MODEL_ID = 'my-prompter-model';
const MODEL_TYPE_ID = 'prompter';
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
const raw = JSON.stringify({
"user_app_id": {
"user_id": USER_ID,
"app_id": APP_ID
},
"model": {
"id": MODEL_ID,
"model_type_id": MODEL_TYPE_ID
}
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
fetch("https://api.clarifai.com/v2/models", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
</script>
//index.js file
////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, model ID, and model type ID.
// Change these strings to run your own example.
///////////////////////////////////////////////////////////////////////////////////////////
const USER_ID = 'YOUR_USER_ID_HERE';
// Your PAT (Personal Access Token) can be found in the Account's Security section
const PAT = 'YOUR_PAT_HERE';
const APP_ID = 'YOUR_APP_ID_HERE';
// Change these to create your own model
const MODEL_ID = 'my-prompter-model';
const MODEL_TYPE_ID = 'prompter';
/////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
/////////////////////////////////////////////////////////////////////////////
const { ClarifaiStub, grpc } = require("clarifai-nodejs-grpc");
const stub = ClarifaiStub.grpc();
// This will be used by every Clarifai endpoint call
const metadata = new grpc.Metadata();
metadata.set("authorization", "Key " + PAT);
stub.PostModels(
{
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID
},
models: [
{
id: MODEL_ID,
model_type_id: MODEL_TYPE_ID
}
]
},
metadata,
(err, response) => {
if (err) {
throw new Error(err);
}
if (response.status.code !== 10000) {
throw new Error("Post models failed, status: " + response.status.description);
}
}
);
package com.clarifai.example;
import com.clarifai.grpc.api.*;
import com.clarifai.channel.ClarifaiChannel;
import com.clarifai.credentials.ClarifaiCallCredentials;
import com.clarifai.grpc.api.status.StatusCode;
public class ClarifaiExample {
////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, model ID, and model type ID.
// Change these strings to run your own example.
///////////////////////////////////////////////////////////////////////////////////////////
static final String USER_ID = "YOUR_USER_ID_HERE";
//Your PAT (Personal Access Token) can be found in the portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
static final String APP_ID = "YOUR_APP_ID_HERE";
// Change these to create your own model
static final String MODEL_ID = "my-prompter-model";
static final String MODEL_TYPE_ID = "prompter";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
V2Grpc.V2BlockingStub stub = V2Grpc.newBlockingStub(ClarifaiChannel.INSTANCE.getGrpcChannel())
.withCallCredentials(new ClarifaiCallCredentials(PAT));
SingleModelResponse postModelsResponse = stub.postModels(
PostModelsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.addModels(
Model.newBuilder()
.setId(MODEL_ID)
.setModelTypeId(MODEL_TYPE_ID)
).build()
);
if (postModelsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post models failed, status: " + postModelsResponse.getStatus());
}
}
}
<?php
require __DIR__ . "/vendor/autoload.php";
/////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, model ID, and model type ID.
// Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////////////
$USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the Account's Security section
$PAT = "YOUR_PAT_HERE";
$APP_ID = "YOUR_APP_ID_HERE";
// Change these to create your own model
$MODEL_ID = "my-prompter-model";
$MODEL_TYPE_ID = "prompter";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
use Clarifai\ClarifaiClient;
use Clarifai\Api\Model;
use Clarifai\Api\PostModelsRequest;
use Clarifai\Api\Status\StatusCode;
use Clarifai\Api\UserAppIDSet;
$client = ClarifaiClient::grpc();
$metadata = ["Authorization" => ["Key " . $PAT]];
$userDataObject = new UserAppIDSet([
"user_id" => $USER_ID,
"app_id" => $APP_ID,
]);
// Let's make a RPC call to the Clarifai platform. It uses the opened gRPC client channel to communicate a
// request and then wait for the response
[$response, $status] = $client->PostModels(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostModelsRequest([
"user_app_id" => $userDataObject,
"models" => [
new Model([
"id" => $MODEL_ID,
"model_type_id" => $MODEL_TYPE_ID,
]),
],
]),
$metadata
)->wait();
// A response is returned and the first thing we do is check the status of it
// A successful response will have a status code of 0; otherwise, there is some error
if ($status->code !== 0) {
throw new Exception("Error: {$status->details}");
}
// In addition to the RPC response status, there is a Clarifai API status that reports if the operation was a success or failure
// (not just that the communication was successful)
if ($response->getStatus()->getCode() != StatusCode::SUCCESS) {
throw new Exception("Failure response: " . $response->getStatus()->getDescription() . " " . $response->getStatus()->getDetails());
}
?>
curl -X POST "https://api.clarifai.com/v2/users/YOUR_USER_ID_HERE/apps/YOUR_APP_ID_HERE/models" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"model": {
"id": "my-prompter-model",
"model_type_id": "prompter"
}
}'
Text Output Example
Predicted output for the model: `my-prompter-model`
Classify whether the sentiment of the given text is positive or negative I love your product very much
Predicted output for the model: `GPT-4`
The sentiment of the given text is positive.
Train a Prompter Model
When training a prompter model, you need to provide a prompt template, which serves as a pre-configured piece of text for instructing an LLM.
Note that your prompt template should include at least one instance of the placeholder {data.text.raw}
. When you input your text data at inference time, all occurrences of {data.text.raw}
within the template will be replaced with the provided text.
- Python
- JavaScript (REST)
- Java
- cURL
###############################################################################################
# In this section, we set the user authentication, app ID, model ID, and prompter details.
# Change these strings to run your own example.
###############################################################################################
USER_ID = "YOUR_USER_ID_HERE"
# Your PAT (Personal Access Token) can be found in the Account's Security section
PAT = "YOUR_PAT_HERE"
APP_ID = "YOUR_APP_ID_HERE"
# Change these to train your own model
MODEL_ID = "my-prompter-model"
PROMPTER_DESCRIPTION = "Positive or negative sentiment classifier prompter"
PROMPT_TEMPLATE = "Classify whether the sentiment of the given text is positive or negative {data.text.raw}"
##########################################################################
# YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
##########################################################################
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2
from google.protobuf.struct_pb2 import Struct
channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)
params = Struct()
params.update({
"prompt_template": PROMPT_TEMPLATE
})
metadata = (("authorization", "Key " + PAT),)
userDataObject = resources_pb2.UserAppIDSet(user_id=USER_ID, app_id=APP_ID)
post_model_versions = stub.PostModelVersions(
service_pb2.PostModelVersionsRequest(
user_app_id=userDataObject,
model_id=MODEL_ID,
description=PROMPTER_DESCRIPTION,
model_versions=[
resources_pb2.ModelVersion(
output_info=resources_pb2.OutputInfo(params=params)
)
],
),
metadata=metadata,
)
if post_model_versions.status.code != status_code_pb2.SUCCESS:
print(post_model_versions.status)
raise Exception("Post models versions failed, status: " + post_model_versions.status.description)
print(post_model_versions)
<!--index.html file-->
<script>
////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, model ID, and prompter details.
// Change these strings to run your own example.
//////////////////////////////////////////////////////////////////////////////////////////////
const USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the Account's Security section
const PAT = "YOUR_PAT_HERE";
const APP_ID = "YOUR_APP_ID_HERE";
// Change these to train your own model
const MODEL_ID = "my-prompter-model";
const PROMPTER_DESCRIPTION = "Positive or negative sentiment classifier prompter";
const PROMPT_TEMPLATE = "Classify whether the sentiment of the given text is positive or negative {data.text.raw}";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
const raw = JSON.stringify({
"user_app_id": {
"user_id": USER_ID,
"app_id": APP_ID
},
"description": PROMPTER_DESCRIPTION,
"model_versions": [{
"output_info": {
"params": {
"prompt_template": PROMPT_TEMPLATE
}
}
}]
});
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Key " + PAT
},
body: raw
};
fetch(`https://api.clarifai.com/v2/models/${MODEL_ID}/versions`, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log("error", error));
</script>
package com.clarifai.example;
import com.clarifai.grpc.api.*;
import com.clarifai.channel.ClarifaiChannel;
import com.clarifai.credentials.ClarifaiCallCredentials;
import com.clarifai.grpc.api.status.StatusCode;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
public class ClarifaiExample {
//////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, model ID, and prompter details.
// Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////////
static final String USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
static final String APP_ID = "YOUR_APP_ID_HERE";
// Change these to train your own model
static final String MODEL_ID = "my-prompter-model";
static final String PROMPTER_DESCRIPTION = "Positive or negative sentiment classifier prompter";
static final String PROMPT_TEMPLATE = "Classify whether the sentiment of the given text is positive or negative {data.text.raw}";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
V2Grpc.V2BlockingStub stub = V2Grpc.newBlockingStub(ClarifaiChannel.INSTANCE.getGrpcChannel())
.withCallCredentials(new ClarifaiCallCredentials(PAT));
Struct.Builder params = Struct.newBuilder()
.putFields("prompt_template", Value.newBuilder().setStringValue(PROMPT_TEMPLATE).build());
SingleModelResponse postModelVersionsResponse = stub.postModelVersions(
PostModelVersionsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.setModelId(MODEL_ID)
.setDescription(PROMPTER_DESCRIPTION)
.addModelVersions(ModelVersion.newBuilder()
.setOutputInfo(OutputInfo.newBuilder()
.setParams(params)
)
)
.build()
);
if (postModelVersionsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post model outputs failed, status: " + postModelVersionsResponse.getStatus());
}
}
}
curl -X POST "https://api.clarifai.com/v2/users/YOUR_USER_ID_HERE/apps/YOUR_APP_ID_HERE/models/my-prompter-model/versions" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"description": "Positive or negative sentiment classifier prompter",
"model_versions": [{
"output_info": {
"params": {
"prompt_template": "Classify whether the sentiment of the given text is positive or negative {data.text.raw}"
}
}
}]
}'
Add to a Workflow
After training your prompter model, you can now put it to work by integrating it into an LLM workflow and using it to accomplish various tasks.
Below is an example of how to connect a prompter model to an LLM like GPT-4 for text-to-text tasks.
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
########################################################################################
# In this section, we set the user authentication, app ID, and the details of the new
# custom workflow. Change these strings to run your own example.
########################################################################################
USER_ID = 'YOUR_USER_ID_HERE'
# Your PAT (Personal Access Token) can be found in the Account's Security section
PAT = 'YOUR_PAT_HERE'
APP_ID = 'YOUR_APP_ID_HERE'
# Change these to create your own custom workflow
WORKFLOW_ID = 'my-custom-prompter-workflow'
NODE_ID_1 = 'prompter-model'
PROMPTER_MODEL_ID = 'my-prompter-model'
PROMPTER_MODEL_USER_ID = 'YOUR_USER_ID_HERE'
PROMPTER_MODEL_APP_ID = 'my-custom-app'
PROMPTER_MODEL_VERSION_ID = 'e851fb99a3b14df788ce11accee45c19'
NODE_ID_2 = 'text-to-text'
LLM_MODEL_ID = 'GPT-4'
LLM_MODEL_USER_ID = 'openai'
LLM_MODEL_APP_ID = 'chat-completion'
LLM_MODEL_VERSION = '5d7a50b44aec4a01a9c492c5a5fcf387'
##########################################################################
# YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
##########################################################################
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2
channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)
metadata = (('authorization', 'Key ' + PAT),)
userDataObject = resources_pb2.UserAppIDSet(user_id=USER_ID, app_id=APP_ID) # The userDataObject is required when using a PAT
post_workflows_response = stub.PostWorkflows(
service_pb2.PostWorkflowsRequest(
user_app_id=userDataObject,
workflows=[
resources_pb2.Workflow(
id=WORKFLOW_ID,
nodes=[
resources_pb2.WorkflowNode(
id=NODE_ID_1,
model=resources_pb2.Model(
id=PROMPTER_MODEL_ID,
user_id=PROMPTER_MODEL_USER_ID,
app_id=PROMPTER_MODEL_APP_ID,
model_version=resources_pb2.ModelVersion(
id=PROMPTER_MODEL_VERSION_ID
)
)
),
resources_pb2.WorkflowNode(
id=NODE_ID_2,
model=resources_pb2.Model(
id=LLM_MODEL_ID,
user_id=LLM_MODEL_USER_ID,
app_id=LLM_MODEL_APP_ID,
model_version=resources_pb2.ModelVersion(
id=LLM_MODEL_VERSION
)
),
node_inputs=[
resources_pb2.NodeInput(node_id=NODE_ID_1)
]
),
]
)
]
),
metadata=metadata
)
if post_workflows_response.status.code != status_code_pb2.SUCCESS:
print(post_workflows_response.status)
raise Exception("Post workflows failed, status: " + post_workflows_response.status.description)
print(post_workflows_response)
<!--index.html file-->
<script>
//////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, and the details of the new
// custom workflow. Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////
const USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the Account's Security section
const PAT = "YOUR_PAT_HERE";
const APP_ID = "YOUR_APP_ID_HERE";
// Change these to create your own custom workflow
const WORKFLOW_ID = "my-custom-prompter-workflow";
const NODE_ID_1 = "prompter-model";
const PROMPTER_MODEL_ID = "my-prompter-model";
const PROMPTER_MODEL_USER_ID = "YOUR_USER_ID_HERE";
const PROMPTER_MODEL_APP_ID = "my-custom-app";
const PROMPTER_MODEL_VERSION_ID = "e851fb99a3b14df788ce11accee45c19";
const NODE_ID_2 = "text-to-text";
const LLM_MODEL_ID = "GPT-4";
const LLM_MODEL_USER_ID = "openai";
const LLM_MODEL_APP_ID = "chat-completion";
const LLM_MODEL_VERSION = "5d7a50b44aec4a01a9c492c5a5fcf387";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
const raw = JSON.stringify({
"user_app_id": {
"user_id": USER_ID,
"app_id": APP_ID
},
"workflows": [{
"id": WORKFLOW_ID,
"nodes": [
{
"id": NODE_ID_1,
"model": {
"id": PROMPTER_MODEL_ID,
"user_id": PROMPTER_MODEL_USER_ID,
"app_id": PROMPTER_MODEL_APP_ID,
"model_version": {
"id": PROMPTER_MODEL_VERSION_ID
}
}
},
{
"id": NODE_ID_2,
"model": {
"id": LLM_MODEL_ID,
"user_id": LLM_MODEL_USER_ID,
"app_id": LLM_MODEL_APP_ID,
"model_version": {
"id": LLM_MODEL_VERSION
}
},
"node_inputs": [
{
"node_id": NODE_ID_1
}
]
}
]
}]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
fetch(`https://api.clarifai.com/v2/workflows`, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
</script>
//index.js file
//////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, and the details of the new
// custom workflow. Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////
const USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the Account's Security section
const PAT = "YOUR_PAT_HERE";
const APP_ID = "YOUR_APP_ID_HERE";
// Change these to create your own custom workflow
const WORKFLOW_ID = "my-custom-prompter-workflow";
const NODE_ID_1 = "prompter-model";
const PROMPTER_MODEL_ID = "my-prompter-model";
const PROMPTER_MODEL_USER_ID = "YOUR_USER_ID_HERE";
const PROMPTER_MODEL_APP_ID = "my-custom-app";
const PROMPTER_MODEL_VERSION_ID = "e851fb99a3b14df788ce11accee45c19";
const NODE_ID_2 = "text-to-text";
const LLM_MODEL_ID = "GPT-4";
const LLM_MODEL_USER_ID = "openai";
const LLM_MODEL_APP_ID = "chat-completion";
const LLM_MODEL_VERSION = "5d7a50b44aec4a01a9c492c5a5fcf387";
/////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
/////////////////////////////////////////////////////////////////////////////
const { ClarifaiStub, grpc } = require("clarifai-nodejs-grpc");
const stub = ClarifaiStub.grpc();
// This will be used by every Clarifai endpoint call
const metadata = new grpc.Metadata();
metadata.set("authorization", "Key " + PAT);
stub.PostWorkflows(
{
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID
},
workflows: [
{
id: WORKFLOW_ID,
nodes: [
{
id: NODE_ID_1,
model: {
id: PROMPTER_MODEL_ID,
user_id: PROMPTER_MODEL_USER_ID,
app_id: PROMPTER_MODEL_APP_ID,
model_version: {
id: PROMPTER_MODEL_VERSION_ID
}
}
},
{
id: NODE_ID_2,
model: {
id: LLM_MODEL_ID,
user_id: LLM_MODEL_USER_ID,
app_id: LLM_MODEL_APP_ID,
model_version: {
id: LLM_MODEL_VERSION
}
},
node_inputs: [
{
node_id: NODE_ID_1
}
]
}
]
}
]
},
metadata,
(err, response) => {
if (err) {
throw new Error(err);
}
if (response.status.code !== 10000) {
throw new Error("Post workflows failed, status: " + response.status.description);
}
console.log(response);
}
);
package com.clarifai.example;
import com.clarifai.channel.ClarifaiChannel;
import com.clarifai.credentials.ClarifaiCallCredentials;
import com.clarifai.grpc.api.*;
import com.clarifai.grpc.api.status.StatusCode;
public class ClarifaiExample {
//////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, and the details of the new
// custom workflow. Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////
static final String USER_ID = "YOUR_USER_ID_HERE";
//Your PAT (Personal Access Token) can be found in the portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
static final String APP_ID = "YOUR_APP_ID_HERE";
// Change these to create your own custom workflow
static final String WORKFLOW_ID = "my-custom-prompter-workflow";
static final String NODE_ID_1 = "prompter-model";
static final String PROMPTER_MODEL_ID = "my-prompter-model";
static final String PROMPTER_MODEL_USER_ID = "YOUR_USER_ID_HERE";
static final String PROMPTER_MODEL_APP_ID = "my-custom-app";
static final String PROMPTER_MODEL_VERSION_ID = "e851fb99a3b14df788ce11accee45c19";
static final String NODE_ID_2 = "text-to-text";
static final String LLM_MODEL_ID = "GPT-4";
static final String LLM_MODEL_USER_ID = "openai";
static final String LLM_MODEL_APP_ID = "chat-completion";
static final String LLM_MODEL_VERSION = "5d7a50b44aec4a01a9c492c5a5fcf387";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
V2Grpc.V2BlockingStub stub = V2Grpc.newBlockingStub(ClarifaiChannel.INSTANCE.getGrpcChannel())
.withCallCredentials(new ClarifaiCallCredentials(PAT));
MultiWorkflowResponse postWorkflowsResponse = stub.postWorkflows(
PostWorkflowsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.addWorkflows(
Workflow.newBuilder()
.setId(WORKFLOW_ID)
.addNodes(
WorkflowNode.newBuilder()
.setId(NODE_ID_1)
.setModel(
Model.newBuilder()
.setId(PROMPTER_MODEL_ID)
.setUserId(PROMPTER_MODEL_USER_ID)
.setAppId(PROMPTER_MODEL_APP_ID)
.setModelVersion(ModelVersion.newBuilder().setId(PROMPTER_MODEL_VERSION_ID))
)
)
.addNodes(
WorkflowNode.newBuilder()
.setId(NODE_ID_2)
.setModel(
Model.newBuilder()
.setId(LLM_MODEL_ID)
.setUserId(LLM_MODEL_USER_ID)
.setAppId(LLM_MODEL_APP_ID)
.setModelVersion(ModelVersion.newBuilder().setId(LLM_MODEL_VERSION))
)
.addNodeInputs(NodeInput.newBuilder().setNodeId(NODE_ID_1))
)
).build()
);
if (postWorkflowsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post workflows failed, status: " + postWorkflowsResponse.getStatus());
}
}
}
<?php
require __DIR__ . "/vendor/autoload.php";
//////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, and the details of the new
// custom workflow. Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////
$USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the Account's Security section
$PAT = "YOUR_PAT_HERE";
$APP_ID = "YOUR_APP_ID_HERE";
// Change these to create your own custom workflow
$WORKFLOW_ID = "my-custom-prompter-workflow";
$NODE_ID_1 = "prompter-model";
$PROMPTER_MODEL_ID = "my-prompter-model";
$PROMPTER_MODEL_USER_ID = "YOUR_USER_ID_HERE";
$PROMPTER_MODEL_APP_ID = "my-custom-app";
$PROMPTER_MODEL_VERSION_ID = "e851fb99a3b14df788ce11accee45c19";
$NODE_ID_2 = "text-to-text";
$LLM_MODEL_ID = "GPT-4";
$LLM_MODEL_USER_ID = "openai";
$LLM_MODEL_APP_ID = "chat-completion";
$LLM_MODEL_VERSION = "5d7a50b44aec4a01a9c492c5a5fcf387";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
use Clarifai\ClarifaiClient;
use Clarifai\Api\PostWorkflowsRequest;
use Clarifai\Api\Workflow;
use Clarifai\Api\WorkflowNode;
use Clarifai\Api\NodeInput;
use Clarifai\Api\Model;
use Clarifai\Api\ModelVersion;
use Clarifai\Api\Status\StatusCode;
use Clarifai\Api\UserAppIDSet;
$client = ClarifaiClient::grpc();
$metadata = ["Authorization" => ["Key " . $PAT]];
$userDataObject = new UserAppIDSet([
"user_id" => $USER_ID,
"app_id" => $APP_ID
]);
// Let's make a RPC call to the Clarifai platform. It uses the opened gRPC client channel to communicate a
// request and then wait for the response
[$response, $status] = $client->PostWorkflows(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostWorkflowsRequest([
"user_app_id" => $userDataObject,
"workflows" => [
new Workflow([
"id"=> $WORKFLOW_ID,
"nodes" => [
new WorkflowNode([
"id" => $NODE_ID_1,
"model" => new Model([
"id" => $PROMPTER_MODEL_ID,
"user_id" => $PROMPTER_MODEL_USER_ID,
"app_id" => $PROMPTER_MODEL_APP_ID,
"model_version" => new ModelVersion([
"id" => $PROMPTER_MODEL_VERSION_ID
])
])
]),
new WorkflowNode([
"id" => $NODE_ID_2,
"model"=> new Model([
"id" => $LLM_MODEL_ID,
"user_id" => $LLM_MODEL_ID,
"app_id" => $LLM_MODEL_APP_ID,
"model_version" => new ModelVersion([
"id" => $LLM_MODEL_VERSION
])
]),
"node_inputs" => [
new NodeInput([
"node_id"=> $NODE_ID_1
])
]
])
]
])
]
]),
$metadata
)->wait();
// A response is returned and the first thing we do is check the status of it
// A successful response will have a status code of 0; otherwise, there is some error
if ($status->code !== 0) {
throw new Exception("Error: {$status->details}");
}
// In addition to the RPC response status, there is a Clarifai API status that reports if the operation was a success or failure
// (not just that the communication was successful)
if ($response->getStatus()->getCode() != StatusCode::SUCCESS) {
print $response->getStatus()->getDetails();
throw new Exception("Failure response: " . $response->getStatus()->getDescription());
}
?>
curl -X POST "https://api.clarifai.com/v2/users/YOUR_USER_ID_HERE/apps/YOUR_APP_ID_HERE/workflows" \
-H "Content-Type: application/json" \
-H "Authorization: Key YOUR_PAT_HERE" \
--data-raw '{
"workflows": [{
"id": "my-custom-prompter-workflow",
"nodes": [
{
"id": "prompter-model",
"model": {
"id": "my-prompter-model",
"user_id": "YOUR_USER_ID_HERE",
"app_id": "my-custom-app",
"model_version": {
"id": "e851fb99a3b14df788ce11accee45c19"
}
}
},
{
"id": "text-to-text",
"model": {
"id": "GPT-4",
"user_id": "openai",
"app_id": "chat-completion",
"model_version": {
"id": "5d7a50b44aec4a01a9c492c5a5fcf387"
}
},
"node_inputs": [
{
"node_id": "prompter-model"
}
]
}
]
}]
}'
Workflow Predict
After creating the workflow, let's now use it to perform a text sentiment prediction task.
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
######################################################################################################
# In this section, we set the user authentication, app ID, workflow ID, and the text
# we want as an input. Change these strings to run your own example.
######################################################################################################
USER_ID = 'YOUR_USER_ID_HERE'
# Your PAT (Personal Access Token) can be found in the Account's Security section
PAT = 'YOUR_PAT_HERE'
APP_ID = 'YOUR_APP_ID_HERE'
# Change these to make your own predictions
WORKFLOW_ID = "my-custom-prompter-workflow"
RAW_TEXT = "I love your product very much"
# To use a hosted text file, assign the URL variable
# TEXT_FILE_URL = "https://samples.clarifai.com/negative_sentence_12.txt"
# Or, to use a local text file, assign the location variable
# TEXT_FILE_LOCATION = "YOUR_TEXT_FILE_LOCATION_HERE"
############################################################################
# YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
############################################################################
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2
channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)
metadata = (("authorization", "Key " + PAT),)
userDataObject = resources_pb2.UserAppIDSet(user_id=USER_ID, app_id=APP_ID)
# To use a local text file, uncomment the following lines
# with open(TEXT_FILE_LOCATION, "rb") as f:
# file_bytes = f.read()
post_workflow_results_response = stub.PostWorkflowResults(
service_pb2.PostWorkflowResultsRequest(
user_app_id=userDataObject,
workflow_id=WORKFLOW_ID,
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(
text=resources_pb2.Text(
raw=RAW_TEXT
# url=TEXT_FILE_URL
# raw=file_bytes
)
)
)
],
),
metadata=metadata,
)
if post_workflow_results_response.status.code != status_code_pb2.SUCCESS:
print(post_workflow_results_response.status)
raise Exception("Post workflow results failed, status: " + post_workflow_results_response.status.description)
# We'll get one WorkflowResult for each input we used above. Because of one input, we have here one WorkflowResult
results = post_workflow_results_response.results[0]
# Each model we have in the workflow will produce one output.
for output in results.outputs:
model = output.model
print("Predicted output for the model: `%s`" % model.id)
print(output.data.text.raw)
# Uncomment this line to print the raw output
# print(results)
<!--index.html file-->
<script>
////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, workflow ID, and the text
// we want as an input. Change these strings to run your own example.
///////////////////////////////////////////////////////////////////////////////////////////////////
// Your PAT (Personal Access Token) can be found in the Account's Security section
const USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the Account's Security section
const PAT = "YOUR_PAT_HERE";
const APP_ID = "YOUR_APP_ID_HERE";
// Change these to make your own predictions
const WORKFLOW_ID = "my-custom-prompter-workflow";
const RAW_TEXT = "I love your product very much";
// To use a hosted text file, assign the URL variable
// const TEXT_FILE_URL = "https://samples.clarifai.com/negative_sentence_12.txt";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
const raw = JSON.stringify({
"user_app_id": {
"user_id": USER_ID,
"app_id": APP_ID
},
"inputs": [
{
"data": {
"text": {
"raw": RAW_TEXT
// "url": TEXT_FILE_URL
}
}
}
]
});
const requestOptions = {
method: "POST",
headers: {
"Accept": "application/json",
"Authorization": "Key " + PAT
},
body: raw
};
fetch(`https://api.clarifai.com/v2/workflows/${WORKFLOW_ID}/results`, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log("error", error));
</script>
//index.js file
//////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, workflow ID, and the text
// we want as an input. Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////////////////
const USER_ID = 'YOUR_USER_ID_HERE';
// Your PAT (Personal Access Token) can be found in the Account's Security section
const PAT = 'YOUR_PAT_HERE';
const APP_ID = 'YOUR_APP_ID_HERE';
// Change these to make your own predictions
const WORKFLOW_ID = "my-custom-prompter-workflow";
const RAW_TEXT = "I love your product very much";
// To use a hosted text file, assign the URL variable
// const TEXT_FILE_URL = "https://samples.clarifai.com/negative_sentence_12.txt"
// Or, to use a local text file, assign the location variable
// TEXT_FILE_LOCATION = "YOUR_TEXT_FILE_LOCATION_HERE"
/////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
/////////////////////////////////////////////////////////////////////////////
const { ClarifaiStub, grpc } = require("clarifai-nodejs-grpc");
const stub = ClarifaiStub.grpc();
// This will be used by every Clarifai endpoint call
const metadata = new grpc.Metadata();
metadata.set("authorization", "Key " + PAT);
// To use a local text file, uncomment the following lines
// const fs = require("fs");
// const fileBytes = fs.readFileSync(TEXT_FILE_LOCATION);
stub.PostWorkflowResults({
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID,
},
workflow_id: WORKFLOW_ID,
inputs: [{
data: {
text: {
raw: RAW_TEXT
// url: TEXT_FILE_URL,
// raw: fileBytes
}
}
}],
},
metadata,
(err, response) => {
if (err) {
throw new Error(err);
}
if (response.status.code !== 10000) {
throw new Error(
"Post workflow results failed, status: " + response.status.description
);
}
// We'll get one WorkflowResult for each input we used above. Because of one input, we have here
// one WorkflowResult
const results = response.results[0];
// Each model we have in the workflow will produce one output.
for (const output of results.outputs) {
const model = output.model;
console.log(`Predicted concepts for the model '${model.id}'`);
console.log(output.data.text.raw);
}
// Uncomment this line to print the raw output
// console.log(results);
}
);
package com.clarifai.example;
import com.clarifai.channel.ClarifaiChannel;
import com.clarifai.credentials.ClarifaiCallCredentials;
import com.clarifai.grpc.api.*;
import com.clarifai.grpc.api.status.StatusCode;
import com.google.protobuf.ByteString;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class ClarifaiExample {
/////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, app ID, workflow ID, and the text
// we want as an input. Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////////////////
static final String USER_ID = "YOUR_USER_ID_HERE";
//Your PAT (Personal Access Token) can be found in the portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
static final String APP_ID = "YOUR_APP_ID_HERE";
// Change these to make your own predictions
static final String WORKFLOW_ID = "my-custom-prompter-workflow";
static final String RAW_TEXT = "I love your product very much";
// To use a hosted text file, assign the URL variable
// static final String TEXT_FILE_URL = "https://samples.clarifai.com/negative_sentence_12.txt";
// Or, to use a local text file, assign the location variable
// static final String TEXT_FILE_LOCATION = "YOUR_TEXT_FILE_LOCATION_HERE";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException {
V2Grpc.V2BlockingStub stub = V2Grpc.newBlockingStub(ClarifaiChannel.INSTANCE.getGrpcChannel())
.withCallCredentials(new ClarifaiCallCredentials(PAT));
PostWorkflowResultsResponse postWorkflowResultsResponse = stub.postWorkflowResults(
PostWorkflowResultsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.setWorkflowId(WORKFLOW_ID)
.addInputs(
Input.newBuilder().setData(
Data.newBuilder().setText(
Text.newBuilder().setRaw(RAW_TEXT)
// Text.newBuilder().setUrl(TEXT_FILE_URL)
// Text.newBuilder().setRawBytes(ByteString.copyFrom(Files.readAllBytes(
// new File(TEXT_FILE_LOCATION).toPath()
//)))
)
)
)
.build()
);
if (postWorkflowResultsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post workflow results failed, status: " + postWorkflowResultsResponse.getStatus());
}
// We'll get one WorkflowResult for each input we used above. Because of one input, we have here
// one WorkflowResult
WorkflowResult results = postWorkflowResultsResponse.getResults(0);
// Each model we have in the workflow will produce its output
for (Output output : results.getOutputsList()) {
Model model = output.getModel();
System.out.println("Predicted concepts for the model '" + model.getId() + "'");
System.out.println(output.getData().getText().getRaw());
}
// Uncomment this line to print the raw output
// System.out.println(results);
}
}
<?php
require __DIR__ . "/vendor/autoload.php";
/////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, workflow ID, and the text
// we want as an input. Change these strings to run your own example.
/////////////////////////////////////////////////////////////////////////////////////////////////////
$USER_ID = "YOUR_USER_ID_HERE";
// Your PAT (Personal Access Token) can be found in the Account's Security section
$PAT = "YOUR_PAT_HERE";
$APP_ID = "YOUR_APP_ID_HERE";
// Change these to make your own predictions
$WORKFLOW_ID = "my-custom-prompter-workflow";
$RAW_TEXT = "I love your product very much";
// To use a hosted text file, assign the URL variable
// $TEXT_FILE_URL = "https://samples.clarifai.com/negative_sentence_12.txt";
// Or, to use a local text file, assign the location variable
// $TEXT_FILE_LOCATION = "YOUR_TEXT_FILE_LOCATION_HERE";
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
use Clarifai\ClarifaiClient;
use Clarifai\Api\Data;
use Clarifai\Api\Text;
use Clarifai\Api\Input;
use Clarifai\Api\PostWorkflowResultsRequest;
use Clarifai\Api\Status\StatusCode;
use Clarifai\Api\UserAppIDSet;
$client = ClarifaiClient::grpc();
$metadata = ["Authorization" => ["Key " . $PAT]];
$userDataObject = new UserAppIDSet([
"user_id" => $USER_ID,
"app_id" => $APP_ID,
]);
// To use a local text file, uncomment the following lines
// $textData = file_get_contents($TEXT_FILE_LOCATION);
// Let's make a RPC call to the Clarifai platform. It uses the opened gRPC client channel to communicate a
// request and then wait for the response
[$response, $status] = $client
->PostWorkflowResults(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostWorkflowResultsRequest([
"user_app_id" => $userDataObject,
"workflow_id" => $WORKFLOW_ID,
"inputs" => [
new Input([
// The Input object wraps the Data object in order to meet the API specification
"data" => new Data([
// The Data object is constructed around the Image object. It offers a container that has additional image independent
// metadata. In this particular use case, no other metadata is needed to be specified
"text" => new Text([
// In the Clarifai platform, a text is defined by a special Text object
"raw" => $RAW_TEXT
// "url" => $TEXT_FILE_URL
// "raw" => $textData
]),
]),
]),
],
]),
$metadata
)
->wait();
// A response is returned and the first thing we do is check the status of it
// A successful response will have a status code of 0; otherwise, there is some error
if ($status->code !== 0) {
throw new Exception("Error: {$status->details}");
}
// In addition to the RPC response status, there is a Clarifai API status that reports if the operation was a success or failure
// (not just that the communication was successful)
if ($response->getStatus()->getCode() != StatusCode::SUCCESS) {
throw new Exception(
"Failure response: " .
$response->getStatus()->getDescription() .
" " .
$response->getStatus()->getDetails()
);
}
// We'll get one WorkflowResult for each input we used above. Because of one input, we have here one WorkflowResult
$results = $response->getResults()[0];
// Each model we have in the workflow will produce one output
foreach ($results->getOutputs() as $output) {
$model = $output->getModel();
echo "Predicted concepts for the model '{$model->getId()}'" . "\n";
$convertDataToJSONString = $output->getData()->getText()->getRaw();
echo $convertDataToJSONString . "\n";
}
// Uncomment this line to print the raw output
// print_r($results);
?>
curl -X POST "https://api.clarifai.com/v2/users/YOUR_USER_ID_HERE/apps/YOUR_APP_ID_HERE/workflows/my-custom-prompter-workflow/results" \
-H "authorization: Key YOUR_PAT_HERE" \
-H "content-type: application/json" \
-d '{
"inputs": [
{
"data": {
"text": {
"raw": "I love your product very much"
}
}
}
]
}'
Text Output Example
Predicted output for the model: `my-prompter-model`
Classify whether the sentiment of the given text is positive or negative I love your product very much
Predicted output for the model: `GPT-4`
The sentiment of the given text is positive.
As you can see on the output above, the response contains the predictions of each model in the workflow. The prompt text starts with the earlier provided template text, and the {data.text.raw}
placeholder is substituted with the provided input text. That is what is used as a prompt for the GPT-4 model.
And the model correctly predicts the sentiment of the provided input text.