azure-ai-textanalytics-py

SDK de Azure AI Text Analytics para análisis de sentimiento, reconocimiento de entidades, frases clave, detección de idioma, PII y NLP en salud. Úsalo para procesamiento de lenguaje natural en texto. Disparadores: "text analytics", "sentiment analysis", "entity recognition", "key phrase", "PII detection", "TextAnalyticsClient".

npx skills add https://github.com/microsoft/skills --skill azure-ai-textanalytics-py

Azure AI Text Analytics SDK for Python

Client library for Azure AI Language service NLP capabilities including sentiment, entities, key phrases, and more.

Installation

pip install azure-ai-textanalytics

Environment Variables

AZURE_LANGUAGE_ENDPOINT=https://<resource>.cognitiveservices.azure.com  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
AZURE_LANGUAGE_KEY=<your-api-key>  # Only required for the legacy API-key auth path below

Authentication & Lifecycle

🔑 Two rules apply to every code sample below:

  1. Prefer DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
    • Local dev: DefaultAzureCredential works as-is.
    • Production: set AZURE_TOKEN_CREDENTIALS=prod (or AZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.
  2. Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
    • Sync: with <Client>(...) as client:
    • Async: async with <Client>(...) as client: and async with DefaultAzureCredential() as credential: (from azure.identity.aio)

Snippets may abbreviate this setup, but production code should always follow both rules.

import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.textanalytics import TextAnalyticsClient

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with TextAnalyticsClient(
    endpoint=os.environ["AZURE_LANGUAGE_ENDPOINT"],
    credential=credential,
) as client:
    languages = client.detect_language(["Hello, world!"])

Legacy: API Key (existing keyed deployments)

New code should use DefaultAzureCredential above. Use AzureKeyCredential only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

with TextAnalyticsClient(
    endpoint=os.environ["AZURE_LANGUAGE_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["AZURE_LANGUAGE_KEY"]),
) as client:
    languages = client.detect_language(["Hello, world!"])

Sentiment Analysis

documents = [
    "I had a wonderful trip to Seattle last week!",
    "The food was terrible and the service was slow."
]

result = client.analyze_sentiment(documents, show_opinion_mining=True)

for doc in result:
    if not doc.is_error:
        print(f"Sentiment: {doc.sentiment}")
        print(f"Scores: pos={doc.confidence_scores.positive:.2f}, "
              f"neg={doc.confidence_scores.negative:.2f}, "
              f"neu={doc.confidence_scores.neutral:.2f}")
        
        # Opinion mining (aspect-based sentiment)
        for sentence in doc.sentences:
            for opinion in sentence.mined_opinions:
                target = opinion.target
                print(f"  Target: '{target.text}' - {target.sentiment}")
                for assessment in opinion.assessments:
                    print(f"    Assessment: '{assessment.text}' - {assessment.sentiment}")

Entity Recognition

documents = ["Microsoft was founded by Bill Gates and Paul Allen in Albuquerque."]

result = client.recognize_entities(documents)

for doc in result:
    if not doc.is_error:
        for entity in doc.entities:
            print(f"Entity: {entity.text}")
            print(f"  Category: {entity.category}")
            print(f"  Subcategory: {entity.subcategory}")
            print(f"  Confidence: {entity.confidence_score:.2f}")

PII Detection

documents = ["My SSN is 123-45-6789 and my email is john@example.com"]

result = client.recognize_pii_entities(documents)

for doc in result:
    if not doc.is_error:
        print(f"Redacted: {doc.redacted_text}")
        for entity in doc.entities:
            print(f"PII: {entity.text} ({entity.category})")

Key Phrase Extraction

documents = ["Azure AI provides powerful machine learning capabilities for developers."]

result = client.extract_key_phrases(documents)

for doc in result:
    if not doc.is_error:
        print(f"Key phrases: {doc.key_phrases}")

Language Detection

documents = ["Ce document est en francais.", "This is written in English."]

result = client.detect_language(documents)

for doc in result:
    if not doc.is_error:
        print(f"Language: {doc.primary_language.name} ({doc.primary_language.iso6391_name})")
        print(f"Confidence: {doc.primary_language.confidence_score:.2f}")

Healthcare Text Analytics

documents = ["Patient has diabetes and was prescribed metformin 500mg twice daily."]

poller = client.begin_analyze_healthcare_entities(documents)
result = poller.result()

for doc in result:
    if not doc.is_error:
        for entity in doc.entities:
            print(f"Entity: {entity.text}")
            print(f"  Category: {entity.category}")
            print(f"  Normalized: {entity.normalized_text}")
            
            # Entity links (UMLS, etc.)
            for link in entity.data_sources:
                print(f"  Link: {link.name} - {link.entity_id}")

Multiple Analysis (Batch)

from azure.ai.textanalytics import (
    RecognizeEntitiesAction,
    ExtractKeyPhrasesAction,
    AnalyzeSentimentAction
)

documents = ["Microsoft announced new Azure AI features at Build conference."]

poller = client.begin_analyze_actions(
    documents,
    actions=[
        RecognizeEntitiesAction(),
        ExtractKeyPhrasesAction(),
        AnalyzeSentimentAction()
    ]
)

results = poller.result()
for doc_results in results:
    for result in doc_results:
        if result.kind == "EntityRecognition":
            print(f"Entities: {[e.text for e in result.entities]}")
        elif result.kind == "KeyPhraseExtraction":
            print(f"Key phrases: {result.key_phrases}")
        elif result.kind == "SentimentAnalysis":
            print(f"Sentiment: {result.sentiment}")

Async Client

from azure.ai.textanalytics.aio import TextAnalyticsClient
from azure.identity.aio import DefaultAzureCredential

async def analyze():
    async with DefaultAzureCredential() as credential:
        async with TextAnalyticsClient(
            endpoint=endpoint,
            credential=credential
        ) as client:
            result = await client.analyze_sentiment(documents)
            # Process results...

Client Types

ClientPurpose
TextAnalyticsClientAll text analytics operations
TextAnalyticsClient (aio)Async version

Available Operations

MethodDescription
analyze_sentimentSentiment analysis with opinion mining
recognize_entitiesNamed entity recognition
recognize_pii_entitiesPII detection and redaction
recognize_linked_entitiesEntity linking to Wikipedia
extract_key_phrasesKey phrase extraction
detect_languageLanguage detection
begin_analyze_healthcare_entitiesHealthcare NLP (long-running)
begin_analyze_actionsMultiple analyses in batch

Best Practices

  1. Pick sync OR async and stay consistent. Do not mix azure.ai.textanalytics sync clients with azure.ai.textanalytics.aio async clients in the same call path. Choose one mode per module.
  2. Always use context managers for clients and async credentials. Wrap every client in with TextAnalyticsClient(...) as client: (sync) or async with TextAnalyticsClient(...) as client: (async). For async DefaultAzureCredential from azure.identity.aio, also use async with credential: so tokens and transports are cleaned up.
  3. Use batch operations for multiple documents (up to 10 per request)
  4. Enable opinion mining for detailed aspect-based sentiment
  5. Use async client for high-throughput scenarios
  6. Handle document errors — results list may contain errors for some docs
  7. Specify language when known to improve accuracy

Reference Files

FileContents
references/capabilities.mdAdditional non-hero capabilities, operation-group coverage, and production checklists.
references/non-hero-scenarios.mdDedicated non-hero examples for secondary/advanced scenarios.

Más skills de microsoft

oss-growth
microsoft
Persona de growth hacker de OSS
agent-framework-azure-ai-py
microsoft
Crea agentes de Azure AI Foundry usando el SDK de Python de Microsoft Agent Framework (agent-framework-azure-ai). Úsalo al crear agentes persistentes con AzureAIAgentsProvider, usando herramientas alojadas (intérprete de código, búsqueda de archivos, búsqueda web), integrando servidores MCP, gestionando hilos de conversación o implementando respuestas en streaming. Cubre herramientas de función, salidas estructuradas y agentes con múltiples herramientas.
development
airunway-aks-setup
microsoft
Configura AI Runway en AKS: desde un clúster vacío hasta un modelo en ejecución. Incluye verificación del clúster, instalación del controlador, evaluación de GPU, configuración del proveedor y primer despliegue. CUÁNDO: "configurar AI Runway", "incorporar clúster AKS", "instalar AI Runway", "configuración de airunway", "desplegar modelo en AKS", "inferencia GPU en AKS", "configuración de KAITO en AKS", "ejecutar LLM en AKS", "vLLM en AKS", "configurar servicio de modelos en AKS", "controlador de AI Runway".
devops
appinsights-instrumentation
microsoft
Guidance for instrumenting webapps with Azure Application Insights. Provides telemetry patterns, SDK setup, and configuration references. WHEN: how to instrument app, App Insights SDK, telemetry patterns, what is App Insights, Application Insights guidance, instrumentation examples, APM best practices.
devops
applicationinsights-web-ts
microsoft
Instrumenta aplicaciones web/navegador con el SDK de JavaScript de Application Insights (@microsoft/applicationinsights-web). Úsalo para monitoreo de usuarios reales (RUM): vistas de página, clics, dependencias AJAX/fetch, excepciones, eventos personalizados y trazas de agentes GenAI del lado del navegador correlacionadas con trazas de OpenTelemetry del backend. Cubre el script de carga del SDK y la configuración npm, extensiones de frameworks (React, React Native, Angular), Click Analytics, inicializadores de telemetría y convenciones semánticas de GenAI de OTel para spans de agentes/herramientas/modelos emitidos desde el navegador.
devops
azure-ai-anomalydetector-java
microsoft
Cree aplicaciones de detección de anomalías con el SDK de Azure AI Anomaly Detector para Java. Úselo al implementar detección de anomalías univariadas/multivariadas, análisis de series temporales o monitoreo impulsado por IA.
development
azure-ai-language-conversations-py
microsoft
Implementa el reconocimiento del lenguaje conversacional (CLU) utilizando el SDK de Python azure-ai-language-conversations. Úsalo al trabajar con ConversationAnalysisClient para analizar la intención y las entidades de la conversación, crear funciones de NLP o integrar el reconocimiento del lenguaje en aplicaciones.
development
azure-ai-ml-py
microsoft
SDK v2 de Azure Machine Learning para Python. Úselo para áreas de trabajo de ML, trabajos, modelos, conjuntos de datos, cómputo y canalizaciones. Disparadores: "azure-ai-ml", "MLClient", "workspace", "model registry", "training jobs", "datasets".
development