Volver al ranking

eyurtsev/kor

Pythoneyurtsev.github.io/kor/

LLM(😽)

information-extractionllmnatural-languagenatural-language-processingnatural-language-understanding
Crecimiento de estrellas
Estrellas
1.7k
Forks
94
Crecimiento semanal
Issues
22
5001k1.5k
mar 2023abr 2024jun 2025jul 2026
ArtefactosPyPIpip install kor
README

Unit Tests Test Docs Release Notes Downloads Open Issues

[!WARNING] If you're using a chat model that supports a tool calling API, you should probably be using the chat models' tool calling API instead of Kor!

Kor is best suited for old style LLMs that did not have a chat interface and did not support tool calling.

Read the tool calling guide in LangChain for more details.

Please refer to the chat model integration table for a list of chat models that support native tool calling.

Kor

This is a half-baked prototype that "helps" you extract structured data from text using LLMs 🧩.

Specify the schema of what should be extracted and provide some examples.

Kor will generate a prompt, send it to the specified LLM and parse out the output.

You might even get results back.

So yes – it’s just another wrapper on top of LLMs with its own flavor of abstractions. 😸

See documentation.

Integrated with the LangChain framework 😽💗 🦜🔗.

Kor vs. LangChain

There are 3 different approaches for extracting information using LLMs:

  1. prompt based/parsing
  2. function/tool calling
  3. JSON mode

Please see the LangChain extraction use case docs for an overview.

Kor has a pretty good implementation of the parsing approach. The approach works with all good-enough LLMs regardless of whether they support function/tool calling or JSON modes.

Extraction quality is principally driven by providing good reference examples and good schema documentation.

Please see guidelines here and here.

Version 1.0.0 Release

  • kor compatible with both pydantic v2 and v1.
  • pydantic v2 had significant breaking changes w/ respect to v1, kor major version bump was used as a precaution.

Main things to watch out for:

  1. Use a default value for any Optional fields if using pydantic v2 for validation.
class MusicRequest(BaseModel):
    song: Optional[List[str]] = Field(
        default=None,
        description="The song(s) that the user would like to be played."
    )
  1. Kor schema is typed checked using pydantic. Pydantic v2 is stricter, and may catch issues that were hiding in existing user code that was using the kor library.

  2. Serialization has not yet been implemented with pydantic v2.

Kor style schema

from langchain.chat_models import ChatOpenAI
from kor import create_extraction_chain, Object, Text

llm = ChatOpenAI(
    model_name="gpt-3.5-turbo",
    temperature=0,
    max_tokens=2000,
    model_kwargs = {
        'frequency_penalty':0,
        'presence_penalty':0,
        'top_p':1.0
    }
)

schema = Object(
    id="player",
    description=(
        "User is controlling a music player to select songs, pause or start them or play"
        " music by a particular artist."
    ),
    attributes=[
        Text(
            id="song",
            description="User wants to play this song",
            examples=[],
            many=True,
        ),
        Text(
            id="album",
            description="User wants to play this album",
            examples=[],
            many=True,
        ),
        Text(
            id="artist",
            description="Music by the given artist",
            examples=[("Songs by paul simon", "paul simon")],
            many=True,
        ),
        Text(
            id="action",
            description="Action to take one of: `play`, `stop`, `next`, `previous`.",
            examples=[
                ("Please stop the music", "stop"),
                ("play something", "play"),
                ("play a song", "play"),
                ("next song", "next"),
            ],
        ),
    ],
    many=False,
)

chain = create_extraction_chain(llm, schema, encoder_or_encoder_class='json')
chain.invoke("play songs by paul simon and led zeppelin and the doors")['data']
{'player': {'artist': ['paul simon', 'led zeppelin', 'the doors']}}

Pydantic style schema

class Action(enum.Enum):
    play = "play"
    stop = "stop"
    previous = "previous"
    next_ = "next"


