Lesson 17 of 26 · see all lessons
Start here: the exam, Python basics and responsible AI (skill area 1, 40-45%)
AI models: how they work, choosing and deploying (skill area 1)
AI workloads: text, speech, vision and extraction (skill area 1)
Generative AI apps and agents in Foundry (skill area 2, 55-60%)
Text, speech, vision and extraction apps in Foundry (skill area 2)
- 17. Building a text analysis app
- 18. Building speech apps: spoken prompts and Azure Speech
- 19. Building vision apps: images in prompts and generated images
- 20. Extracting information with Content Understanding: documents and forms
- 21. Content Understanding for images, audio and video, and a small extraction app
Final review and four mock exams
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.
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.
Read the code: sentiment and key phrases with Azure Language
import osfrom azure.core.credentials import AzureKeyCredentialfrom azure.ai.textanalytics import TextAnalyticsClientendpoint = 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:continues = doc.confidence_scoresprint(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))
Exam depth: know it cold.
- Lines 1-3 import
os, the key credential class and the client. Install the package withpip install azure-ai-textanalytics. - Lines 5-7 read the endpoint and key from environment variables, then create the client.
DefaultAzureCredential()fromazure-identityalso 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_errorset. Otherwise they printsentiment(positive, negative, neutral or mixed) and theconfidence_scores, each between 0 and 1. - Lines 21-23 call
extract_key_phrasesand join each result'skey_phraseslist.
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.
One method per task
Exam depth: know it cold.
| Task | Method | What you read |
|---|---|---|
| Sentiment | analyze_sentiment | .sentiment, .confidence_scores, .sentences. |
| Opinion mining | analyze_sentiment(..., show_opinion_mining=True) | .mined_opinions on each sentence. |
| Key phrases | extract_key_phrases | .key_phrases, a list of strings. |
| Named entities | recognize_entities | .entities, each with .text and .category. |
| Personal data | recognize_pii_entities | .entities and .redacted_text. |
| Linked entities | recognize_linked_entities | Entities with a Wikipedia link. |
| Language | detect_language | .primary_language. |
Decision rule: the noun in the task names the method. "Sentiment" is analyze_sentiment, "personal data" is recognize_pii_entities.
Match
Match each Fernhill Travel need to the TextAnalyticsClient method.
Pick an item on the left, then its match on the right.
Read the code: the same task with a deployed model
import osimport jsonfrom azure.identity import DefaultAzureCredentialfrom azure.ai.projects import AIProjectClientproject = 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 nameinstructions=("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"])
Exam depth: know it cold.
- Lines 6-10 create the
AIProjectClientwith the project endpoint andDefaultAzureCredential, 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_textinto a Python dictionary withjson.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.
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.
Prebuilt API or prompted model?
Exam depth: know it cold.
| Azure Language (prebuilt) | Prompted model | |
|---|---|---|
| Output shape | Fixed objects, same every time. | Whatever your prompt asks for. |
| Confidence scores | Yes, built in, 0 to 1. | No, unless you invent one. |
| Consistency | Same input gives the same labels. | Wording can vary between runs. |
| Flexibility | Only the tasks the API has. | Any label, any field, any language task. |
| Setup | Endpoint 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.
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.
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.
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.
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.
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.
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.
Worth keeping
- Azure Language in Python: TextAnalyticsClient, a credential and one method per task.
- Every method takes a list and returns one result per document; check is_error first.
- A prompted model does custom labels and formats; parse its output_text with json.loads.
- 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.
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.
- [2]Microsoft Learn: Study guide for Exam AI-901: Microsoft Azure AI Fundamentals
- [18]Microsoft Learn: Quickstart: Get started with Microsoft Foundry SDK
- [57]Microsoft Learn: What is Azure Language in Foundry Tools?
- [69]Microsoft Learn: What is sentiment analysis and opinion mining in Azure Language service?
- [110]Microsoft Learn: Azure Text Analytics client library for Python
- [111]Microsoft Learn: TextAnalyticsClient Class
- [112]Microsoft Learn: Azure Language in Foundry Tools - tools and agents
- [113]Microsoft Learn: Customize Agent Behavior at Runtime with Structured Inputs
- [114]Microsoft Learn: How to use structured outputs with Azure OpenAI in Microsoft Foundry Models