nlp_analyze.py: entity extraction always fails with HTTP 400 (`languageCode` sent to the v1 endpoint)

Author: toquedemidasCreated Sep 26, 2026Updated Sep 26, 2026

Summary

In v2.4.0, scripts/nlp_analyze.py builds a single document object with "languageCode". That object goes to both the v2 annotateText call and the v1 documents:analyzeEntities call. languageCode is the v2 field name. The v1 API calls the field language and rejects unknown fields, so every request that includes entities fails with HTTP 400. Entities are in the default feature set, so the default command fails too.

Steps to reproduce

With a valid API key that has the Cloud Natural Language API enabled and billing on:

bash
python3 scripts/nlp_analyze.py --text "Anthropic builds Claude in San Francisco." --json

Output:

Error: NLP API request failed: 400 Client Error: Bad Request for url: https://language.googleapis.com/v1/documents:analyzeEntities

--url mode fails the same way. Google's error body (the script drops it) says:

Invalid JSON payload received. Unknown name "languageCode" at 'document': Cannot find field.

Sending the same v1 request directly shows the cause:

document field v1 analyzeEntities response
"languageCode": "pt" 400 Unknown name "languageCode" at 'document'
"language": "pt" 200 OK

--features sentiment,classify (v2 only) works, which confirms the key and project are set up correctly.

Secondary issue: language is hardcoded to en

analyze_text() defaults to language="en", and the CLI has no flag to change it. As a result:

  • non-English text is always labelled "language": "en" in the output;
  • with the field name fixed, v1 entity extraction would be forced to English for Portuguese, Spanish or other text.

When the field is omitted, the API detects the language itself (it returned pt-PT for Portuguese text in my tests).

Suggested fix

The full patch is included at the end of this issue. It was tested against the live API with auto-detected Portuguese, --language pt, auto-detected English and --url, using entities, sentiment and classify. Core change:

diff
-    language: str = "en",
+    language: Optional[str] = None,
 ...
+    # v2 (annotateText) names the field "languageCode"; v1 (analyzeEntities)
+    # names it "language" and rejects "languageCode" with HTTP 400.
     document = {
         "type": "PLAIN_TEXT",
         "content": text[:100000],  # API limit
-        "languageCode": language,
     }
+    if language:
+        document["languageCode"] = language
+    v1_document = {"type": "PLAIN_TEXT", "content": document["content"]}
+    if language:
+        v1_document["language"] = language
 ...
         body = {
-            "document": document,
+            "document": v1_document,
             "encodingType": "UTF8",
         }

The patch also:

  • adds a --language/-l CLI flag, which defaults to auto-detect;
  • passes language through analyze_url();
  • reports the language the API detected when none was given.

Suggested test

tests/test_nlp_analyze.py mocks both endpoints but never checks the request body, which is how this got through. Something like:

python
def test_v1_entities_body_uses_language_not_languageCode():
    # capture the json= passed to requests.post for NLP_V1_ENTITIES_ENDPOINT
    ...
    assert "languageCode" not in v1_body["document"]
    assert v2_body["document"].get("languageCode") in (None, "pt")

Environment

  • claude-seo v2.4.0 (latest release), manual install
  • macOS, Python 3.14
  • Google Cloud Natural Language API with an API key sent in the X-Goog-Api-Key header
Full patch against v2.4.0 scripts/nlp_analyze.py
diff
--- a/scripts/nlp_analyze.py	2026-09-26 17:11:39
+++ b/scripts/nlp_analyze.py	2026-09-26 23:02:08
@@ -60,7 +60,7 @@
     text: str,
     features: Optional[list] = None,
     api_key: Optional[str] = None,
-    language: str = "en",
+    language: Optional[str] = None,
 ) -> dict:
     """
     Analyze text using Google Cloud Natural Language API.
@@ -69,7 +69,7 @@
         text: Text content to analyze (max 1M characters).
         features: List of features: entities, sentiment, classify, moderate.
         api_key: Google API key.
-        language: Language code (default: en).
+        language: ISO language code (e.g. "pt", "en"). None lets the API detect it.
 
     Returns:
         Dictionary with entities, sentiment, categories, and moderation results.
@@ -92,18 +92,24 @@
     if features is None:
         features = ["entities", "sentiment", "classify"]
 
+    # v2 (annotateText) names the field "languageCode"; v1 (analyzeEntities)
+    # names it "language" and rejects "languageCode" with HTTP 400.
     document = {
         "type": "PLAIN_TEXT",
         "content": text[:100000],  # API limit
-        "languageCode": language,
     }
+    if language:
+        document["languageCode"] = language
+    v1_document = {"type": "PLAIN_TEXT", "content": document["content"]}
+    if language:
+        v1_document["language"] = language
 
     # Entities still use v1 because it returns Knowledge Graph metadata
     # and salience consistently. Other features stay on v2 annotateText.
     wants_entities = "entities" in features
     if wants_entities:
         body = {
-            "document": document,
+            "document": v1_document,
             "encodingType": "UTF8",
         }
         try:
@@ -128,6 +134,8 @@
 
             resp.raise_for_status()
             entity_data = resp.json()
+            if not language and entity_data.get("language"):
+                result["language"] = entity_data["language"]
         except requests.exceptions.RequestException as e:
             result["error"] = f"NLP API request failed: {redact_google_api_key(e)}"
             return result
@@ -241,6 +249,7 @@
     url: str,
     features: Optional[list] = None,
     api_key: Optional[str] = None,
+    language: Optional[str] = None,
 ) -> dict:
     """
     Fetch a URL's text content and analyze it.
@@ -289,7 +298,7 @@
     if not text or len(text) < 50:
         return {"error": "Extracted text too short for meaningful NLP analysis."}
 
-    result = analyze_text(text, features=features, api_key=api_key)
+    result = analyze_text(text, features=features, api_key=api_key, language=language)
     result["source_url"] = url
     result["extracted_text_length"] = len(text)
     return result
@@ -307,6 +316,10 @@
         help="Comma-separated features: entities, sentiment, classify, moderate (default: entities,sentiment,classify)",
     )
     parser.add_argument("--api-key", help="API key override")
+    parser.add_argument(
+        "--language", "-l",
+        help="ISO language code of the text, e.g. pt, en, es (default: auto-detect)",
+    )
     parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
 
     args = parser.parse_args()
@@ -318,9 +331,9 @@
     features = [f.strip() for f in args.features.split(",")]
 
     if args.url:
-        result = analyze_url(args.url, features=features, api_key=args.api_key)
+        result = analyze_url(args.url, features=features, api_key=args.api_key, language=args.language)
     else:
-        result = analyze_text(args.text, features=features, api_key=args.api_key)
+        result = analyze_text(args.text, features=features, api_key=args.api_key, language=args.language)
 
     if result.get("error"):
         print(f"Error: {result['error']}", file=sys.stderr)