Lesson 17 of 26 · see all lessons
  1. Start here: the exam, Python basics and responsible AI (skill area 1, 40-45%)

    1. 1. Start here: the AI-901 exam, the plan and what you already know
    2. 2. The Python and Azure basics AI-901 expects
    3. 3. Responsible AI: the six principles in practice
  2. AI models: how they work, choosing and deploying (skill area 1)

    1. 4. How generative AI models work
    2. 5. Choosing the right AI model for the job
    3. 6. Deploying a model: deployment options and configuration parameters
  3. AI workloads: text, speech, vision and extraction (skill area 1)

    1. 7. Common AI workloads: from chat and agents to vision and extraction
    2. 8. Text analysis: key phrases, entities, sentiment and summaries
    3. 9. Speech: recognition and synthesis
    4. 10. Computer vision and image generation
    5. 11. Extracting information from documents, images, audio and video
  4. Generative AI apps and agents in Foundry (skill area 2, 55-60%)

    1. 12. Writing system and user prompts
    2. 13. Deploying a model and chatting with it in the Foundry portal
    3. 14. Building a lightweight chat client with the Foundry SDK
    4. 15. Creating and testing a single agent in the Foundry portal
    5. 16. Building a lightweight client app for an agent
  5. Text, speech, vision and extraction apps in Foundry (skill area 2)

    1. 17. Building a text analysis app
    2. 18. Building speech apps: spoken prompts and Azure Speech
    3. 19. Building vision apps: images in prompts and generated images
    4. 20. Extracting information with Content Understanding: documents and forms
    5. 21. Content Understanding for images, audio and video, and a small extraction app
  6. Final review and four mock exams

    1. 22. Final review and exam day: every decision on one page
    2. 23. Mock exam 1
    3. 24. Mock exam 2
    4. 25. Mock exam 3
    5. 26. Mock exam 4
See the leaderboard

17 min

Building a text analysis app

Read a small Python app that analyzes customer reviews with Azure Language, and the same task with a deployed model.

By the end of this lesson you can

  • Read a Python app that calls Azure Language for sentiment and key phrases
  • Read the same task done with a deployed model and a JSON prompt
  • Choose between the prebuilt Azure Language API and a prompted model
  • Name the TextAnalyticsClient method for each text analysis task

From earlier lessons · 1 of 2

Fernhill Travel's chat client calls openai.responses.create(model="fh-chat", input=question). In which value does the deployment name go?

Pick one answer.

From earlier lessons · 2 of 2

A review says: "Maria at the Porto desk sorted our refund on 3 May." Which technique returns Maria, Porto and 3 May with their categories?

Pick one answer.

Fernhill Travel's reviews arrive by the hundred each week. The customer team reads a few, guesses the mood and misses the rest. The manager wants a small script that labels every review and pulls out what people talk about. You can build it two ways, and the exam expects you to read both.

[2]

Two ways to analyze text in Foundry

Exam depth: know it cold.

Azure Language is the Foundry Tool for text analysis: a prebuilt API you send text to. In Python you call it through TextAnalyticsClient from the azure-ai-textanalytics package. Each task has its own method, and each result has a fixed shape with confidence scores.

The other way is a prompted model: a model you deployed in Foundry, called with the Foundry SDK. You write instructions such as "label the sentiment and reply as JSON". The model does the task and returns text you parse.

Same goal, different trade-offs. The rest of this lesson reads both apps, then compares them.

[18][57][110]

Rendering diagram…
Top path: the prebuilt Azure Language API returns fixed result objects. Bottom path: a deployed model follows your instructions and returns text.

[18][110]

Read the code: sentiment and key phrases with Azure Language

