Comprehend Sentiment Agent
This integration sends your input text to Amazon Comprehend and returns its sentiment analysis. Use it to evaluate a sentiment-classification task rather than a conversational agent.
Required secrets
| Secret | What it is |
|---|---|
AWS_ACCESS_KEY_ID | AWS access key for calling Comprehend. |
AWS_SECRET_ACCESS_KEY | AWS secret key for calling Comprehend. |
AWS_REGION | AWS region where Comprehend is available. |
AWS_SESSION_TOKEN | Optional AWS session token for temporary credentials. |
Where to get the credentials
Create an IAM user or role with permission to call Amazon Comprehend in the AWS
console, then store its access key, secret key, and region as
project secrets. Only set AWS_SESSION_TOKEN if
you are using temporary credentials.
Turn support
Single-turn. Each evaluation case is classified independently.
Limitations and notes
- This integration returns a sentiment label, not free-form chat text. Pair it with a specification and evaluation method that check a sentiment classification.
- Calls are billed to your own AWS account, subject to its quotas and rate limits.
How the agent works
The agent you copy is a single JavaScript function. This walkthrough explains the pattern so you can adapt it for your own custom agent connection.
The entry point is an exported process function. Its input is the text to
classify, coerced to a trimmed string:
export async function process(input) {
try {
const text = String(input ?? "").trim();
// ...
It reads its credentials from the env object, using the secret names from the
Required secrets table above. The session token is optional:
const accessKeyId = env.AWS_ACCESS_KEY_ID;
const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
const region = env.AWS_REGION;
const sessionToken = env.AWS_SESSION_TOKEN;
if (!text || !accessKeyId || !secretAccessKey || !region) {
return "template_malfunction";
}
The request body is Comprehend's DetectSentiment shape — the language code and
the text to analyze:
const body = JSON.stringify({
LanguageCode: "en",
Text: text,
});
Amazon Comprehend rejects unsigned requests, so the agent signs the request by
hand using AWS Signature Version 4 (HMAC-SHA256). The helpers near the top of the
file (sha256Hex, hmacSha256, buildAuthorization) hash the payload, assemble
the canonical request and string-to-sign, then derive a signing key by chaining
HMACs over the date, region, and service:
const kDate = await hmacSha256(`AWS4${secretAccessKey}`, dateStamp);
const kRegion = await hmacSha256(kDate, region);
const kService = await hmacSha256(kRegion, service);
const kSigning = await hmacSha256(kService, "aws4_request");
const signature = bytesToHex(await hmacSha256(kSigning, stringToSign));
return `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
The resulting signature goes into the authorization header alongside the AWS
target and timestamp headers, and the body is POSTed to the regional Comprehend
host:
const headers = {
"content-type": "application/x-amz-json-1.1",
host,
"x-amz-content-sha256": payloadHash,
"x-amz-date": amzDate,
"x-amz-target": "Comprehend_20171127.DetectSentiment",
authorization,
};
// ...
const response = await fetch(`https://${host}/`, {
method: "POST",
headers,
body,
});
It then parses the response and reads the Sentiment field, returning a
lowercased label:
const payload = await response.json();
const sentiment = String(payload?.Sentiment ?? "").toLowerCase();
if (sentiment === "positive") {
return "positive";
}
if (sentiment === "negative") {
return "negative";
}
return "template_malfunction";
For error handling, the function does not throw. A missing input or credential, a
failed HTTP response, or any caught exception all return the string
"template_malfunction". This means the agent always returns a sentiment
classification label ("positive" or "negative"), never free-form chat text.
Adapting it for your own agent
To point this skeleton at a different service, you would change:
- The endpoint host and path you POST to.
- The authentication or signing scheme (Comprehend's manual Signature Version 4 signing would be replaced by whatever your service expects).
- The request body shape sent to that service.
- The response field you extract the result from (here,
Sentiment). - The secret keys you read from
envand declare in your project secrets.
Set it up
- Copy this integration from the registry — see Registry integrations.
- Create the project secrets above — see Project secrets.
- Preview the agent to confirm it works.