class MusicRequest(BaseModel):
    song: Optional[List[str]] = Field(
        default=None,
        description="The song(s) that the user would like to be played."
    )
    album: Optional[List[str]] = Field(
        default=None,
        description="The album(s) that the user would like to be played."
    )
    artist: Optional[List[str]] = Field(
        default=None,
        description="The artist(s) whose music the user would like to hear.",
        examples=[("Songs by paul simon", "paul simon")],
    )
    action: Optional[Action] = Field(
        default=None,
        description="The action that should be taken; one of `play`, `stop`, `next`, `previous`",
        examples=[
            ("Please stop the music", "stop"),
            ("play something", "play"),
            ("play a song", "play"),
            ("next song", "next"),
        ],
    )
    
schema, validator = from_pydantic(MusicRequest)   
chain = create_extraction_chain(
    llm, schema, encoder_or_encoder_class="json", validator=validator
)
chain.invoke("stop the music now")["validated_data"]
MusicRequest(song=None, album=None, artist=None, action=<Action.stop: 'stop'>)

Compatibility

Kor is tested against python 3.8, 3.9, 3.10, 3.11.

Installation

pip install kor

💡 Ideas

Ideas of some things that could be done with Kor.

  • Extract data from text that matches an extraction schema.
  • Power an AI assistant with skills by precisely understanding a user request.
  • Provide natural language access to an existing API.

🚧 Prototype

Prototype! So the API is not expected to be stable!

✨ What does Kor excel at? 🌟

  • Making mistakes! Plenty of them!
  • Slow! It uses large prompts with examples, and works best with the larger slower LLMs.
  • Crashing for long enough pieces of text! Context length window could become limiting when working with large forms or long text inputs.

The expectation is that as LLMs improve some of these issues will be mitigated.

Limitations

Kor has no limitations. (Just kidding.)

Take a look at the section above and at the compatibility section.

Got Ideas?

Open an issue, and let's discuss!

🎶 Why the name?

Fast to type and sufficiently unique.

Contributing

If you have any ideas or feature requests, please open an issue and share!

See CONTRIBUTING.md for more information.

Other packages

Probabilistically speaking this package is unlikely to work for your use case.

So here are some great alternatives:

Repositorios relacionados
PaddlePaddle/PaddleNLP

Easy-to-use and powerful LLM and SLM library with awesome model zoo.

PythonPyPIApache License 2.0nlpembedding
paddlenlp.readthedocs.io
13k3k
zjunlp/DeepKE

[EMNLP 2022] An Open Toolkit for Knowledge Graph Extraction and Construction

PythonPyPIMIT Licenseknowledge-graphrelation-extraction
deepke.zjukg.cn
4.4k746
snipsco/snips-nlu

Snips Python library to extract meaning from text

PythonPyPIApache License 2.0nlpnlu
snips-nlu.readthedocs.io
4k504
urchade/GLiNER

Generalist and Lightweight Model for Named Entity Recognition (Extract any entity types from texts)

PythonPyPIApache License 2.0information-extractionlarge-language-models
urchade.github.io/GLiNER
3.4k289
yifanfeng97/Hyper-Extract

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

PythonPyPIOtheraicli
yifanfeng97.github.io/Hyper-Extract/
3.1k373
mit-nlp/MITIE

MITIE: library and tools for information extraction

C++machine-learningnatural-language-processing
3k532
naiveHobo/InvoiceNet

Deep neural network to extract intelligent information from invoice documents.

PythonPyPIMIT Licenseinvoiceinvoice-management
2.7k412
HarderThenHarder/transformers_tasks

⭐️ NLP Algorithms with transformers lib. Supporting Text-Classification, Text-Generation, Information-Extraction, Text-Matching, RLHF, SFT etc.

Jupyter Notebooknlptext-classification
zhihu.com/column/c_1451236880973426688
2.4k399
crownpku/Information-Extraction-Chinese

Chinese Named Entity Recognition with IDCNN/biLSTM+CRF, and Relation Extraction with biGRU+2ATT 中文实体识别与关系提取

PythonPyPInlpchinese-nlp
2.3k799
tstanislawek/awesome-document-understanding

A curated list of resources for Document Understanding (DU) topic

awesome-listmachine-learning
1.5k178
quqxui/Awesome-LLM4IE-Papers

Awesome papers about generative Information Extraction (IE) using Large Language Models (LLMs)

cross-domain-learningdata-augmentation
arxiv.org/abs/2312.17617
1.1k61