python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]
client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
reviews = [
"The Lisbon guide was brilliant, but the hotel room was noisy.",
"Our flight to Rome was cancelled and nobody called us.",
]
results = client.analyze_sentiment(reviews)
for review, doc in zip(reviews, results):
if doc.is_error:
continue
s = doc.confidence_scores
print(f"{doc.sentiment}: pos={s.positive:.2f} neg={s.negative:.2f}")
for doc in client.extract_key_phrases(reviews):
if not doc.is_error:
print(", ".join(doc.key_phrases))
Output: one line per review, such as "mixed: pos=0.48 neg=0.50", then one line of key phrases per review, such as "Lisbon guide, hotel room". Exact scores and phrases vary.

[110][111]

Exam depth: know it cold.

  • Lines 1-3 import os, the key credential class and the client. Install the package with pip install azure-ai-textanalytics.
  • Lines 5-7 read the endpoint and key from environment variables, then create the client. DefaultAzureCredential() from azure-identity also works in place of the key.
  • Lines 9-12 build a list of strings. Every method takes a list of documents, even for one review.
  • Line 14 calls analyze_sentiment. It returns one result per document, in the same order.
  • Lines 15-19 skip any document with is_error set. Otherwise they print sentiment (positive, negative, neutral or mixed) and the confidence_scores, each between 0 and 1.
  • Lines 21-23 call extract_key_phrases and join each result's key_phrases list.

[69][110]

In the Azure Language app, line 14 is results = client.analyze_sentiment(reviews). You need the overall label for the first review. Which expression gives it?

Pick one answer.

[110]

One method per task

Exam depth: know it cold.

TaskMethodWhat you read
Sentimentanalyze_sentiment.sentiment, .confidence_scores, .sentences.
Opinion mininganalyze_sentiment(..., show_opinion_mining=True).mined_opinions on each sentence.
Key phrasesextract_key_phrases.key_phrases, a list of strings.
Named entitiesrecognize_entities.entities, each with .text and .category.
Personal datarecognize_pii_entities.entities and .redacted_text.
Linked entitiesrecognize_linked_entitiesEntities with a Wikipedia link.
Languagedetect_language.primary_language.

Decision rule: the noun in the task names the method. "Sentiment" is analyze_sentiment, "personal data" is recognize_pii_entities.

[110][111]

Match

Match each Fernhill Travel need to the TextAnalyticsClient method.

Pick an item on the left, then its match on the right.

[110]

[57][69][110]

Read the code: the same task with a deployed model

