=============== LIBRARY RULES =============== From library maintainers: - All endpoints accept POST with JSON body containing text field - Use multipart/form-data for file uploads - Authentication via Ocp-Apim-Subscription-Key header - All models run on CPU with ONNX optimization - Language detection supports 217 languages via fastText ### Customer Review Analysis (Python) Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Python example for analyzing customer reviews in bulk, calculating sentiment trends, extracting entities, and detecting languages. ```APIDOC ## Customer Review Analysis (Python) This Python function `analyze_reviews` processes a list of customer reviews to extract sentiment, entities, and language information, providing a summary of the analysis. ### Function Signature `def analyze_reviews(reviews: list[str]) -> dict` ### Parameters - **reviews** (list[str]): A list of customer review strings to analyze. ### Returns - (dict): A dictionary containing the analysis results, including total reviews, positive rate, top entities, and language distribution. ### Example Usage ```python import requests from collections import Counter BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} def analyze_reviews(reviews: list[str]) -> dict: """Analyze a batch of customer reviews.""" sentiments = [] all_entities = [] languages = Counter() for review in reviews: sent = requests.post(f"{BASE_URL}/sentiment", headers=HEADERS, json={"text": review}).json() ent = requests.post(f"{BASE_URL}/entities", headers=HEADERS, json={"text": review}).json() lang = requests.post(f"{BASE_URL}/language", headers=HEADERS, json={"text": review}).json() sentiments.append(sent["sentiment"]) all_entities.extend([e["text"] for e in ent["entities"] if e["label"] in ("ORG", "PER")]) languages[lang["language"]] += 1 positive_rate = sentiments.count("positive") / len(sentiments) * 100 entity_freq = Counter(all_entities).most_common(10) return { "total_reviews": len(reviews), "positive_rate": f"{positive_rate:.1f}%", "top_entities": entity_freq, "languages": dict(languages), } ``` ``` -------------------------------- ### NLP API Endpoints (curl) Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Provides examples of how to call various NLP API endpoints using curl commands. ```APIDOC ## NLP API Endpoints (curl) This section provides `curl` commands to interact with different NLP API endpoints. Replace `YOUR_KEY` with your actual API key. ### Base URL `BASE="https://apim-ai-apis.azure-api.net/v1/nlp"` ### Endpoints #### Toxicity **Method:** POST **Endpoint:** `/toxicity` **Description:** Detects toxicity in a given text. **Request Body:** `{"text": "You are wonderful!"}` ```bash curl -s -X POST "$BASE/toxicity" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "You are wonderful!"}' | python3 -m json.tool ``` #### Sentiment Analysis **Method:** POST **Endpoint:** `/sentiment` **Description:** Analyzes the sentiment of a given text. **Request Body:** `{"text": "Best product ever!"}` ```bash curl -s -X POST "$BASE/sentiment" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Best product ever!"}' | python3 -m json.tool ``` #### Entity Recognition **Method:** POST **Endpoint:** `/entities` **Description:** Extracts named entities from a given text. **Request Body:** `{"text": "Satya Nadella leads Microsoft from Redmond."}` ```bash curl -s -X POST "$BASE/entities" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Satya Nadella leads Microsoft from Redmond."}' | python3 -m json.tool ``` #### Personally Identifiable Information (PII) Detection **Method:** POST **Endpoint:** `/pii` **Description:** Detects Personally Identifiable Information (PII) in a given text. **Request Body:** `{"text": "Email me at test@test.com, SSN 123-45-6789"}` ```bash curl -s -X POST "$BASE/pii" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Email me at test@test.com, SSN 123-45-6789"}' | python3 -m json.tool ``` #### Language Detection **Method:** POST **Endpoint:** `/language` **Description:** Detects the language of a given text. **Request Body:** `{"text": "Bonjour le monde"}` ```bash curl -s -X POST "$BASE/language" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Bonjour le monde"}' | python3 -m json.tool ``` #### Health Check **Method:** GET **Endpoint:** `/health` **Description:** Checks the health status of the NLP API. ```bash curl -s "$BASE/health" -H "Authorization: Bearer $KEY" | python3 -m json.tool ``` ``` -------------------------------- ### Named Entity Recognition (NER) Response Example Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt The NER response lists detected entities, including their text, label (PER, ORG, LOC, MISC), start and end positions, and a confidence score. ```json { "text": "Your text to analyze", "entities": [ {"text": "Entity Name", "label": "PER", "start": 0, "end": 11, "score": 0.9987} ], "entity_count": 1 } ``` -------------------------------- ### Content Moderation for Chat Applications (Python) Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Python example demonstrating how to use the NLP API for real-time content moderation in chat applications, combining toxicity and PII detection. ```APIDOC ## Content Moderation for Chat Applications (Python) This Python function `should_allow_message` uses the NLP API to moderate user messages in real-time, checking for toxicity and sensitive PII. ### Function Signature `def should_allow_message(message: str) -> tuple[bool, str]` ### Parameters - **message** (str): The user message to moderate. ### Returns - (tuple[bool, str]): A tuple containing a boolean indicating if the message is allowed, and a string reason for disallowing if applicable. ### Example Usage ```python import requests BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} def should_allow_message(message: str) -> tuple[bool, str]: """Returns (allowed, reason) for a chat message.""" toxicity = requests.post(f"{BASE_URL}/toxicity", headers=HEADERS, json={"text": message}).json() if toxicity["scores"]["severe_toxic"] > 0.3: return False, "severe_toxic" if toxicity["scores"]["threat"] > 0.3: return False, "threat" if toxicity["is_toxic"]: return False, toxicity["max_category"] pii = requests.post(f"{BASE_URL}/pii", headers=HEADERS, json={"text": message}).json() if pii["pii_found"]: pii_types = [e["type"] for e in pii["entities"]] if "ssn" in pii_types or "credit_card" in pii_types: return False, f"sensitive_pii: {pii_types}" return True, "allowed" ``` ``` -------------------------------- ### Python: Moderate Content Pipeline Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Use this function to run a content moderation pipeline that checks for toxicity, PII, and language. Ensure you have a valid API key and the 'requests' library installed. ```python import requests BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} def moderate_content(text: str) -> dict: """Run content moderation pipeline: toxicity + PII + language.""" toxicity = requests.post(f"{BASE_URL}/toxicity", headers=HEADERS, json={"text": text}).json() pii = requests.post(f"{BASE_URL}/pii", headers=HEADERS, json={"text": text}).json() language = requests.post(f"{BASE_URL}/language", headers=HEADERS, json={"text": text}).json() return { "text": text, "language": language["language"], "is_toxic": toxicity["is_toxic"], "toxic_categories": {k: v for k, v in toxicity["scores"].items() if v > 0.5}, "has_pii": pii["pii_found"], "pii_types": [e["type"] for e in pii.get("entities", [])], "action": "block" if toxicity["is_toxic"] else ("redact" if pii["pii_found"] else "allow") } result = moderate_content("Please contact John at john@example.com for details") print(f"Action: {result['action']}") print(f"Language: {result['language']}") print(f"PII found: {result['pii_types']}") ``` -------------------------------- ### Analyze Sentiment of Reviews using Python Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt This Python snippet analyzes the sentiment of multiple reviews concurrently using ThreadPoolExecutor. Ensure 'requests' is installed and replace 'YOUR_KEY' with your API key. ```python import requests from concurrent.futures import ThreadPoolExecutor BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} reviews = [ "Absolutely love this! Best purchase I've ever made.", "Terrible quality. Completely disappointed.", "It's okay, nothing special but gets the job done.", "Amazing customer support, they went above and beyond!", "Would not recommend to anyone. Total waste of money.", ] def analyze(text): return requests.post(f"{BASE_URL}/sentiment", headers=HEADERS, json={"text": text}).json() with ThreadPoolExecutor(max_workers=5) as pool: results = list(pool.map(analyze, reviews)) for text, r in zip(reviews, results): icon = "+" if r["sentiment"] == "positive" else "-" print(f"[{icon} {r['confidence']:.3f}] {text}") # [+ 0.985] Absolutely love this! Best purchase I've ever made. # [- 0.978] Terrible quality. Completely disappointed. # [+ 0.612] It's okay, nothing special but gets the job done. # [+ 0.991] Amazing customer support, they went above and beyond! # [- 0.982] Would not recommend to anyone. Total waste of money. ``` -------------------------------- ### Service Health Check Response Example Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt The health check endpoint returns the status of the service and the load status of each NLP model. ```json { "status": "healthy", "models": { "toxicity": "loaded", "sentiment": "loaded", "ner": "loaded", "pii": "loaded", "language": "loaded" } } ``` -------------------------------- ### Personally Identifiable Information (PII) Detection Response Example Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt The PII detection response indicates if PII was found and lists the detected entities with their type, value, and character positions. ```json { "text": "Your text to analyze", "pii_found": true, "entities": [ {"type": "email", "value": "user@example.com", "start": 10, "end": 26} ], "pii_count": 1 } ``` -------------------------------- ### Toxicity Detection Response Example Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt The response from the toxicity endpoint details whether the text is toxic and provides scores for specific categories like toxic, severe_toxic, obscene, threat, insult, and identity_hate. ```json { "text": "Your text to analyze", "is_toxic": false, "scores": { "toxic": 0.0012, "severe_toxic": 0.0001, "obscene": 0.0005, "threat": 0.0002, "insult": 0.0008, "identity_hate": 0.0001 }, "max_score": 0.0012, "max_category": "toxic" } ``` -------------------------------- ### Language Detection Response Example Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt The language detection response includes the detected language code, its confidence score, and the full language name. ```json { "text": "Your text to analyze", "language": "en", "confidence": 0.9876, "language_name": "English" } ``` -------------------------------- ### Toxicity Detection Request Example Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Send text to the toxicity endpoint to detect toxic content across six categories. The response includes a boolean indicating overall toxicity and detailed scores per category. ```json { "text": "Your text to analyze" } ``` -------------------------------- ### JavaScript: Express.js Content Moderation Middleware Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Implement Express.js middleware to moderate incoming messages for toxicity and PII before processing. This example uses fetch for API calls and requires an API key. ```javascript import express from "express"; const app = express(); app.use(express.json()); const NLP_BASE = "https://apim-ai-apis.azure-api.net/v1/nlp"; const API_KEY = "YOUR_KEY"; const headers = { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }; // Moderation middleware async function moderateContent(req, res, next) { const text = req.body.message || req.body.content || req.body.text; if (!text) return next(); try { const [toxicityRes, piiRes] = await Promise.all([ fetch(`${NLP_BASE}/toxicity`, { method: "POST", headers, body: JSON.stringify({ text }), }), fetch(`${NLP_BASE}/pii`, { method: "POST", headers, body: JSON.stringify({ text }), }), ]); const toxicity = await toxicityRes.json(); const pii = await piiRes.json(); if (toxicity.is_toxic) { return res .status(422) .json({ error: "Content blocked", category: toxicity.max_category }); } req.moderation = { is_toxic: false, has_pii: pii.pii_found, pii_types: pii.entities?.map((e) => e.type) || [] }; next(); } catch (err) { next(); // Fail open — log error but don't block } } app.post("/api/messages", moderateContent, (req, res) => { res.json({ status: "sent", moderation: req.moderation }); }); app.listen(3000); ``` -------------------------------- ### curl: All NLP API Endpoints Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Demonstrates how to call various NLP API endpoints using curl, including toxicity, sentiment, entities, PII, language detection, and health checks. Ensure to replace YOUR_KEY with your actual API key. ```bash BASE="https://apim-ai-apis.azure-api.net/v1/nlp" KEY="YOUR_KEY" # Toxicity curl -s -X POST "$BASE/toxicity" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "You are wonderful!"}' | python3 -m json.tool # Sentiment curl -s -X POST "$BASE/sentiment" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Best product ever!"}' | python3 -m json.tool # Entities curl -s -X POST "$BASE/entities" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Satya Nadella leads Microsoft from Redmond."}' | python3 -m json.tool # PII curl -s -X POST "$BASE/pii" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Email me at test@test.com, SSN 123-45-6789"}' | python3 -m json.tool # Language curl -s -X POST "$BASE/language" \ -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" \ -d '{"text": "Bonjour le monde"}' | python3 -m json.tool # Health curl -s "$BASE/health" -H "Authorization: Bearer $KEY" | python3 -m json.tool ``` -------------------------------- ### GET /v1/nlp/health Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms.txt Checks the health status of the NLP service. ```APIDOC ## GET /v1/nlp/health ### Description Provides a health check for the Brainiall NLP API service. ### Method GET ### Endpoint https://apim-ai-apis.azure-net/v1/nlp/health ### Response #### Success Response (200) - **status** (string) - The health status of the service (e.g., 'healthy', 'unhealthy'). ### Response Example ```json { "status": "healthy" } ``` ``` -------------------------------- ### Batch Analysis with Rate Limiting (JavaScript) Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Demonstrates how to perform batch analysis on a list of texts with built-in rate limiting using JavaScript. ```APIDOC ## JavaScript: Batch Analysis with Rate Limiting This function `batchAnalyze` allows for processing multiple text inputs in batches, applying a concurrency limit and a delay between batches to manage API rate limits. ### Function Signature `async function batchAnalyze(texts, endpoint, concurrency = 5)` ### Parameters - **texts** (Array): An array of strings, where each string is a text to be analyzed. - **endpoint** (string): The specific NLP API endpoint to call (e.g., "sentiment", "toxicity"). - **concurrency** (number, optional): The maximum number of concurrent requests to make per batch. Defaults to 5. ### Returns - (Array): An array of JSON objects, where each object is the result of an analysis for a single text input. ### Example Usage ```javascript const BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp"; const API_KEY = "YOUR_KEY"; async function batchAnalyze(texts, endpoint, concurrency = 5) { const results = []; for (let i = 0; i < texts.length; i += concurrency) { const batch = texts.slice(i, i + concurrency); const batchResults = await Promise.all( batch.map(async (text) => { const response = await fetch(`${BASE_URL}/${endpoint}`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }, body: JSON.stringify({ text }), }); return response.json(); }) ); results.push(...batchResults); if (i + concurrency < texts.length) { await new Promise((resolve) => setTimeout(resolve, 100)); } } return results; } // Analyze 100 customer reviews const reviews = ["Great product!", "Terrible service", /* ... */]; const sentiments = await batchAnalyze(reviews, "sentiment", 10); const positive = sentiments.filter((r) => r.sentiment === "positive").length; console.log(`Positive: ${positive}/${sentiments.length} (${((positive / sentiments.length) * 100).toFixed(1)}%)`); ``` ``` -------------------------------- ### GET /health Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Checks the health status of the NLP service and reports the load status of each model. ```APIDOC ## GET /health ### Description Service health check. Returns model load status. ### Method GET ### Endpoint /v1/nlp/health ### Response #### Success Response (200) - **status** (string) - The overall health status of the service (e.g., 'healthy'). - **models** (object) - An object detailing the load status of each NLP model: - **toxicity** (string) - Load status of the toxicity model. - **sentiment** (string) - Load status of the sentiment model. - **ner** (string) - Load status of the NER model. - **pii** (string) - Load status of the PII detection model. - **language** (string) - Load status of the language detection model. #### Response Example ```json { "status": "healthy", "models": { "toxicity": "loaded", "sentiment": "loaded", "ner": "loaded", "pii": "loaded", "language": "loaded" } } ``` ``` -------------------------------- ### Async NLP Analysis with Python Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Run multiple NLP analyses concurrently for improved performance. Requires httpx and asyncio. Ensure your API key is set in HEADERS. ```python import asyncio import httpx BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} async def analyze_text_async(text: str) -> dict: """Run all NLP analyses concurrently for maximum speed.""" async with httpx.AsyncClient() as client: tasks = [ client.post(f"{BASE_URL}/toxicity", headers=HEADERS, json={"text": text}), client.post(f"{BASE_URL}/sentiment", headers=HEADERS, json={"text": text}), client.post(f"{BASE_URL}/entities", headers=HEADERS, json={"text": text}), client.post(f"{BASE_URL}/pii", headers=HEADERS, json={"text": text}), client.post(f"{BASE_URL}/language", headers=HEADERS, json={"text": text}), ] responses = await asyncio.gather(*tasks) results = [r.json() for r in responses] return { "text": text, "language": results[4]["language"], "sentiment": results[1]["sentiment"], "sentiment_confidence": results[1]["confidence"], "is_toxic": results[0]["is_toxic"], "toxic_max_category": results[0]["max_category"], "toxic_max_score": results[0]["max_score"], "entities": results[2]["entities"], "entity_count": results[2]["entity_count"], "pii_found": results[3]["pii_found"], "pii_entities": results[3].get("entities", []), } async def batch_analyze_async(texts: list[str]) -> list[dict]: """Analyze multiple texts concurrently.""" tasks = [analyze_text_async(text) for text in texts] return await asyncio.gather(*tasks) # Usage async def main(): texts = [ "The new iPhone release exceeded expectations with record sales.", "Contact support@company.com or call 555-123-4567 for help.", "Le president Macron a visite la Tour Eiffel a Paris.", ] results = await batch_analyze_async(texts) for r in results: print(f"[{r['language']}] {r['sentiment']} ({r['sentiment_confidence']:.2f}) | " f"Toxic: {r['is_toxic']} | Entities: {r['entity_count']} | PII: {r['pii_found']}") asyncio.run(main()) ``` -------------------------------- ### Detect PII using cURL Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/README.md This cURL command demonstrates how to detect PII in text. Replace 'YOUR_KEY' with your actual API key. ```bash curl -X POST https://apim-ai-apis.azure-api.net/v1/nlp/pii \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_KEY" \ -d '{"text": "Contact me at john@example.com or call 555-123-4567. My SSN is 123-45-6789."}' ``` -------------------------------- ### Sentiment Analysis Response Example Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt The sentiment analysis response provides the classified sentiment (positive/negative) and a confidence score, along with detailed scores for both positive and negative classifications. ```json { "text": "Your text to analyze", "sentiment": "positive", "confidence": 0.9847, "scores": { "positive": 0.9847, "negative": 0.0153 } } ``` -------------------------------- ### Replace LLM-based NLP with Brainiall NLP for Sentiment Analysis Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Compares the cost and latency of using GPT-4o for sentiment analysis versus Brainiall NLP. Brainiall NLP is 2,500x cheaper and 10x faster. ```python # Before: GPT-4o for sentiment ($2,500/1M) from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Classify sentiment as positive or negative: 'Great product!'"}], ) # Costs ~$0.0025 per request, 500ms+ latency ``` ```python # After: Brainiall NLP ($0.001 per request, <50ms latency) import requests result = requests.post( "https://apim-ai-apis.azure-api.net/v1/nlp/sentiment", headers={"Authorization": "Bearer YOUR_KEY"}, json={"text": "Great product!"} ).json() # 2,500x cheaper, 10x faster ``` -------------------------------- ### Detect Language of Text (Python) Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt Use this snippet to detect the language of multiple text inputs. Ensure you have the 'requests' library installed and replace 'YOUR_KEY' with your actual API key. ```python import requests BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} texts = [ "Hello, how are you doing today?", "Bonjour, comment allez-vous aujourd'hui?", "Hallo, wie geht es Ihnen heute?", "Hola, ¿cómo estás hoy?", "Ciao, come stai oggi?", "Olá, como você está hoje?", "Привет, как дела сегодня?", "こんにちは、今日はお元気ですか?", "안녕하세요, 오늘 어떠세요?", "مرحبا، كيف حالك اليوم؟", ] for text in texts: result = requests.post(f"{BASE_URL}/language", headers=HEADERS, json={"text": text}).json() print(f"[{result['language']:3s} {result['confidence']:.3f}] {result['language_name']:12s} | {text[:45]}") # [en 0.988] English | Hello, how are you doing today? # [fr 0.991] French | Bonjour, comment allez-vous aujourd'hui? # [de 0.985] German | Hallo, wie geht es Ihnen heute? # [es 0.980] Spanish | Hola, ¿cómo estás hoy? # [it 0.987] Italian | Ciao, come stai oggi? # [pt 0.983] Portuguese | Olá, como você está hoje? # [ru 0.992] Russian | Привет, как дела сегодня? # [ja 0.996] Japanese | こんにちは、今日はお元気ですか? # [ko 0.994] Korean | 안녕하세요, 오늘 어떠세요? # [ar 0.989] Arabic | مرحبا، كيف حالك اليوم? ``` -------------------------------- ### Run Full NLP Analysis Concurrently Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt Uses `asyncio` and `httpx` to run all five NLP endpoints concurrently against a single text. Ideal for comprehensive document analysis or per-message audit trails. ```python import asyncio import httpx BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} async def full_analysis(text: str) -> dict: async with httpx.AsyncClient() as client: endpoints = ["toxicity", "sentiment", "entities", "pii", "language"] tasks = [ client.post(f"{BASE_URL}/{ep}", headers=HEADERS, json={"text": text}) for ep in endpoints ] responses = await asyncio.gather(*tasks) toxicity, sentiment, entities, pii, language = [r.json() for r in responses] return { "text": text, "language": language["language"], "language_name": language["language_name"], "sentiment": sentiment["sentiment"], "sentiment_confidence": sentiment["confidence"], "is_toxic": toxicity["is_toxic"], "toxic_max_category": toxicity["max_category"], "toxic_max_score": toxicity["max_score"], "entities": [{"text": e["text"], "label": e["label"]} for e in entities["entities"]], "entity_count": entities["entity_count"], "pii_found": pii["pii_found"], "pii_types": [e["type"] for e in pii.get("entities", [])], } text = "John Smith from Amazon in Seattle emailed john@amazon.com — this new AI product is incredible!" result = asyncio.run(full_analysis(text)) print(f"Language : {result['language_name']} ({result['language']})") print(f"Sentiment : {result['sentiment']} ({result['sentiment_confidence']:.3f})") print(f"Toxic : {result['is_toxic']} (max: {result['toxic_max_category']} {result['toxic_max_score']:.4f})") print(f"Entities : {result['entity_count']} — {result['entities']}") print(f"PII : {result['pii_found']} — {result['pii_types']}") # Language : English (en) # Sentiment : positive (0.978) # Toxic : False (max: toxic 0.0018) # Entities : 3 — [{'text': 'John Smith', 'label': 'PER'}, {'text': 'Amazon', 'label': 'ORG'}, {'text': 'Seattle', 'label': 'LOC'}] # PII : True — ['email'] ``` -------------------------------- ### Apify MCP Server Configuration Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/README.md Configuration for integrating Brainiall NLP with Apify using MCP. Replace YOUR_APIFY_TOKEN with your actual token. ```json { "mcpServers": { "brainiall-nlp-apify": { "url": "https://HkExWxGM8fNldLxd6.apify.actor/mcp?token=YOUR_APIFY_TOKEN" } } } ``` -------------------------------- ### Detect Toxicity with Python Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/README.md Use this endpoint to detect toxic content across six categories. Requires authentication with a Bearer token. ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/nlp/toxicity", headers={"Authorization": "Bearer YOUR_KEY"}, json={"text": "You are an amazing person and I appreciate your work!"} ) result = response.json() print(result) ``` -------------------------------- ### Detect PII with cURL Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt This cURL command demonstrates how to detect PII in a given text. The output includes the type, value, and character offsets of the detected PII. ```bash curl -s -X POST "https://apim-ai-apis.azure-api.net/v1/nlp/pii" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_KEY" \ -d '{"text": "Email me at alice@company.com or call 555-123-4567. SSN: 123-45-6789."}' | python3 -m json.tool ``` -------------------------------- ### MCP Server Configuration for Brainiall NLP Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/README.md Configure MCP clients like Claude Desktop or Cursor to use Brainiall NLP. This JSON snippet defines the server URL and necessary headers. ```json { "mcpServers": { "brainiall-nlp": { "url": "https://apim-ai-apis.azure-api.net/mcp/nlp/mcp", "headers": { "Accept": "application/json, text/event-stream" } } } } ``` -------------------------------- ### Detect Toxicity in Text using Python Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt Use this snippet to classify text across six toxicity categories. Ensure you have the 'requests' library installed and replace 'YOUR_KEY' with your actual API key. ```python import requests BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} texts = [ "You are such a wonderful person!", "I hate everything about this terrible product", "The weather is nice today", ] for text in texts: result = requests.post(f"{BASE_URL}/toxicity", headers=HEADERS, json={"text": text}).json() status = "TOXIC" if result["is_toxic"] else "SAFE" print(f"[{status}] {text}") print(f" Max category: {result['max_category']} = {result['max_score']:.4f}") print(f" All scores: {result['scores']}") # [SAFE ] You are such a wonderful person! # Max category: toxic = 0.0012 # All scores: {'toxic': 0.0012, 'severe_toxic': 0.0001, 'obscene': 0.0005, 'threat': 0.0002, 'insult': 0.0008, 'identity_hate': 0.0001} # [TOXIC] I hate everything about this terrible product # Max category: toxic = 0.8734 # All scores: {'toxic': 0.8734, 'severe_toxic': 0.0012, ...} ``` -------------------------------- ### Full NLP Pipeline Analysis Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/README.md Execute all available NLP analyses (toxicity, sentiment, entities, PII, language) on a single text. Requires a valid API key. ```python import requests import json BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp" HEADERS = { "Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json" } text = "John Smith from Microsoft emailed john@microsoft.com saying the new product launch was fantastic!" # Run all analyses endpoints = ["toxicity", "sentiment", "entities", "pii", "language"] results = {} for endpoint in endpoints: response = requests.post( f"{BASE_URL}/{endpoint}", headers=HEADERS, json={"text": text} ) results[endpoint] = response.json() # Print summary print(f"Text: {text}") print(f"Language: {results['language']['language']} ({results['language']['confidence']:.4f})") print(f"Sentiment: {results['sentiment']['sentiment']} ({results['sentiment']['confidence']:.4f})") print(f"Toxic: {results['toxicity']['is_toxic']} (max score: {results['toxicity']['max_score']:.4f})") print(f"Entities: {results['entities']['entity_count']} found") for e in results['entities']['entities']: print(f" - {e['text']} [{e['label']}]") print(f"PII: {results['pii']['pii_count']} found") for p in results['pii']['entities']: print(f" - {p['type']}: {p['value']}") ``` -------------------------------- ### LangChain NLP Tools Integration Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Integrate Brainiall NLP services as LangChain tools for use in AI agents. Requires requests for synchronous API calls. ```python from langchain_core.tools import tool from langchain_brainiall import ChatBrainiall from langgraph.prebuilt import create_react_agent import requests NLP_BASE = "https://apim-ai-apis.azure-api.net/v1/nlp" NLP_HEADERS = {"Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json"} @tool def analyze_sentiment(text: str) -> str: """Analyze the sentiment of text. Returns positive or negative with confidence.""" result = requests.post(f"{NLP_BASE}/sentiment", headers=NLP_HEADERS, json={"text": text}).json() return f"Sentiment: {result['sentiment']} (confidence: {result['confidence']:.2f})" @tool def detect_toxicity(text: str) -> str: """Check if text contains toxic content across 6 categories.""" result = requests.post(f"{NLP_BASE}/toxicity", headers=NLP_HEADERS, json={"text": text}).json() if result["is_toxic"]: return f"TOXIC: {result['max_category']} (score: {result['max_score']:.2f})" return f"Not toxic. Max score: {result['max_score']:.3f} ({result['max_category']})" @tool def extract_entities(text: str) -> str: """Extract named entities (persons, organizations, locations) from text.""" result = requests.post(f"{NLP_BASE}/entities", headers=NLP_HEADERS, json={"text": text}).json() if not result["entities"]: return "No entities found." entities = [f"{e['text']} ({e['label']})" for e in result["entities"]] return f"Found {len(entities)} entities: {', '.join(entities)}" @tool def detect_pii(text: str) -> str: """Detect personally identifiable information (emails, phones, SSNs, credit cards).""" result = requests.post(f"{NLP_BASE}/pii", headers=NLP_HEADERS, json={"text": text}).json() if not result["pii_found"]: return "No PII detected." pii_items = [f"{e['type']}: {e['value']}" for e in result["entities"]] return f"PII found: {', '.join(pii_items)}" @tool def detect_language(text: str) -> str: """Detect the language of text. Supports 217 languages.""" result = requests.post(f"{NLP_BASE}/language", headers=NLP_HEADERS, json={"text": text}).json() return f"Language: {result['language_name']} ({result['language']}) - confidence: {result['confidence']:.2f}" # Create an AI agent with NLP tools llm = ChatBrainiall(model="claude-sonnet-4-6") agent = create_react_agent(llm, [analyze_sentiment, detect_toxicity, extract_entities, detect_pii, detect_language]) result = agent.invoke({"messages": [("human", "Analyze this customer review for sentiment and any PII: 'John Smith loved the product. Contact him at john@example.com'")]}) for msg in result["messages"]: print(f"{msg.type}: {msg.content}") ``` -------------------------------- ### Analyze Sentiment using cURL Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt This cURL command shows how to perform sentiment analysis on a given text. Remember to replace 'YOUR_KEY' with your valid API key. ```bash curl -s -X POST "https://apim-ai-apis.azure-api.net/v1/nlp/sentiment" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_KEY" \ -d '{"text": "This product exceeded all my expectations!"}' | python3 -m json.tool # { # "text": "This product exceeded all my expectations!", # "sentiment": "positive", # "confidence": 0.9847, # "scores": { "positive": 0.9847, "negative": 0.0153 } # } ``` -------------------------------- ### GET /health — Service health check Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt Returns the operational status and model load state for all five NLP models. Use this to verify service availability before running batch jobs or as a liveness probe in containerized deployments. ```APIDOC ## GET /health — Service health check ### Description Returns the operational status and model load state for all five NLP models. Use this to verify service availability before running batch jobs or as a liveness probe in containerized deployments. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The overall operational status of the service (e.g., "healthy"). - **models** (object) - An object containing the load state of each NLP model. - **toxicity** (string) - Load state of the toxicity model. - **sentiment** (string) - Load state of the sentiment model. - **ner** (string) - Load state of the NER model. - **pii** (string) - Load state of the PII model. - **language** (string) - Load state of the language model. #### Response Example ```json { "status": "healthy", "models": { "toxicity": "loaded", "sentiment": "loaded", "ner": "loaded", "pii": "loaded", "language": "loaded" } } ``` ``` -------------------------------- ### JavaScript: Full NLP Analysis Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Perform comprehensive NLP analysis including toxicity, sentiment, entities, PII, and language detection using JavaScript's fetch API. Requires an API key. ```javascript const BASE_URL = "https://apim-ai-apis.azure-api.net/v1/nlp"; const HEADERS = { "Content-Type": "application/json", Authorization: "Bearer YOUR_KEY", }; async function analyzeText(text) { const endpoints = ["toxicity", "sentiment", "entities", "pii", "language"]; const results = {}; await Promise.all( endpoints.map(async (endpoint) => { const response = await fetch(`${BASE_URL}/${endpoint}`, { method: "POST", headers: HEADERS, body: JSON.stringify({ text }), }); results[endpoint] = await response.json(); }) ); return { text, language: results.language.language, sentiment: results.sentiment.sentiment, confidence: results.sentiment.confidence, is_toxic: results.toxicity.is_toxic, entity_count: results.entities.entity_count, pii_found: results.pii.pii_found, }; } const analysis = await analyzeText( "John from Google in NYC emailed john@google.com — great product!" ); console.log(JSON.stringify(analysis, null, 2)); ``` -------------------------------- ### Migrate from AWS Comprehend to Brainiall NLP Sentiment Analysis Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/llms-full.txt Replaces AWS Comprehend API calls with Brainiall NLP for sentiment analysis. Offers a 500x cost reduction. ```python # Before: AWS Comprehend ($500/1M requests) import boto3 comprehend = boto3.client("comprehend") result = comprehend.detect_sentiment(Text="Great product!", LanguageCode="en") print(result["Sentiment"]) ``` ```python # After: Brainiall NLP ($1/1M requests — 500x cheaper) import requests result = requests.post( "https://apim-ai-apis.azure-api.net/v1/nlp/sentiment", headers={"Authorization": "Bearer YOUR_KEY"}, json={"text": "Great product!"} ).json() print(result["sentiment"]) ``` -------------------------------- ### Detect Toxicity in Text using cURL Source: https://context7.com/fasuizu-br/brainiall-nlp-api/llms.txt This cURL command demonstrates how to send a POST request to the toxicity detection endpoint. Replace 'YOUR_KEY' with your API key. ```bash curl -s -X POST "https://apim-ai-apis.azure-api.net/v1/nlp/toxicity" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_KEY" \ -d '{"text": "You are such a wonderful person!"}' | python3 -m json.tool # { # "text": "You are such a wonderful person!", # "is_toxic": false, # "scores": { "toxic": 0.0012, "severe_toxic": 0.0001, ... }, # "max_score": 0.0012, # "max_category": "toxic" # } ``` -------------------------------- ### Extract Entities using cURL Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/README.md This cURL command demonstrates how to extract named entities from text using the API. Ensure you replace 'YOUR_KEY' with your actual API key. ```bash curl -X POST https://apim-ai-apis.azure-api.net/v1/nlp/entities \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_KEY" \ -d '{"text": "Elon Musk announced that Tesla will open a new factory in Berlin, Germany next year."}' ``` -------------------------------- ### Detect Language using cURL Source: https://github.com/fasuizu-br/brainiall-nlp-api/blob/main/README.md This cURL command demonstrates how to detect the language of a given text. Replace 'YOUR_KEY' with your valid API key. ```bash curl -X POST https://apim-ai-apis.azure-api.net/v1/nlp/language \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_KEY" \ -d '{"text": "Bonjour, comment allez-vous?"}' ```