Skip to main content

Python library for extracting structured event data from text posts with LLM agents.

Project description

event_extraction_agent

event_extraction_agent - Python-библиотека для извлечения структурированных данных о мероприятиях из текстовых постов с помощью LLM.

Главный и стабильный способ использования - ExtractionPipeline: вы передаете источник постов и ExtractionAgentConfig, а на выходе получаете BatchExtractionResult со всеми событиями, статусами, ошибками и методами сохранения результата.

Установка

pip install event-extraction-agent

Для локальной разработки из репозитория:

python -m pip install -e ".[dev]"
python -m pytest

Быстрый старт

from event_extraction_agent import (
    ExtractionAgentConfig,
    ExtractionPipeline,
    OllamaChatClient,
    SourcePost,
)


class MySource:
    def fetch_posts(self) -> list[SourcePost]:
        return [
            SourcePost(
                text="12 июня в 18:00 пройдет открытая лекция.",
                source_name="Example source",
                source_url="https://example.com/posts/123",
                published_at="2026-06-01T10:00:00+03:00",
                external_id="post-123",
            )
        ]


pipeline = ExtractionPipeline(
    source=MySource(),
    agent_config=ExtractionAgentConfig(
        main_client=OllamaChatClient(model="qwen2.5:3b"),
    ),
)

result = pipeline.run()

for outcome in result.outcomes:
    if outcome.event:
        print(outcome.event.model_dump(mode="json"))
    else:
        print(outcome.status, outcome.errors)

Минимально в ExtractionAgentConfig нужно передать main_client. Если refinement_client не задан, уточнение типа события выполняется тем же клиентом.

Сохранение результата

pipeline.run() возвращает BatchExtractionResult. Его можно сохранить в JSON:

result = pipeline.run()
result.save_json("events_result.json")

И загрузить обратно:

from event_extraction_agent import BatchExtractionResult

previous = BatchExtractionResult.load_json("events_result.json")

Incremental processing

Pipeline может сам загрузить предыдущий результат и сохранить новый:

pipeline = ExtractionPipeline(
    source=source,
    agent_config=agent_config,
    previous_result_path="events_result.json",
    save_result_path="events_result.json",
)

result = pipeline.run()
print(result.cached, result.processed)

Incremental-режим пропускает LLM extraction, если у нового поста совпали external_id и нормализованный текст для LLM (raw_text, если он задан, иначе text) с предыдущим результатом. Результаты со статусом llm_error по умолчанию обрабатываются повторно.

VK source

Для VK есть готовый source adapter:

from event_extraction_agent import ExtractionAgentConfig, ExtractionPipeline, OllamaChatClient, VKSource

source = VKSource(
    access_token="vk-service-token",
    sources=[
        "https://vk.com/club123",
        "public456",
        "my_community_domain",
        -789,
    ],
    posts_per_source_limit=20,
)

result = ExtractionPipeline(
    source=source,
    agent_config=ExtractionAgentConfig(
        main_client=OllamaChatClient(model="qwen2.5:3b"),
    ),
    previous_result_path="events_result.json",
    save_result_path="events_result.json",
).run()

VKSource получает посты через wall.get, очищает текст для LLM, добавляет source_name, source_url, published_at, external_id и возвращает список SourcePost.

Если один VK source недоступен, остальные источники по умолчанию продолжают обрабатываться. Ошибки доступны через source.errors или fetch_posts_with_errors():

fetch_result = source.fetch_posts_with_errors()

for error in fetch_result.errors:
    print(error.source, error.code, error)

По умолчанию VKSource использует rate limit 20 запросов в секунду и retry/backoff для временных ошибок VK, HTTP 429/5xx и сетевых сбоев.

Настройка агента

Все настройки LLM и extraction-поведения передаются через ExtractionAgentConfig:

config = ExtractionAgentConfig(
    main_client=main_client,
    refinement_client=refinement_client,
    use_event_type_refinement=True,
    current_datetime="2026-06-10T12:00:00+03:00",
    min_request_interval_seconds=2.1,
    max_retries=1,
)

Поддерживается любой LLM-клиент с методом:

complete(system_prompt: str, user_prompt: str) -> str

В пакете есть готовые клиенты:

  • OllamaChatClient
  • GroqChatClient

Что возвращает pipeline

BatchExtractionResult содержит:

  • outcomes: результаты по каждому посту;
  • extracted, skipped, invalid, llm_errors: счетчики статусов;
  • cached, processed: счетчики incremental-режима;
  • error_count, error_limit_reached: информация о batch-лимитах;
  • save_json(path) и load_json(path).

Каждый ExtractionOutcome содержит исходный SourcePost, статус обработки, найденное Event или структурированные ошибки.

Границы пакета

В пакет входит extraction-ядро, pipeline, модели, LLM-клиенты для Ollama/Groq и VK source adapter.

Пакет намеренно не включает:

  • базу данных;
  • HTTP API;
  • расписания;
  • чтение секретов из .env;
  • обработку VK-вложений;
  • source adapters кроме VK.

Приложение, которое использует библиотеку, отвечает за конфигурацию, секреты, хранение данных и собственные источники.

Происхождение пакета

event_extraction_agent выделен из проекта olivoreo/event-ai-agent. Из исходного проекта перенесено extraction-ядро: модели события, промпты, валидация, исправление ответа LLM и клиенты для Ollama/Groq.

При переносе намеренно не включались backend API, база данных, загрузчики внешних источников и экспериментальные ML-компоненты. Цель пакета - сделать extraction-логику переиспользуемой в других проектах.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

event_extraction_agent-1.0.1.tar.gz (34.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

event_extraction_agent-1.0.1-py3-none-any.whl (27.8 kB view details)

Uploaded Python 3

File details

Details for the file event_extraction_agent-1.0.1.tar.gz.

File metadata

  • Download URL: event_extraction_agent-1.0.1.tar.gz
  • Upload date:
  • Size: 34.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for event_extraction_agent-1.0.1.tar.gz
Algorithm Hash digest
SHA256 c0247513fc4a14113218e902fe7e1b95117d0e9496ed428c64861f2528584af0
MD5 57c5d336582a8bcc3fc95601114873c8
BLAKE2b-256 b7f9a9eff691dcfcbe715da460ccfc7f77b7416f82e5e9996f2066d95c78a723

See more details on using hashes here.

Provenance

The following attestation bundles were made for event_extraction_agent-1.0.1.tar.gz:

Publisher: publish.yml on olivoreo/event-extraction-agent

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file event_extraction_agent-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for event_extraction_agent-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9ef0e0c968b974e0c7ae1ef4e6174385cef8cec1183456aa0da231c3b1834a20
MD5 928a983c126ba04b4570b828ba272ab9
BLAKE2b-256 5adb5633a71874afc929bfa33da08e2144618858cfba8fee31e1273d67e6ade9

See more details on using hashes here.

Provenance

The following attestation bundles were made for event_extraction_agent-1.0.1-py3-none-any.whl:

Publisher: publish.yml on olivoreo/event-extraction-agent

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page