python
import os
import json
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
project = AIProjectClient(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
review = "The Lisbon guide was brilliant, but the hotel room was noisy."
response = openai.responses.create(
model="gpt-5-mini", # your deployment name
instructions=(
"Label the review's sentiment as positive, negative, neutral or mixed "
"and list its key phrases. Reply only with JSON like "
'{"sentiment": "mixed", "key_phrases": ["hotel room"]}'
),
input=review,
)
result = json.loads(response.output_text)
print(result["sentiment"], result["key_phrases"])
Output: something like "mixed ['Lisbon guide', 'hotel room']". The model writes the JSON, so wording can vary between runs.

[18][113]

Exam depth: know it cold.

  • Lines 6-10 create the AIProjectClient with the project endpoint and DefaultAzureCredential, then get an OpenAI client. This is the chat client from lesson 14.
  • Line 14 passes your deployment name as model.
  • Lines 15-19 set instructions, the system-style rules for this call. They name the labels, the task and the JSON shape.
  • Line 20 sends the review as input.
  • Line 22 turns output_text into a Python dictionary with json.loads.

A prompt asks for JSON but can't force it. If the model adds extra words, json.loads fails. Structured outputs fix that: you pass a JSON schema in the Responses API's text.format, and the model must follow it.

[18][113][114]

For each statement, select Yes if it is true. Statement: in the prompted-model app, json.loads(response.output_text) always succeeds, because the instructions ask for JSON.

Pick one answer.

[114]

Prebuilt API or prompted model?

Exam depth: know it cold.

Azure Language (prebuilt)Prompted model
Output shapeFixed objects, same every time.Whatever your prompt asks for.
Confidence scoresYes, built in, 0 to 1.No, unless you invent one.
ConsistencySame input gives the same labels.Wording can vary between runs.
FlexibilityOnly the tasks the API has.Any label, any field, any language task.
SetupEndpoint and key, one call per task.A deployed model and a careful prompt.

Decision rule: standard task, scores or repeatable labels, use Azure Language. Custom labels or one call that does several things in your own format, prompt a deployed model.

[69][110][114]

Fernhill Travel needs every review tagged with one of its own labels: "guide", "hotel", "transport" or "booking". A short reason must explain each tag. The team wants one call per review. What should you use?

Pick one answer.

[110][113]

Me: asks the model for JSON. The model: "Sure! Here's your JSON:" json.loads: crashes. Picture: Classic two-panel reaction meme, flat cartoon style.

Azure Language as an agent tool

Exam depth: recognize it.

Agents can call Azure Language too. The Azure Language MCP server (preview) exposes features such as NER, PII redaction, sentiment and summarization as tools through the Model Context Protocol. You add it to an agent in the Foundry portal from the tool catalog, through a project connection. It also runs as a local server you host yourself.

Recognize the idea: the agent decides when to call Azure Language, and you write no TextAnalyticsClient code.

[57][112]

Exam-style practice

Fernhill Travel stores support emails for training. Staff must not see customers' phone numbers or passport numbers. The solution must return the email text with those values masked, with the least code. Which method should you call?

Pick one answer.

[110]

For each statement, select Yes if it is true. Statement: analyze_sentiment returns confidence scores for positive, neutral and negative for each document and each sentence.

Pick one answer.

[69]

Complete the code. client = TextAnalyticsClient(endpoint=endpoint, credential=____). The app uses an API key stored in the variable key. What goes in the blank?

Pick one answer.

[110]

A dashboard must show how sure the system is about each review's sentiment, as a number from 0 to 1. The team wants the least custom code. What should you use?

Pick one answer.

[69]

FlashcardsIndex cardsFlashcards ⚡

Card 1 of 17

[110][112][114]

Worth keeping

  1. Azure Language in Python: TextAnalyticsClient, a credential and one method per task.
  2. Every method takes a list and returns one result per document; check is_error first.
  3. A prompted model does custom labels and formats; parse its output_text with json.loads.
  4. Need confidence scores or repeatable labels: Azure Language. Need your own labels: a prompt.

On the job

Start with the prebuilt API for anything it already does, such as entities or PII masking. Sentiment and key phrases still work but retire in March 2029, so plan new sentiment work on a deployed model. It is cheap to run, returns the same labels for the same text and gives scores you can set thresholds on. Add a prompted model only for the part the API can't do, such as your company's own topic labels. Log the model's raw reply, so you can see why a parse failed.

[69][110][114]

Reviews are handled. Then a customer calls the Fernhill helpline and asks, out loud, "Which tours still have seats in June?" Text won't do this time. Next lesson, your app listens and talks back.

Leaderboard

Loading…

50 XP for each lesson you finish, 10 for each right answer. Names show only for learners who turn on Show me on leaderboards.

Embed this practice on your site

Free for classrooms, blogs and study groups. Paste this into any page that accepts HTML.

Report a copyright problem with this lesson

Sources for this lesson (9)

Each fact in the lesson is marked with the number of the page it comes from.

  1. [2]Microsoft Learn: Study guide for Exam AI-901: Microsoft Azure AI Fundamentals
  2. [18]Microsoft Learn: Quickstart: Get started with Microsoft Foundry SDK
  3. [57]Microsoft Learn: What is Azure Language in Foundry Tools?
  4. [69]Microsoft Learn: What is sentiment analysis and opinion mining in Azure Language service?
  5. [110]Microsoft Learn: Azure Text Analytics client library for Python
  6. [111]Microsoft Learn: TextAnalyticsClient Class
  7. [112]Microsoft Learn: Azure Language in Foundry Tools - tools and agents
  8. [113]Microsoft Learn: Customize Agent Behavior at Runtime with Structured Inputs
  9. [114]Microsoft Learn: How to use structured outputs with Azure OpenAI in Microsoft Foundry Models