Caller-specified task subset
Running every task on every request is wasteful. A chat widget probably only needs sentiment and emotion. A content moderation pipeline might want entities and summary. Letting the caller pick the subset cuts cost, cuts latency, and cuts irrelevant noise in the response.
Caller picks the subset
The request carries a tasks array. The agent only dispatches what is asked, ignoring the rest.
VALID_TASKS = {"sentiment", "entities", "keywords", "summary", "emotion"}
class AnalyzeRequest(BaseModel):
text: str = Field(..., min_length=1, max_length=20000)
tasks: List[str] = Field(
default_factory=lambda: list(VALID_TASKS),
description="Subset of: sentiment, entities, keywords, summary, emotion",
)
class Entity(BaseModel):
text: str
type: str = Field(..., description="e.g. PERSON, ORG, LOCATION, PRODUCT, EVENT, OTHER")
class EmotionResult(BaseModel):
primary: str = Field(..., description="e.g. joy, anger, sadness, fear, surprise, disgust, neutral")
confidence: float = Field(..., ge=0.0, le=1.0)
class AnalyzeResponse(BaseModel):
text: str
tasks: List[str]
sentiment: Optional[SentimentResult] = None
entities: Optional[List[Entity]] = None
keywords: Optional[List[str]] = None
summary: Optional[str] = None
emotion: Optional[EmotionResult] = None
errors: dict = Field(default_factory=dict)Entity and EmotionResult follow the same recipe as SentimentResult: small models with constrained fields. Every task field on the response is Optional. If the caller did not request summary, the summary field stays None in the response. Callers only pay for what they ask for, and the response shape makes that obvious.
# Ask for only sentiment and emotion
curl -X POST http://localhost:8000/sentiment/analyze \
-H "Content-Type: application/json" \
-d '{
"text": "I absolutely love this new coffee shop!",
"tasks": ["sentiment", "emotion"]
}'
# Response:
# {
# "text": "I absolutely love this new coffee shop!",
# "tasks": ["sentiment", "emotion"],
# "sentiment": {"label": "positive", "score": 0.9, ...},
# "emotion": {"primary": "joy", "confidence": 0.85},
# "entities": null,
# "keywords": null,
# "summary": null,
# "errors": {}
# }Only the requested tasks run. The unrequested fields stay null in the response so the shape is stable and typed.
Quiz: Quiz
Loading practice…