Documentation Index
Fetch the complete documentation index at: https://assemblyai.com/docs/llms.txt
Use this file to discover all available pages before exploring further.
Supported languages
Supported languages
Supported models
Supported models
Supported regions
Supported regions
US & EU
Quickstart
- Python
- Python SDK
- JavaScript
- JavaScript SDK
Enable Sentiment Analysis by setting
sentiment_analysis to True in the JSON payload.import requests
import time
base_url = "https://api.assemblyai.com"
headers = {
"authorization": "<YOUR_API_KEY>"
}
with open("./local_file.mp3", "rb") as f:
response = requests.post(base_url + "/v2/upload",
headers=headers,
data=f)
upload_url = response.json()["upload_url"]
data = {
"audio_url": upload_url, # You can also use a URL to an audio or video file on the web
"speech_models": ["universal-3-pro", "universal-2"],
"language_detection": True,
"sentiment_analysis": True
}
url = base_url + "/v2/transcript"
response = requests.post(url, json=data, headers=headers)
transcript_id = response.json()['id']
polling_endpoint = base_url + "/v2/transcript/" + transcript_id
print(f"Transcript ID: {transcript_id}")
while True:
transcription_result = requests.get(polling_endpoint, headers=headers).json()
if transcription_result['status'] == 'completed':
for sentiment_result in transcription_result['sentiment_analysis_results']:
print(sentiment_result['text'])
print(sentiment_result['sentiment']) # POSITIVE, NEUTRAL, or NEGATIVE
print(sentiment_result['confidence'])
print(f"Timestamp: {sentiment_result['start']} - {sentiment_result['end']}")
break
elif transcription_result['status'] == 'error':
raise RuntimeError(f"Transcription failed: {transcription_result['error']}")
else:
time.sleep(3)
Enable Sentiment Analysis by setting
sentiment_analysis to True in the transcription config.import assemblyai as aai
aai.settings.api_key = "<YOUR_API_KEY>"
# audio_file = "./local_file.mp3"
audio_file = "https://assembly.ai/wildfires.mp3"
config = aai.TranscriptionConfig(
speech_models=["universal-3-pro", "universal-2"],
language_detection=True,
sentiment_analysis=True
)
transcript = aai.Transcriber().transcribe(audio_file, config)
print(f"Transcript ID: {transcript.id}")
for sentiment_result in transcript.sentiment_analysis:
print(sentiment_result.text)
print(sentiment_result.sentiment) # POSITIVE, NEUTRAL, or NEGATIVE
print(sentiment_result.confidence)
print(f"Timestamp: {sentiment_result.start} - {sentiment_result.end}")
Enable Sentiment Analysis by setting
sentiment_analysis to true in the JSON payload.import fs from "fs-extra";
const baseUrl = "https://api.assemblyai.com";
const headers = {
authorization: "<YOUR_API_KEY>",
};
const path = "./my-audio.mp3";
const audioData = await fs.readFile(path);
let res = await fetch(`${baseUrl}/v2/upload`, {
method: "POST",
headers,
body: audioData,
});
if (!res.ok) throw new Error(`Error: ${res.status}`);
const uploadResponse = await res.json();
const uploadUrl = uploadResponse.upload_url;
const data = {
audio_url: uploadUrl, // You can also use a URL to an audio or video file on the web
speech_models: ["universal-3-pro", "universal-2"],
language_detection: true,
sentiment_analysis: true,
};
const url = `${baseUrl}/v2/transcript`;
res = await fetch(url, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error(`Error: ${res.status}`);
const response = await res.json();
const transcriptId = response.id;
console.log("Transcript ID: ", transcriptId);
const pollingEndpoint = `${baseUrl}/v2/transcript/${transcriptId}`;
while (true) {
res = await fetch(pollingEndpoint, { headers });
if (!res.ok) throw new Error(`Error: ${res.status}`);
const transcriptionResult = await res.json();
if (transcriptionResult.status === "completed") {
for (const sentimentResult of transcriptionResult.sentiment_analysis_results) {
console.log(sentimentResult.text);
console.log(sentimentResult.sentiment); // POSITIVE, NEUTRAL, or NEGATIVE
console.log(sentimentResult.confidence);
console.log(
`Timestamp: ${sentimentResult.start} - ${sentimentResult.end}`
);
}
break;
} else if (transcriptionResult.status === "error") {
throw new Error(`Transcription failed: ${transcriptionResult.error}`);
} else {
await new Promise((resolve) => setTimeout(resolve, 3000));
}
}
Enable Sentiment Analysis by setting
sentiment_analysis to true in the transcription config.import { AssemblyAI } from "assemblyai";
const client = new AssemblyAI({
apiKey: "<YOUR_API_KEY>",
});
// const audioFile = './local_file.mp3'
const audioFile = "https://assembly.ai/wildfires.mp3";
const params = {
audio: audioFile,
speech_models: ["universal-3-pro", "universal-2"],
language_detection: true,
sentiment_analysis: true,
};
const run = async () => {
const transcript = await client.transcripts.transcribe(params);
console.log("Transcript ID: ", transcript.id);
for (const result of transcript.sentiment_analysis_results) {
console.log(result.text);
console.log(result.sentiment); // POSITIVE, NEUTRAL, or NEGATIVE
console.log(result.confidence);
console.log(`Timestamp: ${result.start} - ${result.end}`);
}
};
run();
Example output
Smoke from hundreds of wildfires in Canada is triggering air quality alerts throughout the US.
NEGATIVE
0.8181032538414001
Timestamp: 250 - 6350
...
Sentiment Analysis Using LLM GatewayCheck out this cookbook LLM Gateway for Customer Call Sentiment
Analysis for an example of how to use
LLM Gateway to analyze the sentiment of a customer call.
Add speaker labels to sentiments
- Python
- Python SDK
- JavaScript
- JavaScript SDK
To add speaker labels to each sentiment analysis result, using Speaker Diarization, enable
speaker_labels in the JSON payload.Each sentiment result will then have a speaker field that contains the speaker label.data = {
"audio_url": upload_url,
"sentiment_analysis": True,
"speaker_labels": True
}
# ...
for sentiment_result in transcription_result['sentiment_analysis_results']:
print(sentiment_result['speaker'])
break
To add speaker labels to each sentiment analysis result, using Speaker Diarization, enable
speaker_labels in the transcription config.Each sentiment result will then have a speaker field that contains the speaker label.config = aai.TranscriptionConfig(
sentiment_analysis=True,
speaker_labels=True
)
# ...
for sentiment_result in transcript.sentiment_analysis:
print(sentiment_result.speaker)
To add speaker labels to each sentiment analysis result, using Speaker Diarization, enable
speaker_labels in the JSON payload.Each sentiment result will then have a speaker field that contains the speaker label.const data = {
audio_url: uploadUrl,
sentiment_analysis: true,
speaker_labels: true
}
// ...
for (const sentimentResult of transcriptionResult.sentiment_analysis_results) {
console.log(sentimentResult.speaker);
}
break;
To add speaker labels to each sentiment analysis result, using Speaker Diarization, enable
speaker_labels in the transcription config.Each sentiment result will then have a speaker field that contains the speaker label.const params = {
audio: audioUrl,
sentiment_analysis: true,
speaker_labels: true,
};
// ...
for (const result of transcript.sentiment_analysis_results) {
console.log(result.speaker);
}
API reference
Request
curl https://api.assemblyai.com/v2/transcript \
--header "Authorization: <YOUR_API_KEY>" \
--header "Content-Type: application/json" \
--data '{
"audio_url": "YOUR_AUDIO_URL",
"sentiment_analysis": true
}'
| Key | Type | Description |
|---|---|---|
sentiment_analysis | boolean | Enable Sentiment Analysis. |
Response
{
sentiment_analysis_results: [
{
text: "Smoke from hundreds of wildfires in Canada is triggering air quality alerts throughout the US.",
start: 250,
end: 6382,
sentiment: "NEGATIVE",
confidence: 0.8181034922599792,
speaker: null,
},
{
text: "Skylines from Maine to Maryland to Minnesota are gray and smoggy.",
start: 6516,
end: 11050,
sentiment: "NEGATIVE",
confidence: 0.5900681018829346,
speaker: null,
},
{
text: "And in some places, the air quality warnings include the warning to stay inside.",
start: 11130,
end: 15646,
sentiment: "NEUTRAL",
confidence: 0.5371454358100891,
speaker: null,
},
{
text: "We wanted to better understand what's happening here and why, so we called Peter de Carlo, an associate professor in the Department of Environmental Health and Engineering at Johns Hopkins University Varsity.",
start: 15828,
end: 25490,
sentiment: "NEUTRAL",
confidence: 0.7929256558418274,
speaker: null,
},
{
text: "Good morning, professor.",
start: 25570,
end: 26950,
sentiment: "POSITIVE",
confidence: 0.8253473043441772,
speaker: null,
},
{
text: "Good morning.",
start: 27850,
end: 28840,
sentiment: "POSITIVE",
confidence: 0.7193593382835388,
speaker: null,
},
{
text: "What is it about the conditions right now that have caused this round of wildfires to affect so many people so far away?",
start: 29610,
end: 37400,
sentiment: "NEGATIVE",
confidence: 0.7902835607528687,
speaker: null,
},
{
text: "Well, there's a couple of things.",
start: 38970,
end: 40694,
sentiment: "NEUTRAL",
confidence: 0.7348891496658325,
speaker: null,
},
{
text: "The season has been pretty dry already.",
start: 40892,
end: 42922,
sentiment: "NEGATIVE",
confidence: 0.9268015623092651,
speaker: null,
},
{
text: "And then the fact that we're getting hit in the US.",
start: 43056,
end: 45898,
sentiment: "NEGATIVE",
confidence: 0.7737327814102173,
speaker: null,
},
{
text: "Is because there's a couple of weather systems that are essentially channeling the smoke from those Canadian wildfires through Pennsylvania into the Mid Atlantic and the Northeast and kind of just dropping the smoke there.",
start: 46064,
end: 56142,
sentiment: "NEUTRAL",
confidence: 0.6657092571258545,
speaker: null,
},
{
text: "So what is it in this haze that makes it harmful?",
start: 56276,
end: 59274,
sentiment: "NEGATIVE",
confidence: 0.8751137852668762,
speaker: null,
},
{
text: "And I'm assuming it is harmful.",
start: 59322,
end: 61070,
sentiment: "NEGATIVE",
confidence: 0.8000661730766296,
speaker: null,
},
{
text: "It is.",
start: 62290,
end: 63150,
sentiment: "NEUTRAL",
confidence: 0.6054744720458984,
speaker: null,
},
{
text: "The levels outside right now in Baltimore are considered unhealthy.",
start: 63300,
end: 67010,
sentiment: "NEGATIVE",
confidence: 0.9444372653961182,
speaker: null,
},
{
text: "And most of that is due to what's called particulate matter, which are tiny particles, microscopic smaller than the width of your hair that can get into your lungs and impact your respiratory system, your cardiovascular system, and even your neurological your brain.",
start: 67750,
end: 82950,
sentiment: "NEGATIVE",
confidence: 0.7631250619888306,
speaker: null,
},
{
text: "What makes this particularly harmful?",
start: 83450,
end: 85554,
sentiment: "NEGATIVE",
confidence: 0.932969331741333,
speaker: null,
},
{
text: "Is it the volume of particulant?",
start: 85602,
end: 88034,
sentiment: "NEUTRAL",
confidence: 0.8304142951965332,
speaker: null,
},
{
text: "Is it something in particular?",
start: 88082,
end: 89302,
sentiment: "NEUTRAL",
confidence: 0.8175228238105774,
speaker: null,
},
{
text: "What is it exactly?",
start: 89436,
end: 90278,
sentiment: "NEUTRAL",
confidence: 0.815334141254425,
speaker: null,
},
{
text: "Can you just drill down on that a little bit more?",
start: 90364,
end: 92540,
sentiment: "NEUTRAL",
confidence: 0.8712159991264343,
speaker: null,
},
{
text: "Yeah.",
start: 93390,
end: 93802,
sentiment: "NEUTRAL",
confidence: 0.5491448640823364,
speaker: null,
},
{
text: "So the concentration of particulate matter I was looking at some of the monitors that we have was reaching levels of what are, in science, big 150 micrograms per meter cubed, which is more than ten times what the annual average should be and about four times higher than what you're supposed to have on a 24 hours average.",
start: 93856,
end: 113258,
sentiment: "NEUTRAL",
confidence: 0.6115278601646423,
speaker: null,
},
{
text: "And so the concentrations of these particles in the air are just much, much higher than we typically see.",
start: 113354,
end: 119650,
sentiment: "NEUTRAL",
confidence: 0.5178466439247131,
speaker: null,
},
{
text: "And exposure to those high levels can lead to a host of health problems.",
start: 119720,
end: 123314,
sentiment: "NEGATIVE",
confidence: 0.939525306224823,
speaker: null,
},
{
text: "And who is most vulnerable?",
start: 123432,
end: 124942,
sentiment: "NEUTRAL",
confidence: 0.5373413562774658,
speaker: null,
},
{
text: "I noticed that in New York City, for example, they're canceling outdoor activities.",
start: 125006,
end: 128702,
sentiment: "NEGATIVE",
confidence: 0.7793571352958679,
speaker: null,
},
{
text: "And so here it is in the early days of summer, and they have to keep all the kids inside.",
start: 128766,
end: 132870,
sentiment: "NEUTRAL",
confidence: 0.4853213131427765,
speaker: null,
},
{
text: "So who tends to be vulnerable in a situation like this?",
start: 132940,
end: 136440,
sentiment: "NEUTRAL",
confidence: 0.5655253529548645,
speaker: null,
},
{
text: "It's the youngest.",
start: 137370,
end: 138754,
sentiment: "NEUTRAL",
confidence: 0.7843366265296936,
speaker: null,
},
{
text: "So children, obviously, whose bodies are still developing.",
start: 138802,
end: 142514,
sentiment: "NEUTRAL",
confidence: 0.765259325504303,
speaker: null,
},
{
text: "The elderly, who are their bodies are more in decline and they're more susceptible to the health impacts of breathing, the poor air quality.",
start: 142562,
end: 149660,
sentiment: "NEGATIVE",
confidence: 0.9401319026947021,
speaker: null,
},
{
text: "And then people who have preexisting health conditions, people with respiratory conditions or heart conditions can be triggered by high levels of air pollution.",
start: 150530,
end: 156910,
sentiment: "NEGATIVE",
confidence: 0.8857417702674866,
speaker: null,
},
{
text: "Could this get worse?",
start: 157410,
end: 158910,
sentiment: "NEGATIVE",
confidence: 0.9435272216796875,
speaker: null,
},
{
text: "That's a good question.",
start: 162050,
end: 163440,
sentiment: "POSITIVE",
confidence: 0.8283342719078064,
speaker: null,
},
{
text: "In some areas, it's much worse than others.",
start: 165010,
end: 166942,
sentiment: "NEGATIVE",
confidence: 0.896091103553772,
speaker: null,
},
{
text: "And it just depends on kind of where the smoke is concentrated.",
start: 166996,
end: 170370,
sentiment: "NEUTRAL",
confidence: 0.7206501960754395,
speaker: null,
},
{
text: "I think New York has some of the higher concentrations right now, but that's going to change as that air moves away from the New York area.",
start: 170950,
end: 176930,
sentiment: "NEUTRAL",
confidence: 0.758122980594635,
speaker: null,
},
{
text: "But over the course of the next few days, we will see different areas being hit at different times with the highest concentrations.",
start: 177080,
end: 183666,
sentiment: "NEUTRAL",
confidence: 0.7974407076835632,
speaker: null,
},
{
text: "I was going to ask you about more fires start burning.",
start: 183778,
end: 185634,
sentiment: "NEUTRAL",
confidence: 0.611624538898468,
speaker: null,
},
{
text: "I don't expect the concentrations to go up too much higher.",
start: 185682,
end: 189030,
sentiment: "NEUTRAL",
confidence: 0.5720192790031433,
speaker: null,
},
{
text: "I was going to ask you how and you started to answer this, but how much longer could this last?",
start: 189100,
end: 193242,
sentiment: "NEUTRAL",
confidence: 0.546766459941864,
speaker: null,
},
{
text: "Or forgive me if I'm asking you to speculate, but what do you think?",
start: 193296,
end: 196540,
sentiment: "NEUTRAL",
confidence: 0.7195860743522644,
speaker: null,
},
{
text: "Well, I think the fires are going to burn for a little bit longer, but the key for us in the US.",
start: 198030,
end: 202202,
sentiment: "NEUTRAL",
confidence: 0.5855423808097839,
speaker: null,
},
{
text: "Is the weather system changing.",
start: 202256,
end: 203754,
sentiment: "NEUTRAL",
confidence: 0.8448712229728699,
speaker: null,
},
{
text: "And so right now, it's kind of the weather systems that are pulling that air into our mid Atlantic and Northeast region.",
start: 203802,
end: 211082,
sentiment: "NEUTRAL",
confidence: 0.8283596038818359,
speaker: null,
},
{
text: "As those weather systems change and shift, we'll see that smoke going elsewhere and not impact us in this region as much.",
start: 211146,
end: 219122,
sentiment: "NEUTRAL",
confidence: 0.6655184030532837,
speaker: null,
},
{
text: "And so I think that's going to be the defining factor.",
start: 219176,
end: 221006,
sentiment: "NEUTRAL",
confidence: 0.6444751024246216,
speaker: null,
},
{
text: "And I think the next couple of days we're going to see a shift in that weather pattern and start to push the smoke away from where we are.",
start: 221038,
end: 227638,
sentiment: "NEUTRAL",
confidence: 0.8290640711784363,
speaker: null,
},
{
text: "And finally, with the impacts of climate change, we are seeing more wildfires.",
start: 227724,
end: 232354,
sentiment: "NEGATIVE",
confidence: 0.6964414715766907,
speaker: null,
},
{
text: "Will we be seeing more of these kinds of wide ranging air quality consequences or circumstances?",
start: 232482,
end: 240330,
sentiment: "NEUTRAL",
confidence: 0.5142849087715149,
speaker: null,
},
{
text: "I mean, that is one of the predictions for climate change.",
start: 241310,
end: 245162,
sentiment: "NEUTRAL",
confidence: 0.6701292395591736,
speaker: null,
},
{
text: "Looking into the future, the fire season is starting earlier and lasting longer, and we're seeing more frequent fires.",
start: 245216,
end: 251286,
sentiment: "NEUTRAL",
confidence: 0.475503146648407,
speaker: null,
},
{
text: "So, yeah, this is probably something that we'll be seeing more frequently.",
start: 251318,
end: 255578,
sentiment: "NEUTRAL",
confidence: 0.6273220181465149,
speaker: null,
},
{
text: "This tends to be much more of an issue in the Western US.",
start: 255674,
end: 258046,
sentiment: "NEUTRAL",
confidence: 0.5828160643577576,
speaker: null,
},
{
text: "So the eastern US.",
start: 258148,
end: 259054,
sentiment: "NEUTRAL",
confidence: 0.7606309056282043,
speaker: null,
},
{
text: "Getting hit right now is a little bit new.",
start: 259092,
end: 261760,
sentiment: "NEUTRAL",
confidence: 0.5369289517402649,
speaker: null,
},
{
text: "But yeah, I think with climate change moving forward, this is something that is going to happen more frequently.",
start: 262130,
end: 267770,
sentiment: "NEUTRAL",
confidence: 0.6625354886054993,
speaker: null,
},
{
text: "That's Peter De Carlo, associate professor in the Department of Environmental Health and Engineering at Johns Hopkins University.",
start: 267930,
end: 274850,
sentiment: "NEUTRAL",
confidence: 0.90962153673172,
speaker: null,
},
{
text: "Sergeant Carlo, thanks so much for joining us and sharing this expertise with us.",
start: 274970,
end: 278600,
sentiment: "POSITIVE",
confidence: 0.9753028154373169,
speaker: null,
},
{
text: "Thank you for having me.",
start: 279370,
end: 280340,
sentiment: "POSITIVE",
confidence: 0.9709058403968811,
speaker: null,
},
],
}
| Key | Type | Description |
|---|---|---|
sentiment_analysis_results | array | A temporal sequence of Sentiment Analysis results for the audio file, one element for each sentence in the file. |
sentiment_analysis_results[i].text | string | The transcript of the i-th sentence. |
sentiment_analysis_results[i].start | number | The starting time, in milliseconds, of the i-th sentence. |
sentiment_analysis_results[i].end | number | The ending time, in milliseconds, of the i-th sentence. |
sentiment_analysis_results[i].sentiment | string | The detected sentiment for the i-th sentence, one of POSITIVE, NEUTRAL, NEGATIVE. |
sentiment_analysis_results[i].confidence | number | The confidence score for the detected sentiment of the i-th sentence, from 0 to 1. |
sentiment_analysis_results[i].speaker | string or null | The speaker of the i-th sentence if Speaker Diarization is enabled, else null. |
Frequently asked questions
What if the model predicts the wrong sentiment label for a sentence?
What if the model predicts the wrong sentiment label for a sentence?
The Sentiment Analysis model is based on the interpretation of the transcript and may not always accurately capture the intended sentiment of the speaker. It’s recommended to take into account the context of the transcript and to validate the sentiment analysis results with human judgment when possible.
What if the transcript contains sensitive or offensive content?
What if the transcript contains sensitive or offensive content?
The Content Moderation model can be used to identify and filter out sensitive or offensive content from the transcript.
What if the sentiment analysis results aren't consistent with my expectations?
What if the sentiment analysis results aren't consistent with my expectations?
It’s important to ensure that the audio being analyzed is relevant to your use case. Additionally, it’s recommended to take into account the context of the transcript and to evaluate the confidence score for each sentiment label.
What if the sentiment analysis is taking too long to process?
What if the sentiment analysis is taking too long to process?
The Sentiment Analysis model is designed to be fast and efficient, but processing times may vary depending on the size of the audio file and the complexity of the language used. If you experience longer processing times than expected, don’t hesitate to contact our support team.