Skip to content

ai_document_annotator

Class info

Classes

Name Children Inherits
AIDocumentAnnotator
docler.annotators.ai_document_annotator
AI-based document and chunk annotator.
    DefaultMetadata
    docler.annotators.ai_document_annotator
    Default metadata for a document or chunk.

      🛈 DocStrings

      AI-powered document and chunk metadata annotation.

      AIDocumentAnnotator

      Bases: Annotator[AIDocumentAnnotatorConfig]

      AI-based document and chunk annotator.

      Enhances documents and chunks with metadata.

      Class Type Parameters:

      Name Bound or Constraints Description Default
      TMetadata Schema

      Type of metadata model to use. Must be a schemez Schema.

      DefaultMetadata
      Source code in src/docler/annotators/ai_document_annotator.py
      class AIDocumentAnnotator[TMetadata: Schema = DefaultMetadata](
          Annotator[AIDocumentAnnotatorConfig]
      ):
          """AI-based document and chunk annotator.
      
          Enhances documents and chunks with metadata.
      
          Type Parameters:
              TMetadata: Type of metadata model to use. Must be a schemez Schema.
          """
      
          Config = AIDocumentAnnotatorConfig
          REQUIRED_PACKAGES: ClassVar = {"agentpool"}
      
          def __init__(
              self,
              model: str | None = None,
              system_prompt: str | None = None,
              user_prompt: str | None = None,
              metadata_model: type[TMetadata] = DefaultMetadata,  # type: ignore
              max_context_length: int = 1500,
              batch_size: int = 5,
          ) -> None:
              """Initialize the AI document annotator.
      
              Args:
                  model: LLM model to use for annotation
                  system_prompt: Optional custom prompt for annotation
                  user_prompt: Optional custom prompt for annotation
                  metadata_model: Pydantic model class for metadata structure
                  max_context_length: Maximum length of context for annotation
                  batch_size: Number of chunks to process in parallel
              """
              super().__init__()
              self.model = model or DEFAULT_ANNOTATOR_MODEL
              self.system_prompt = system_prompt or DEFAULT_DOC_SYSTEM_PROMPT
              self.user_prompt = user_prompt or DEFAULT_DOC_PROMPT_TEMPLATE
              self.metadata_model = metadata_model
              self.max_context_length = max_context_length
              self.batch_size = batch_size
      
          async def annotate(self, document: ChunkedDocument) -> ChunkedDocument:
              """Annotate document and chunks with AI-generated metadata.
      
              Args:
                  document: Chunked document to annotate
      
              Returns:
                  Document with enhanced metadata
              """
              from agentpool import Agent
      
              agent = Agent(
                  model=self.model,
                  system_prompt=self.system_prompt,
                  output_type=self.metadata_model,
              )
              # Get a condensed version of the document for context
              context = (
                  document.content[: self.max_context_length] + "..."
                  if self.max_context_length and len(document.content) > self.max_context_length
                  else document.content
              )
      
              semaphore = asyncio.Semaphore(self.batch_size)
      
              async def annotate_chunk(chunk: TextChunk) -> None:
                  prompt = self.user_prompt.format(context=context, chunk=chunk.content)
                  try:
                      async with semaphore:
                          result = await agent.run(prompt)
                  except Exception:
                      # One failing chunk must not drop the others' results.
                      self.logger.exception("Error annotating chunk %s", chunk.chunk_index)
                      return
                  chunk.metadata |= result.content.model_dump()
      
              await anyenv.gather(*(annotate_chunk(chunk) for chunk in document.chunks))
              return document
      

      __init__

      __init__(
          model: str | None = None,
          system_prompt: str | None = None,
          user_prompt: str | None = None,
          metadata_model: type[TMetadata] = DefaultMetadata,
          max_context_length: int = 1500,
          batch_size: int = 5,
      ) -> None
      

      Initialize the AI document annotator.

      Parameters:

      Name Type Description Default
      model str | None

      LLM model to use for annotation

      None
      system_prompt str | None

      Optional custom prompt for annotation

      None
      user_prompt str | None

      Optional custom prompt for annotation

      None
      metadata_model type[TMetadata]

      Pydantic model class for metadata structure

      DefaultMetadata
      max_context_length int

      Maximum length of context for annotation

      1500
      batch_size int

      Number of chunks to process in parallel

      5
      Source code in src/docler/annotators/ai_document_annotator.py
      def __init__(
          self,
          model: str | None = None,
          system_prompt: str | None = None,
          user_prompt: str | None = None,
          metadata_model: type[TMetadata] = DefaultMetadata,  # type: ignore
          max_context_length: int = 1500,
          batch_size: int = 5,
      ) -> None:
          """Initialize the AI document annotator.
      
          Args:
              model: LLM model to use for annotation
              system_prompt: Optional custom prompt for annotation
              user_prompt: Optional custom prompt for annotation
              metadata_model: Pydantic model class for metadata structure
              max_context_length: Maximum length of context for annotation
              batch_size: Number of chunks to process in parallel
          """
          super().__init__()
          self.model = model or DEFAULT_ANNOTATOR_MODEL
          self.system_prompt = system_prompt or DEFAULT_DOC_SYSTEM_PROMPT
          self.user_prompt = user_prompt or DEFAULT_DOC_PROMPT_TEMPLATE
          self.metadata_model = metadata_model
          self.max_context_length = max_context_length
          self.batch_size = batch_size
      

      annotate async

      annotate(document: ChunkedDocument) -> ChunkedDocument
      

      Annotate document and chunks with AI-generated metadata.

      Parameters:

      Name Type Description Default
      document ChunkedDocument

      Chunked document to annotate

      required

      Returns:

      Type Description
      ChunkedDocument

      Document with enhanced metadata

      Source code in src/docler/annotators/ai_document_annotator.py
      async def annotate(self, document: ChunkedDocument) -> ChunkedDocument:
          """Annotate document and chunks with AI-generated metadata.
      
          Args:
              document: Chunked document to annotate
      
          Returns:
              Document with enhanced metadata
          """
          from agentpool import Agent
      
          agent = Agent(
              model=self.model,
              system_prompt=self.system_prompt,
              output_type=self.metadata_model,
          )
          # Get a condensed version of the document for context
          context = (
              document.content[: self.max_context_length] + "..."
              if self.max_context_length and len(document.content) > self.max_context_length
              else document.content
          )
      
          semaphore = asyncio.Semaphore(self.batch_size)
      
          async def annotate_chunk(chunk: TextChunk) -> None:
              prompt = self.user_prompt.format(context=context, chunk=chunk.content)
              try:
                  async with semaphore:
                      result = await agent.run(prompt)
              except Exception:
                  # One failing chunk must not drop the others' results.
                  self.logger.exception("Error annotating chunk %s", chunk.chunk_index)
                  return
              chunk.metadata |= result.content.model_dump()
      
          await anyenv.gather(*(annotate_chunk(chunk) for chunk in document.chunks))
          return document
      

      DefaultMetadata

      Bases: Schema

      Default metadata for a document or chunk.

      Source code in src/docler/annotators/ai_document_annotator.py
      class DefaultMetadata(Schema):
          """Default metadata for a document or chunk."""
      
          topics: list[str]
          """Topics/categories."""
      
          keywords: list[str]
          """Keywords."""
      
          entities: list[str]
          """Main entities."""
      

      entities instance-attribute

      entities: list[str]
      

      Main entities.

      keywords instance-attribute

      keywords: list[str]
      

      Keywords.

      topics instance-attribute

      topics: list[str]
      

      Topics/categories.