LLM-based Named Entity Recognition using LangChain and LangGraph
Project description
pyNameEntityRecognition
pyNameEntityRecognition is a state-of-the-art Python package for LLM-based Named Entity Recognition (NER). It leverages LangChain for LLM orchestration and LangGraph for creating robust, agentic, and self-refining extraction workflows. The package is designed to be highly flexible, provider-agnostic, and easily extensible.
Key Features
- Dual-Path Extraction Engine: Choose between a high-throughput, streamlined LCEL pipeline for efficiency (
mode='lcel') or a stateful, self-correcting agentic workflow using LangGraph for maximum accuracy (mode='agentic'). - Dynamic Schema Definition: Define your entity extraction targets on the fly using simple Pydantic models. The engine automatically adapts its prompts and parsing to your schema.
- LLM Agnostic: Seamlessly switch between different LLM providers like OpenAI, Anthropic, Azure, and local models via Ollama. The engine accepts any pre-instantiated LangChain
BaseLanguageModelobject. - Automatic Chunking & Merging: For documents that exceed the LLM's context window, the engine automatically handles NLP-aware text chunking and intelligently merges the results from overlapping chunks.
- Anti-Hallucination: The agentic workflow includes a critical validation step that ensures every extracted entity span is an exact, verbatim match of the source text, significantly reducing hallucinations.
- Developer-Friendly: Comes with built-in observability features, including structured logging, seamless LangSmith integration, and a
displaCy-like visualizer for NER outputs.
Installation
Note on spaCy Model Dependency
This package requires the en_core_web_sm spaCy model for tokenization. Before using the package, please ensure you have downloaded this model by running:
python -m spacy download en_core_web_sm
This project uses Poetry for dependency management and packaging.
Windows Users: Some dependencies, like numpy, may require C++ compiler tools to be installed on your system. If you encounter installation errors related to a missing C++ compiler, please install the Microsoft C++ Build Tools.
-
Clone the repository:
git clone https://github.com/GowthamRao/py_name_entity_recognition.git cd py_name_entity_recognition
-
Install dependencies using Poetry: If you do not have Poetry installed, please follow the official installation instructions.
Once Poetry is installed, you can install the project dependencies:
poetry installThis will create a virtual environment and install all the necessary dependencies, including development dependencies.
-
Download spaCy Model: The package uses spaCy for robust tokenization. You'll need to download the default English model. You can do this using Poetry's
runcommand:poetry run python -m spacy download en_core_web_sm
Note: If you use a python version manager like
pyenvand switch to a new python version, you will need to run this command again to download the model for the new environment.
Configuration
LLM API Keys
The package uses python-dotenv to automatically load environment variables from a .env file in your project's root directory. Create a .env file to store your API keys:
# .env file
OPENAI_API_KEY="sk-..."
ANTHROPIC_API_KEY="sk-ant-..."
AZURE_OPENAI_API_KEY="..."
AZURE_OPENAI_ENDPOINT="..."
LangSmith Observability (Recommended)
To enable detailed tracing and debugging with LangSmith, add the following variables to your .env file:
# .env file
LANGCHAIN_TRACING_V2="true"
LANGCHAIN_API_KEY="ls__..."
LANGCHAIN_PROJECT="Your-Project-Name" # Optional: The project to log runs to
Quick Start
Here's a simple example of how to use the main extract_entities function.
import asyncio
from pydantic import BaseModel, Field
from typing import List
# Import the main extraction function
from py_name_entity_recognition import extract_entities
# Import the visualization utility
from py_name_entity_recognition.observability.visualization import display_biores
# 1. Define your extraction schema using Pydantic
class UserInfo(BaseModel):
"""Schema for extracting user information."""
Person: List[str] = Field(description="The full name of a person.")
Location: List[str] = Field(description="A city, state, or country.")
Company: List[str] = Field(description="The name of a company or organization.")
# 2. Define the text you want to process
text = "John Doe, a software engineer at Google, lives in New York. He is meeting with Jane Smith from Microsoft tomorrow."
# 3. Run the extraction
async def main():
# Use the default 'lcel' mode for fast extraction
print("--- Running in LCEL Mode ---")
conll_output = await extract_entities(
input_data=text,
schema=UserInfo
)
print(conll_output)
# Display the result as color-coded HTML (works best in Jupyter)
display_biores(conll_output)
# Get the output in a structured JSON format
print("\n--- Running with JSON Output ---")
json_output = await extract_entities(
input_data=text,
schema=UserInfo,
output_format="json"
)
print(json_output)
# Use the 'agentic' mode for higher accuracy and self-correction
print("\n--- Running in Agentic Mode ---")
agentic_output = await extract_entities(
input_data=text,
schema=UserInfo,
mode="agentic"
)
display_biores(agentic_output)
# Run the async main function
if __name__ == "__main__":
asyncio.run(main())
This example demonstrates the core functionality of the package, including schema definition, running different extraction modes, and formatting the output.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file py_name_entity_recognition-1.0.8.tar.gz.
File metadata
- Download URL: py_name_entity_recognition-1.0.8.tar.gz
- Upload date:
- Size: 31.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a903c2d2c4d152c113ef0955670d4d6b3db5bf5f6d42ad1c60fdb62e05cd51c1
|
|
| MD5 |
da591517a048a25c4ffdf769a3edf054
|
|
| BLAKE2b-256 |
4500362292d415bc2b04d76dd1e58538a21d65615904e01ee863ecebf93018cd
|
Provenance
The following attestation bundles were made for py_name_entity_recognition-1.0.8.tar.gz:
Publisher:
ci.yml on OHDSI/py_name_entity_recognition
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
py_name_entity_recognition-1.0.8.tar.gz -
Subject digest:
a903c2d2c4d152c113ef0955670d4d6b3db5bf5f6d42ad1c60fdb62e05cd51c1 - Sigstore transparency entry: 521567726
- Sigstore integration time:
-
Permalink:
OHDSI/py_name_entity_recognition@d828ab52fae46260d42fb49858af07ffc5729d26 -
Branch / Tag:
refs/tags/v1.0.8 - Owner: https://github.com/OHDSI
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@d828ab52fae46260d42fb49858af07ffc5729d26 -
Trigger Event:
push
-
Statement type:
File details
Details for the file py_name_entity_recognition-1.0.8-py3-none-any.whl.
File metadata
- Download URL: py_name_entity_recognition-1.0.8-py3-none-any.whl
- Upload date:
- Size: 36.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
61dde8f03a23a4c0bdea82d6e7e963ce5c6cc262a6578fce9109d9bb18c1f2be
|
|
| MD5 |
900c8089f5452d56493945d136e68247
|
|
| BLAKE2b-256 |
6815f814a0e2524eb17813454950e544c91bd0f1c27bd419b8ba6cca11039dc7
|
Provenance
The following attestation bundles were made for py_name_entity_recognition-1.0.8-py3-none-any.whl:
Publisher:
ci.yml on OHDSI/py_name_entity_recognition
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
py_name_entity_recognition-1.0.8-py3-none-any.whl -
Subject digest:
61dde8f03a23a4c0bdea82d6e7e963ce5c6cc262a6578fce9109d9bb18c1f2be - Sigstore transparency entry: 521567777
- Sigstore integration time:
-
Permalink:
OHDSI/py_name_entity_recognition@d828ab52fae46260d42fb49858af07ffc5729d26 -
Branch / Tag:
refs/tags/v1.0.8 - Owner: https://github.com/OHDSI
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@d828ab52fae46260d42fb49858af07ffc5729d26 -
Trigger Event:
push
-
Statement type: