Text
Make predictions on text inputs
To get predictions for a given text input, you need to supply the text along with the specific model from which you wish to receive predictions. You can supply the text via a publicly accessible URL, a local text file, or in its raw format.
The file size of each text input should be less than 20MB.
You need to specify your choice of model for prediction by utilizing the MODEL_ID
parameter.
Most of our models now have new versions that support inference hyperparameters like temperature, top_k, etc. You can learn how to configure them here.
The initialization code used in the following examples is outlined in detail on the client installation page.
Text Classification
Input: Text
Output: Concepts
Text classification is the process of categorizing text documents into predefined categories based on their content. This task is typically accomplished using machine learning models trained on labeled datasets, where each document is associated with a specific category.
These models learn patterns and features in the text data during training, enabling them to classify new, unseen documents into the relevant categories effectively.
Predict via URL
Below is an example of how you would make predictions on passages of text hosted on the web from the multilingual-uncased-sentiment
model.
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
######################################################################################################
# In this section, we set the user authentication, user and app ID, model details, and the URL of
# 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
PAT = 'YOUR_PAT_HERE'
# Specify the correct user_id/app_id pairings
# Since you're making inferences outside your app's scope
USER_ID = 'nlptownres'
APP_ID = 'text-classification'
# Change these to whatever model and text URL you want to use
MODEL_ID = 'multilingual-uncased-sentiment'
MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd'
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
############################################################################
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_model_outputs_response = stub.PostModelOutputs(
service_pb2.PostModelOutputsRequest(
user_app_id=userDataObject, # The userDataObject is created in the overview and is required when using a PAT
model_id=MODEL_ID,
version_id=MODEL_VERSION_ID, # This is optional. Defaults to the latest model version
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(
text=resources_pb2.Text(
url=TEXT_FILE_URL
)
)
)
]
),
metadata=metadata
)
if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
print(post_model_outputs_response.status)
raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description)
# Since we have one input, one output will exist here
output = post_model_outputs_response.outputs[0]
print("Predicted concepts:")
for concept in output.data.concepts:
print("%s %.2f" % (concept.name, concept.value))
# Uncomment this line to print the raw output
#print(output)
<!--index.html file-->
<script>
////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the URL
// of 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'nlptownres';
const APP_ID = 'text-classification';
// Change these to whatever model and text URL you want to use
const MODEL_ID = 'multilingual-uncased-sentiment';
const MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
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": {
"url": TEXT_FILE_URL
}
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
// NOTE: MODEL_VERSION_ID is optional, you can also call prediction with the MODEL_ID only
// https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/outputs
// this will default to the latest version_id
fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/versions/" + MODEL_VERSION_ID + "/outputs", 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, user and app ID, model details, and the URL
// of 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'nlptownres';
const APP_ID = 'text-classification';
// Change these to whatever model and text URL you want to use
const MODEL_ID = 'multilingual-uncased-sentiment';
const MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
const TEXT_URL = 'https://samples.clarifai.com/negative_sentence_12.txt';
///////////////////////////////////////////////////////////////////////////////////
// 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.PostModelOutputs(
{
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID
},
model_id: MODEL_ID,
version_id: MODEL_VERSION_ID, // This is optional. Defaults to the latest model version.
inputs: [
{ data: { text: { url: TEXT_URL, allow_duplicate_url: true } } }
]
},
metadata,
(err, response) => {
if (err) {
throw new Error(err);
}
if (response.status.code !== 10000) {
throw new Error("Post model outputs failed, status: " + response.status.description);
}
// Since we have one input, one output will exist here.
const output = response.outputs[0];
console.log("Predicted concepts:");
for (const concept of output.data.concepts) {
console.log(concept.name + " " + concept.value);
}
}
);
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, user and app ID, model details, and the URL
// of 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 portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
static final String USER_ID = "nlptownres";
static final String APP_ID = "text-classification";
// Change these to whatever model and text URL you want to use
static final String MODEL_ID = "multilingual-uncased-sentiment";
static final String MODEL_VERSION_ID = "29d5fef0229a4936a607380d7ef775dd";
static final String TEXT_URL = "https://samples.clarifai.com/negative_sentence_12.txt";
///////////////////////////////////////////////////////////////////////////////////
// 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));
MultiOutputResponse postModelOutputsResponse = stub.postModelOutputs(
PostModelOutputsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.setModelId(MODEL_ID)
.setVersionId(MODEL_VERSION_ID) // This is optional. Defaults to the latest model version
.addInputs(
Input.newBuilder().setData(
Data.newBuilder().setText(
Text.newBuilder().setUrl(TEXT_URL)
)
)
)
.build()
);
if (postModelOutputsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post model outputs failed, status: " + postModelOutputsResponse.getStatus());
}
// Since we have one input, one output will exist here
Output output = postModelOutputsResponse.getOutputs(0);
System.out.println("Predicted concepts:");
for (Concept concept: output.getData().getConceptsList()) {
System.out.printf("%s %.2f%n", concept.getName(), concept.getValue());
}
}
}
<?php
require __DIR__ . '/vendor/autoload.php';
////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the URL
// of 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
$PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
$USER_ID = 'nlptownres';
$APP_ID = 'text-classification';
// Change these to whatever model and text URL you want to use
$MODEL_ID = 'multilingual-uncased-sentiment';
$MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
$TEXT_URL = 'https://samples.clarifai.com/negative_sentence_12.txt';
///////////////////////////////////////////////////////////////////////////////////
// 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\PostModelOutputsRequest;
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->PostModelOutputs(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostModelOutputsRequest([
'user_app_id' => $userDataObject,
'model_id' => $MODEL_ID,
'version_id' => $MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
'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 Text object. It offers a container that has additional text 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
'url' => $TEXT_URL
])
])
])
]
]),
$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());
}
// The output of a successful call can be used in many ways. In this example, we loop through all of the predicted concepts and print them out along with
// their numerical prediction value (confidence)
echo "Predicted concepts: </br>";
foreach ($response->getOutputs()[0]->getData()->getConcepts() as $concept) {
echo $concept->getName() . ": " . number_format($concept->getValue(), 2) . "</br>";
}
?>
curl -X POST "https://api.clarifai.com/v2/users/nlptownres/apps/text-classification/models/multilingual-uncased-sentiment/versions/29d5fef0229a4936a607380d7ef775dd/outputs" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"inputs": [
{
"data": {
"text": {
"url": "https://samples.clarifai.com/negative_sentence_12.txt"
}
}
}
]
}'
Text Output Example
Predicted concepts:
3-stars 0.25
2-stars 0.23
1-star 0.20
4-stars 0.17
5-stars 0.14
Raw Output Example
id: "479d7bb7e0e4415da8a265ceb10d4c7c"
status {
code: SUCCESS
description: "Ok"
}
created_at {
seconds: 1701798270
nanos: 281180166
}
model {
id: "multilingual-uncased-sentiment"
name: "multilingual-uncased-sentiment"
created_at {
seconds: 1656469244
nanos: 44961000
}
app_id: "text-classification"
model_version {
id: "29d5fef0229a4936a607380d7ef775dd"
created_at {
seconds: 1656469244
nanos: 60443000
}
status {
code: MODEL_TRAINED
description: "Model is trained and ready"
}
visibility {
gettable: PUBLIC
}
app_id: "text-classification"
user_id: "nlptownres"
metadata {
fields {
key: "Model version logs zipped"
value {
string_value: "https://s3.amazonaws.com/clarifai-temp/prod/29d5fef0229a4936a607380d7ef775dd.zip"
}
}
}
}
user_id: "nlptownres"
model_type_id: "text-classifier"
visibility {
gettable: PUBLIC
}
modified_at {
seconds: 1661364520
nanos: 417454000
}
task: "text-classification"
workflow_recommended {
}
}
input {
id: "b188010be5b84bafa330092327f4f4c0"
data {
text {
url: "https://samples.clarifai.com/negative_sentence_12.txt"
}
}
}
data {
concepts {
id: "3-stars"
name: "3-stars"
value: 0.2539905309677124
app_id: "text-classification"
}
concepts {
id: "2-stars"
name: "2-stars"
value: 0.23382391035556793
app_id: "text-classification"
}
concepts {
id: "1-star"
name: "1-star"
value: 0.20093071460723877
app_id: "text-classification"
}
concepts {
id: "4-stars"
name: "4-stars"
value: 0.17351166903972626
app_id: "text-classification"
}
concepts {
id: "5-stars"
name: "5-stars"
value: 0.13774323463439941
app_id: "text-classification"
}
}
Predict via Local Files
Below is an example of how you would provide text inputs via local text files and receive predictions from the multilingual-uncased-sentiment
model.
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
#######################################################################################################
# In this section, we set the user authentication, user and app ID, model details, and the location
# of 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
PAT = 'YOUR_PAT_HERE'
# Specify the correct user_id/app_id pairings
# Since you're making inferences outside your app's scope
USER_ID = 'nlptownres'
APP_ID = 'text-classification'
# Change these to whatever model and text input you want to use
MODEL_ID = 'multilingual-uncased-sentiment'
MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd'
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)
with open(TEXT_FILE_LOCATION, "rb") as f:
file_bytes = f.read()
post_model_outputs_response = stub.PostModelOutputs(
service_pb2.PostModelOutputsRequest(
user_app_id=userDataObject, # The userDataObject is created in the overview and is required when using a PAT
model_id=MODEL_ID,
version_id=MODEL_VERSION_ID, # This is optional. Defaults to the latest model version
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(
text=resources_pb2.Text(
raw=file_bytes
)
)
)
]
),
metadata=metadata
)
if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
print(post_model_outputs_response.status)
raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description)
# Since we have one input, one output will exist here.
output = post_model_outputs_response.outputs[0]
print("Predicted concepts:")
for concept in output.data.concepts:
print("%s %.2f" % (concept.name, concept.value))
# Uncomment this line to print the raw output
#print(output)
<!--index.html file-->
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the location
// of 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'nlptownres';
const APP_ID = 'text-classification';
// Change these to whatever model and text input you want to use
const MODEL_ID = 'multilingual-uncased-sentiment';
const MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
const TEXT_FILE_BYTES = 'YOUR_TEXT_FILE_BYTES_HERE';
///////////////////////////////////////////////////////////////////////////////////
// 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": TEXT_FILE_BYTES
}
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
// NOTE: MODEL_VERSION_ID is optional, you can also call prediction with the MODEL_ID only
// https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/outputs
// this will default to the latest version_id
fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/versions/" + MODEL_VERSION_ID + "/outputs", 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, user and app ID, model details, and the location
// of 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'nlptownres';
const APP_ID = 'text-classification';
// Change these to whatever model and text input you want to use
const MODEL_ID = 'multilingual-uncased-sentiment';
const MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
const 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);
const fs = require("fs");
const fileBytes = fs.readFileSync(TEXT_FILE_LOCATION);
stub.PostModelOutputs(
{
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID
},
model_id: MODEL_ID,
version_id: MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
inputs: [
{ data: { text: { raw: fileBytes } } }
]
},
metadata,
(err, response) => {
if (err) {
throw new Error(err);
}
if (response.status.code !== 10000) {
throw new Error("Post model outputs failed, status: " + response.status.description);
}
// Since we have one input, one output will exist here
const output = response.outputs[0];
console.log("Predicted concepts:");
for (const concept of output.data.concepts) {
console.log(concept.name + " " + concept.value);
}
}
);
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.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, user and app ID, model details, and the location
// of 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 portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
static final String USER_ID = "nlptownres";
static final String APP_ID = "text-classification";
// Change these to whatever model and text input you want to use
static final String MODEL_ID = "multilingual-uncased-sentiment";
static final String MODEL_VERSION_ID = "29d5fef0229a4936a607380d7ef775dd";
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));
MultiOutputResponse postModelOutputsResponse = stub.postModelOutputs(
PostModelOutputsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.setModelId(MODEL_ID)
.setVersionId(MODEL_VERSION_ID) // This is optional. Defaults to the latest model version
.addInputs(
Input.newBuilder().setData(
Data.newBuilder().setText(
Text.newBuilder()
.setRawBytes(ByteString.copyFrom(Files.readAllBytes(
new File(TEXT_FILE_LOCATION).toPath()
)))
)
)
)
.build()
);
if (postModelOutputsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post model outputs failed, status: " + postModelOutputsResponse.getStatus());
}
// Since we have one input, one output will exist here
Output output = postModelOutputsResponse.getOutputs(0);
System.out.println("Predicted concepts:");
for (Concept concept: output.getData().getConceptsList()) {
System.out.printf("%s %.2f%n", concept.getName(), concept.getValue());
}
}
}
<?php
require __DIR__ . '/vendor/autoload.php';
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the location
// of 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
$PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
$USER_ID = 'nlptownres';
$APP_ID = 'text-classification';
// Change these to whatever model and text URL you want to use
$MODEL_ID = 'multilingual-uncased-sentiment';
$MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
$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\PostModelOutputsRequest;
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
]);
$textData = file_get_contents($TEXT_FILE_LOCATION); // Get the text bytes data from the 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->PostModelOutputs(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostModelOutputsRequest([
'user_app_id' => $userDataObject,
'model_id' => $MODEL_ID,
'version_id' => $MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
'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 Text object. It offers a container that has additional text 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' => $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());
}
// The output of a successful call can be used in many ways. In this example, we loop through all of the predicted concepts and print them out along with
// their numerical prediction value (confidence)
echo "Predicted concepts: </br>";
foreach ($response->getOutputs()[0]->getData()->getConcepts() as $concept) {
echo $concept->getName() . ": " . number_format($concept->getValue(), 2) . "</br>";
}
?>
# Smaller files (195 KB or less)
curl -X POST "https://api.clarifai.com/v2/users/nlptownres/apps/text-classification/models/multilingual-uncased-sentiment/versions/29d5fef0229a4936a607380d7ef775dd/outputs" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"inputs": [
{
"data": {
"text": {
"raw": "YOUR_TEXT_FILE_BYTES_HERE"
}
}
}
]
}'
Predict via Raw Text
Below is an example of how you would provide raw text inputs and receive predictions from the multilingual-uncased-sentiment
model.
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
#########################################################################################################
# In this section, we set the user authentication, user and app ID, model details, and the raw 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
PAT = 'YOUR_PAT_HERE'
# Specify the correct user_id/app_id pairings
# Since you're making inferences outside your app's scope
USER_ID = 'nlptownres'
APP_ID = 'text-classification'
# Change these to whatever model and raw text you want to use
MODEL_ID = 'multilingual-uncased-sentiment'
MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd'
RAW_TEXT = 'I love your product very much'
############################################################################
# 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_model_outputs_response = stub.PostModelOutputs(
service_pb2.PostModelOutputsRequest(
user_app_id=userDataObject, # The userDataObject is created in the overview and is required when using a PAT
model_id=MODEL_ID,
version_id=MODEL_VERSION_ID, # This is optional. Defaults to the latest model version
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(
text=resources_pb2.Text(
raw=RAW_TEXT
)
)
)
]
),
metadata=metadata
)
if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
print(post_model_outputs_response.status)
raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description)
# Since we have one input, one output will exist here
output = post_model_outputs_response.outputs[0]
print("Predicted concepts:")
for concept in output.data.concepts:
print("%s %.2f" % (concept.name, concept.value))
# Uncomment this line to print the raw output
#print(output)
<!--index.html file-->
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the raw
// 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'nlptownres';
const APP_ID = 'text-classification';
// Change these to whatever model and raw text you want to use
const MODEL_ID = 'multilingual-uncased-sentiment';
const MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
const RAW_TEXT = 'I love your product very much';
///////////////////////////////////////////////////////////////////////////////////
// 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
}
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
// NOTE: MODEL_VERSION_ID is optional, you can also call prediction with the MODEL_ID only
// https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/outputs
// this will default to the latest version_id
fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/versions/" + MODEL_VERSION_ID + "/outputs", 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, user and app ID, model details, and the raw
// 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'nlptownres';
const APP_ID = 'text-classification';
// Change these to whatever model and raw text you want to use
const MODEL_ID = 'multilingual-uncased-sentiment';
const MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
const RAW_TEXT = 'I love your product very much';
///////////////////////////////////////////////////////////////////////////////////
// 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.PostModelOutputs(
{
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID
},
model_id: MODEL_ID,
version_id: MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
inputs: [
{ data: { text: { raw: RAW_TEXT } } }
]
},
metadata,
(err, response) => {
if (err) {
throw new Error(err);
}
if (response.status.code !== 10000) {
throw new Error("Post model outputs failed, status: " + response.status.description);
}
// Since we have one input, one output will exist here
const output = response.outputs[0];
console.log("Predicted concepts:");
for (const concept of output.data.concepts) {
console.log(concept.name + " " + concept.value);
}
}
);
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, user and app ID, model details, and the raw
// text we want as an input. Change these strings to run your own example.
///////////////////////////////////////////////////////////////////////////////////////////////////
//Your PAT (Personal Access Token) can be found in the portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
static final String USER_ID = "nlptownres";
static final String APP_ID = "text-classification";
// Change these to whatever model and raw text you want to use
static final String MODEL_ID = "multilingual-uncased-sentiment";
static final String MODEL_VERSION_ID = "29d5fef0229a4936a607380d7ef775dd";
static final String RAW_TEXT = "I love your product very much";
///////////////////////////////////////////////////////////////////////////////////
// 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));
MultiOutputResponse postModelOutputsResponse = stub.postModelOutputs(
PostModelOutputsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.setModelId(MODEL_ID)
.setVersionId(MODEL_VERSION_ID) // This is optional. Defaults to the latest model version
.addInputs(
Input.newBuilder().setData(
Data.newBuilder().setText(
Text.newBuilder().setRaw(RAW_TEXT)
)
)
)
.build()
);
if (postModelOutputsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post model outputs failed, status: " + postModelOutputsResponse.getStatus());
}
// Since we have one input, one output will exist here
Output output = postModelOutputsResponse.getOutputs(0);
System.out.println("Predicted concepts:");
for (Concept concept: output.getData().getConceptsList()) {
System.out.printf("%s %.2f%n", concept.getName(), concept.getValue());
}
}
}
<?php
require __DIR__ . '/vendor/autoload.php';
/////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the raw
// 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
$PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
$USER_ID = 'nlptownres';
$APP_ID = 'text-classification';
// Change these to whatever model and raw text you want to use
$MODEL_ID = 'multilingual-uncased-sentiment';
$MODEL_VERSION_ID = '29d5fef0229a4936a607380d7ef775dd';
$RAW_TEXT = 'I love your product very much';
///////////////////////////////////////////////////////////////////////////////////
// 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\PostModelOutputsRequest;
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->PostModelOutputs(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostModelOutputsRequest([
'user_app_id' => $userDataObject,
'model_id' => $MODEL_ID,
'version_id' => $MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
'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 Text object. It offers a container that has additional text 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
])
])
])
]
]),
$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());
}
// The output of a successful call can be used in many ways. In this example, we loop through all of the predicted concepts and print them out along with
// their numerical prediction value (confidence)
echo "Predicted concepts: </br>";
foreach ($response->getOutputs()[0]->getData()->getConcepts() as $concept) {
echo $concept->getName() . ": " . number_format($concept->getValue(), 2) . "</br>";
}
?>
curl -X POST "https://api.clarifai.com/v2/users/nlptownres/apps/text-classification/models/multilingual-uncased-sentiment/versions/29d5fef0229a4936a607380d7ef775dd/outputs" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"inputs": [
{
"data": {
"text": {
"raw": "I love your product very much"
}
}
}
]
}'
Text-to-Image Generation
Input: Text
Output: Images
Text-to-image generation involves creating visual images based on textual descriptions. In this field, machine learning models are trained to establish a meaningful connection between textual descriptions and their corresponding visual representations.
Then, when given a textual input, these models can generate images that accurately reflect the content described in the text.
Below is an example of how you would perform text-to-image generation using the Stable Diffusion XL model.
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
#################################################################################################################
# In this section, we set the user authentication, user and app ID, model details, and the prompt text we want
# to provide 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
PAT = 'YOUR_PAT_HERE'
# Specify the correct user_id/app_id pairings
# Since you're making inferences outside your app's scope
USER_ID = 'stability-ai'
APP_ID = 'stable-diffusion-2'
# Change these to whatever model and text URL you want to use
MODEL_ID = 'stable-diffusion-xl'
MODEL_VERSION_ID = '0c919cc1edfc455dbc96207753f178d7'
RAW_TEXT = 'A penguin watching the sunset.'
# 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_model_outputs_response = stub.PostModelOutputs(
service_pb2.PostModelOutputsRequest(
user_app_id=userDataObject, # The userDataObject is created in the overview and is required when using a PAT
model_id=MODEL_ID,
version_id=MODEL_VERSION_ID, # This is optional. Defaults to the latest model version
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_model_outputs_response.status.code != status_code_pb2.SUCCESS:
print(post_model_outputs_response.status)
raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description)
# Since we have one input, one output will exist here
output = post_model_outputs_response.outputs[0].data.image.base64
image_filename = f"gen-image.jpg"
with open(image_filename, 'wb') as f:
f.write(output)
<!--index.html file-->
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the prompt text we want
// to provide 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'stability-ai';
const APP_ID = 'stable-diffusion-2';
// Change these to whatever model and text you want to use
const MODEL_ID = 'stable-diffusion-xl';
const MODEL_VERSION_ID = '0c919cc1edfc455dbc96207753f178d7';
const RAW_TEXT = 'A penguin watching the sunset.';
// 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({
"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/users/${USER_ID}/apps/${APP_ID}/models/${MODEL_ID}/versions/${MODEL_VERSION_ID}/outputs`, requestOptions)
.then(response => response.json())
.then(result => {
const imageBase64 = result.outputs[0].data.image.base64;
// Create an anchor element for downloading the image
const downloadLink = document.createElement('a');
downloadLink.href = `data:image/jpeg;base64,${imageBase64}`;
downloadLink.download = 'gen-image.jpg';
// Trigger a click event on the link to prompt the download
downloadLink.click();
})
.catch(error => console.log('error', error));
</script>
//index.js file
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the prompt text we want
// to provide 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'stability-ai';
const APP_ID = 'stable-diffusion-2';
// Change these to whatever model and text you want to use
const MODEL_ID = 'stable-diffusion-xl';
const MODEL_VERSION_ID = '0c919cc1edfc455dbc96207753f178d7';
const RAW_TEXT = 'A penguin watching the sunset.';
// 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.PostModelOutputs(
{
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID
},
model_id: MODEL_ID,
version_id: MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
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 models failed, status: " + response.status.description);
}
// Since we have one input, one output will exist here.
const output = response.outputs[0].data.image.base64;
const fs = require('fs');
const imageFilename = 'gen-image.jpg';
fs.writeFileSync(imageFilename, Buffer.from(output, 'base64'));
console.log(`Image saved as ${imageFilename}`);
}
);
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.ByteString;
import java.io.FileOutputStream;
import java.io.IOException;
// import java.io.File; // Uncomment to use a local text file
// import java.nio.file.Files; // Uncomment to use a local text file
public class ClarifaiExample {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the prompt text we want
// to provide as an input. Change these strings to run your own example.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Your PAT (Personal Access Token) can be found in the portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
static final String USER_ID = "stability-ai";
static final String APP_ID = "stable-diffusion-2";
// Change these to whatever model you want to use
static final String MODEL_ID = "stable-diffusion-xl";
static final String MODEL_VERSION_ID = "0c919cc1edfc455dbc96207753f178d7";
static final String RAW_TEXT = "A penguin watching the sunset.";
// 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) {
V2Grpc.V2BlockingStub stub = V2Grpc.newBlockingStub(ClarifaiChannel.INSTANCE.getGrpcChannel())
.withCallCredentials(new ClarifaiCallCredentials(PAT));
MultiOutputResponse postModelOutputsResponse = stub.postModelOutputs(
PostModelOutputsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.setModelId(MODEL_ID)
.setVersionId(MODEL_VERSION_ID) // This is optional. Defaults to the latest model version.
.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 (postModelOutputsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post model outputs failed, status: " + postModelOutputsResponse.getStatus());
}
// Extract the base64-encoded image data
ByteString imageData = postModelOutputsResponse.getOutputs(0).getData().getImage().getBase64();
// Save the image to a file
try {
FileOutputStream outputStream = new FileOutputStream("gen-image.jpg");
outputStream.write(imageData.toByteArray());
outputStream.close();
} catch (IOException e) {
System.err.println("Error writing image to file: " + e.getMessage());
System.exit(1);
}
}
}
<?php
require __DIR__ . '/vendor/autoload.php';
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the prompt text we want
// to provide 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
$PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
$USER_ID = 'stability-ai';
$APP_ID = 'stable-diffusion-2';
// Change these to whatever model and image URL you want to use
$MODEL_ID = 'stable-diffusion-xl';
$MODEL_VERSION_ID = '0c919cc1edfc455dbc96207753f178d7';
$RAW_TEXT = 'A penguin watching the sunset.';
# 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\PostModelOutputsRequest;
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
]);
//$textData = file_get_contents($TEXT_FILE_LOCATION); // Get the text bytes data from the 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->PostModelOutputs(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostModelOutputsRequest([
'user_app_id' => $userDataObject,
'model_id' => $MODEL_ID,
'version_id' => $MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
'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 Text object. It offers a container that has additional text 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());
}
// Save the output image
$output = $response->getOutputs()[0]->getData()->getImage()->getBase64();
$imageFilename = "gen-image.jpg";
file_put_contents($imageFilename, base64_decode($output));
?>
curl -X POST "https://api.clarifai.com/v2/users/stability-ai/apps/stable-diffusion-2/models/stable-diffusion-xl/versions/0c919cc1edfc455dbc96207753f178d7/outputs" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"inputs": [
{
"data": {
"text": {
"raw": "A penguin watching the sunset."
}
}
}
]
}'
Here is a generated output example:
Text-to-Speech Generation
Input: Text
Output: Audio
Text-to-speech (TTS) generation involves converting written text into spoken words. A machine learning model is used to synthesize human-like speech from input text, allowing a computer or device to "speak" the provided content.
Below is an example of how you would perform text-to-speech generation using the Speech-synthesis model.
In this example, we've used the params.update()
method to fine-tune various inference parameters that allow us to customize the behavior of the Speech-synthesis model. You can check the various inference parameters you can configure on the model's description page on the Clarifai portal.
- Python
- JavaScript (REST)
- NodeJS
- Java
- PHP
- cURL
#################################################################################################################
# In this section, we set the user authentication, user and app ID, model details, and the text we want
# to provide 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
PAT = "YOUR_PAT_HERE"
# Specify the correct user_id/app_id pairings
# Since you're making inferences outside your app's scope
USER_ID = "eleven-labs"
APP_ID = "audio-generation"
# Change these to whatever model and text URL you want to use
MODEL_ID = "speech-synthesis"
MODEL_VERSION_ID = "f588d92c044d4487a38c8f3d7a3b0eb2"
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
from google.protobuf.struct_pb2 import Struct
channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)
params = Struct()
params.update(
{
"model_id": "eleven_multilingual_v1",
"voice_id": "pNInz6obpgDQGcFmaJgB",
"stability": 0.4,
"similarity_boost": 0.7,
}
)
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_model_outputs_response = stub.PostModelOutputs(
service_pb2.PostModelOutputsRequest(
user_app_id=userDataObject, # The userDataObject is created in the overview and is required when using a PAT
model_id=MODEL_ID,
version_id=MODEL_VERSION_ID, # This is optional. Defaults to the latest model version
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(
text=resources_pb2.Text(
raw=RAW_TEXT
# url=TEXT_FILE_URL
# raw=file_bytes
)
)
)
],
model=resources_pb2.Model(
model_version=resources_pb2.ModelVersion(
output_info=resources_pb2.OutputInfo(params=params)
)
),
),
metadata=metadata,
)
if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
print(post_model_outputs_response.status)
raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description )
# Uncomment this line to print the full Response JSON
# print(post_model_outputs_response)
# Since we have one input, one output will exist here
output = post_model_outputs_response.outputs[0].data.audio.base64
audio_filename = f"audio_file.wav"
with open(audio_filename, "wb") as f:
f.write(output)
<!--index.html file-->
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the text we want
// to provide 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 PAT = 'YOUR_PAT_HERE';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'eleven-labs';
const APP_ID = 'audio-generation';
// Change these to whatever model and text you want to use
const MODEL_ID = 'speech-synthesis';
const MODEL_VERSION_ID = 'f588d92c044d4487a38c8f3d7a3b0eb2';
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({
"inputs": [
{
"data": {
"text": {
"raw": RAW_TEXT
// "url": TEXT_FILE_URL
}
}
}
],
"model": {
"model_version": {
"output_info": {
"params": {
"model_id": "eleven_multilingual_v1",
"voice_id": "EXAVITQu4vr4xnSDxMaL",
"similarity_boost": 0,
"stability": 0.5,
}
}
}
}
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
fetch(`https://api.clarifai.com/v2/users/${USER_ID}/apps/${APP_ID}/models/${MODEL_ID}/versions/${MODEL_VERSION_ID}/outputs`, requestOptions)
.then(response => response.json())
.then(result => {
const audioBase64 = result.outputs[0].data.audio.base64;
// Create an anchor element for downloading the audio
const downloadLink = document.createElement('a');
downloadLink.href = `data:audio/wav;base64,${audioBase64}`;
downloadLink.download = 'audio_file.wav';
// Trigger a click event on the link to prompt the download
downloadLink.click();
})
.catch(error => console.log('error', error));
</script>
//index.js file
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the text we want
// to provide 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 PAT = "YOUR_PAT_HERE";
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = "eleven-labs";
const APP_ID = "audio-generation";
// Change these to whatever model and text you want to use
const MODEL_ID = "speech-synthesis";
const MODEL_VERSION_ID = "f588d92c044d4487a38c8f3d7a3b0eb2";
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.PostModelOutputs(
{
user_app_id: {
"user_id": USER_ID,
"app_id": APP_ID
},
model_id: MODEL_ID,
version_id: MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
inputs: [
{
"data": {
"text": {
"raw": RAW_TEXT
// url: TEXT_FILE_URL
// raw: fileBytes
}
}
}
],
"model": {
"model_version": {
"output_info": {
"params": {
"model_id": "eleven_multilingual_v1",
"voice_id": "EXAVITQu4vr4xnSDxMaL",
"similarity_boost": 0,
"stability": 0.5,
}
}
}
}
},
metadata,
(err, response) => {
if (err) {
throw new Error(err);
}
if (response.status.code !== 10000) {
throw new Error("Post models failed, status: " + response.status.description);
}
// Since we have one input, one output will exist here.
const output = response.outputs[0].data.audio.base64;
const fs = require("fs");
const audioFilename = "audio_file.wav";
fs.writeFileSync(audioFilename, Buffer.from(output, 'base64'));
console.log(`Image saved as ${audioFilename}`);
}
);
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 java.io.FileOutputStream;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
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, user and app ID, model details, and the text we want
// to provide as an input. Change these strings to run your own example.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Your PAT (Personal Access Token) can be found in the portal under Authentication
static final String PAT = "YOUR_PAT_HERE";
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
static final String USER_ID = "eleven-labs";
static final String APP_ID = "audio-generation";
// Change these to whatever model you want to use
static final String MODEL_ID = "speech-synthesis";
static final String MODEL_VERSION_ID = "f588d92c044d4487a38c8f3d7a3b0eb2";
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));
Struct.Builder params = Struct.newBuilder()
.putFields("model_id", Value.newBuilder().setStringValue("eleven_multilingual_v1").build())
.putFields("voice_id", Value.newBuilder().setStringValue("pNInz6obpgDQGcFmaJgB").build())
.putFields("stability", Value.newBuilder().setNumberValue(0.4).build())
.putFields("similarity_boost", Value.newBuilder().setNumberValue(.7).build());
MultiOutputResponse postModelOutputsResponse = stub.postModelOutputs(
PostModelOutputsRequest.newBuilder()
.setUserAppId(UserAppIDSet.newBuilder().setUserId(USER_ID).setAppId(APP_ID))
.setModelId(MODEL_ID)
.setVersionId(MODEL_VERSION_ID) // This is optional. Defaults to the latest model version.
.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()
// )))
)
)
)
.setModel(Model.newBuilder()
.setModelVersion(ModelVersion.newBuilder()
.setOutputInfo(OutputInfo.newBuilder().setParams(params))
)
)
.build()
);
if (postModelOutputsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
throw new RuntimeException("Post model outputs failed, status: " + postModelOutputsResponse.getStatus());
}
// Extract the base64-encoded audio data
ByteString audioData = postModelOutputsResponse.getOutputs(0).getData().getAudio().getBase64();
// Save the audio to a file
try {
FileOutputStream outputStream = new FileOutputStream("audio_file.wav");
outputStream.write(audioData.toByteArray());
outputStream.close();
} catch (IOException e) {
System.err.println("Error writing image to file: " + e.getMessage());
System.exit(1);
}
}
}
<?php
require __DIR__ . "/vendor/autoload.php";
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// In this section, we set the user authentication, user and app ID, model details, and the text we want
// to provide 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
$PAT = "YOUR_PAT_HERE";
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
$USER_ID = "eleven-labs";
$APP_ID = "audio-generation";
// Change these to whatever model and image URL you want to use
$MODEL_ID = "speech-synthesis";
$MODEL_VERSION_ID = "f588d92c044d4487a38c8f3d7a3b0eb2";
$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\Model;
use Clarifai\Api\ModelVersion;
use Clarifai\Api\OutputInfo;
use Clarifai\Api\PostModelOutputsRequest;
use Clarifai\Api\Status\StatusCode;
use Clarifai\Api\UserAppIDSet;
use Google\Protobuf\Struct;
$client = ClarifaiClient::grpc();
$metadata = ["Authorization" => ["Key " . $PAT]];
$userDataObject = new UserAppIDSet([
"user_id" => $USER_ID,
"app_id" => $APP_ID,
]);
// create Struct instance
$params = new Struct();
$params->model_id = "eleven_multilingual_v1";
$params->voice_id = "pNInz6obpgDQGcFmaJgB";
$params->stability = 0.4;
$params->similarity_boost = 0.7;
//$textData = file_get_contents($TEXT_FILE_LOCATION); // Get the text bytes data from the 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->PostModelOutputs(
// The request object carries the request along with the request status and other metadata related to the request itself
new PostModelOutputsRequest([
"user_app_id" => $userDataObject,
"model_id" => $MODEL_ID,
"version_id" => $MODEL_VERSION_ID, // This is optional. Defaults to the latest model version
"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 Text object. It offers a container that has additional text 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
]),
]),
]),
],
"model" => new Model([
"model_version" => new ModelVersion([
"output_info" => new OutputInfo(["params" => $params]),
]),
]),
]),
$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()
);
}
// Save the output file
$output = $response->getOutputs()[0]->getData()->getAudio()->getBase64();
$audioFilename = "audio_file.wav";
file_put_contents($audioFilename, base64_decode($output));
?>
curl -X POST "https://api.clarifai.com/v2/users/eleven-labs/apps/audio-generation/models/speech-synthesis/versions/f588d92c044d4487a38c8f3d7a3b0eb2/outputs" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"inputs": [
{
"data": {
"text": {
"raw": "I love your product very much!"
}
}
}
],
"model": {
"model_version": {
"output_info": {
"params": {
"model_id": "eleven_multilingual_v1",
"voice_id": "EXAVITQu4vr4xnSDxMaL",
"similarity_boost": 0,
"stability": 0.5
}
}
}
}
}'
Use Third-Party API Keys
The ability to use third-party API keys is currently exclusively available to Enterprise users. Learn more here.
For the third-party models we've wrapped into our platform, like those provided by OpenAI, Anthropic, Cohere, and others, you can also choose to utilize their API keys as an option—in addition to using the default Clarifai keys.
This Bring Your Own Key (BYOK) flexibility allows you to integrate your preferred services and APIs into your workflow, enhancing the versatility of our platform.
Here is an example of how to add an OpenAI API key for Dalle-3 for text-to-image tasks.
- cURL
curl -X POST "https://api.clarifai.com/v2/users/openai/apps/dall-e/models/dall-e-3/versions/dc9dcb6ee67543cebc0b9a025861b868/outputs" \
-H "Authorization: Key YOUR_PAT_HERE" \
-H "Content-Type: application/json" \
-d '{
"inputs": [
{
"data": {
"text": {
"raw": "An expressive oil painting of a basketball player dunking, depicted as an explosion of a nebula"
}
}
}
],
"model": {
"model_version": {
"output_info": {
"params": {
"size":"1024x1024",
"quality":"hd",
"api_key":"ADD_THIRD_PARTY_KEY_HERE"
}
}
}
}
}'