extract

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package extract turns text into entities, the relations between them, and the triples those relations assert.

Two extractors implement the same stage. Rules needs nothing but the text: regexes, a gazetteer and relation patterns, all deterministic and all testable without a network. LLM asks a Model — the one thing this package does not compute itself — and does the work around the call: building the prompt, recovering JSON from whatever the model wrapped it in, and binding the answer back to the entities already known.

A Schema gates either extractor's output against a domain ontology, and a Floor gates it on confidence. The two are orthogonal — one asks "is this in the vocabulary", the other "is this sure enough" — so they share the two entry points of Test and a caller runs both.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalid = errors.New("extraction rejected")

ErrInvalid is what Report.Err wraps, so a caller can tell a rejected extraction from a transport failure with errors.Is.

View Source
var ErrParse = errors.New("no JSON in model reply")

ErrParse reports that a model reply held no usable JSON.

Functions

func JSON

func JSON(reply string) ([]byte, error)

JSON recovers the JSON document from a model reply. It strips a markdown fence, and when what is left still does not parse it takes the outermost braces or brackets, drops a trailing comma before a closing one, and closes what the model left open when it ran into a token limit. Those three faults are what models actually produce; anything else is ErrParse.

func Loose

func Loose(t semantic.Triple, known []Entity, min float64) []string

Loose returns the endpoints of a triple that match none of the entities already known. A graph builder promotes those into nodes of their own instead of leaving the edge dangling.

func Near

func Near(text string, candidates []string) (int, float64)

Near finds the candidate most like text and how alike it is, in [0,1]. It tries the cheap tests first and stops as soon as one is decisive: an exact match, then a known synonym, then containment scaled by how much of the longer string the shorter one covers, then the longest-matching-blocks ratio. It returns -1 when there are no candidates.

The Python original inserts sentence-embedding and word-vector stages between containment and the ratio. Those need a model; the stages that do not are here, and an embedding-backed matcher belongs behind Model rather than in this function.

func Ratio

func Ratio(a, b string) float64

Ratio is the share of two strings that lies in matching blocks: twice the matched length over the summed length, the similarity Python's difflib reports. Identical strings give 1, strings with nothing in common give 0.

func Similar

func Similar(text string, candidates []string) float64

Similar is how alike text and the closest candidate are, in [0,1], for a caller that wants the score without the candidate.

func Weigh

func Weigh(label string, score float64, want []string, text string) float64

Weigh blends an extractor's own confidence with how close the item is to the types a caller asked for, half from each. It returns score unchanged when the caller named no types, since there is then nothing to compare against.

Types

type Chain

type Chain struct {
	Mentions []Mention
	Head     Mention
	Label    string
}

Chain is the mentions that name one thing. Head is the mention that names it best: a name rather than a pronoun, and the earliest of those.

func Chains

func Chains(ms []Mention) []Chain

Chains groups the mentions that name one thing: names that match, and every pronoun Refer bound to one of them. A thing mentioned once is not a chain, so the result holds only what was said more than once.

func Coref

func Coref(text string, known []Entity) []Chain

Coref is the whole pass over a text: its mentions, the pronouns among them resolved, and the chains that result.

type Class

type Class struct {
	Name  string `json:"name"`
	Label string `json:"label"`
}

Class is one concept. Label stands in when Name is absent.

type Entity

type Entity struct {
	Text  string
	Label string
	Start int
	End   int
	Score float64
	Meta  map[string]any
}

Entity is a labelled span of the text it was found in. Start and End are byte offsets, so text[Start:End] is the span. Score is the extractor's confidence in [0,1].

func Bind

func Bind(text string, known []Entity, min float64) (Entity, bool)

Bind returns the entity that best matches text, or false when none reaches min. An exact, case-insensitive hit always wins.

func Narrow

func Narrow(text string, known []Entity, max int) []Entity

Narrow trims an entity roster to those the text plausibly mentions, and then to the longest max of them. A prompt that spends its budget listing entities the chunk never names buys nothing. A roster already within max is returned untouched, and one whose entities the text never mentions is kept whole rather than emptied — a filter that removes everything has told the caller nothing.

func (*Entity) UnmarshalJSON

func (e *Entity) UnmarshalJSON(b []byte) error

UnmarshalJSON reads an entity as a model returned it. Offsets are optional — the prompt asks for text and label, not spans — and an entity that comes back without them spans its own text, so End-Start is its length even when the position is unknown.

type Floor

type Floor float64

Floor is the least confidence an extraction may carry. It checks the axis a Schema does not: how much of the extraction clears the bar, and whether it is structurally sound — no entity with empty text, no relation missing an endpoint or pointing at itself. The zero Floor admits any score and still reports the structural faults.

func (Floor) Check

func (f Floor) Check(x Set) Report

Check scores an extraction on confidence and structure. Entities and relations are scored the way the Python validator scores them — a penalty for the share below the floor, a penalty for the share that is malformed, and a factor for the mean confidence — and an extraction holding both takes the mean of the two.

func (Floor) Keep

func (f Floor) Keep(x Set) Set

Keep returns the part of an extraction that clears the floor.

type Gap

type Gap struct {
	// Max is the most bytes that may separate two entities for them to count
	// as near. Zero uses 100, past which two mentions are rarely about each
	// other.
	Max int

	// Preds are the predicates to name a relation from. Empty says
	// related_to and nothing more.
	Preds []string

	// Min is the least a predicate must resemble the words between two
	// entities to be used. Zero uses 0.6. It has no effect without Preds,
	// since related_to is not a guess about which relation holds.
	Min float64
}

Gap relates entities that occur close together. It is what is left when no pattern fits: two things named a few words apart are usually about each other, even when the sentence joining them says how in a way no rule anticipated. On its own it claims only that much — the predicate is related_to — but a caller who names the predicates it is looking for gets the words between the two matched against them, and the best match names the relation.

Handing it the linking verbs at a Min of 1 is how an attribute is read: Gap{Preds: []string{"is", "was", "has"}, Min: 1} over "Apple is a corporation" states what the sentence states, and states nothing where the sentence used a verb it was not given.

The zero Gap works: entities within 100 bytes of each other, related_to.

func (Gap) Relations

func (g Gap) Relations(text string, known []Entity) []Relation

Relations pairs every two entities near enough to each other in text. Endpoints are ordered as the text reads them, not as the caller listed them, so two runs over the same text agree.

type Kind

type Kind string

Kind is which extraction a prompt asks for. Its value is the JSON key the reply must use.

const (
	Ents Kind = "entities"
	Rels Kind = "relations"
	Tris Kind = "triplets"
)

The three extractions a prompt can ask for.

func (Kind) JSON

func (k Kind) JSON() string

JSON is the JSON Schema of the reply this Kind demands, for an adapter that can constrain its model's output.

type LLM

type LLM struct {
	Model Model

	// Kinds are the entity labels to prefer. Empty asks for the general set.
	Kinds []string
	// Preds are the predicates to prefer, for both relations and triples.
	// Empty asks for whatever fits the text.
	Preds []string
	// Cap is the most entities a relation prompt will name. Zero uses 80,
	// past which the prompt spends more on the list than on the text.
	Cap int
	// When also asks when each relation held.
	When bool
	// Schema, when set, rejects an extraction that does not conform to it.
	Schema *Schema
	// Match is how alike a stated endpoint and a known entity must be for the
	// two to be the same thing. Zero uses 0.8.
	Match float64
}

LLM extracts by asking a Model. The call itself is the caller's business; what belongs here is everything around it — the prompt that states the shape of the answer, the recovery of JSON from whatever the model wrapped it in, the aliases providers use for the same field, and the binding of a named endpoint back to an entity already found.

Set Schema to refuse an extraction that leaves the ontology. A caller who would rather keep the conforming part calls Schema.Keep on the result instead.

func (LLM) Entities

func (l LLM) Entities(ctx context.Context, text string) ([]Entity, error)

Entities asks the model which entities the text names.

func (LLM) Extract

func (l LLM) Extract(ctx context.Context, c semantic.Chunk) ([]semantic.Triple, error)

Extract makes LLM a pipeline stage.

func (LLM) Find

func (l LLM) Find(ctx context.Context, text string) (Set, error)

Find runs both passes: the entities, then the relations between them.

func (LLM) Relations

func (l LLM) Relations(ctx context.Context, text string, known []Entity) ([]Relation, error)

Relations asks the model how the entities it was given are connected. The entities are named in the prompt so the model reuses their surface forms, and each endpoint it returns is bound back to one of them; an endpoint that matches none is kept as an UNKNOWN entity rather than dropped, because a co-founder the entity pass missed is still a co-founder.

func (LLM) Triples

func (l LLM) Triples(ctx context.Context, c semantic.Chunk) ([]semantic.Triple, error)

Triples asks the model for subject-predicate-object statements about a chunk directly, without first naming entities. It is the cheap path: one call instead of two, at the cost of untyped endpoints.

type Link struct {
	Subject   string
	Predicate string
	Object    string
	Score     float64

	// From and Until are when the relation began and ceased, as an ISO date
	// or as the phrase the text used. Empty when the text said nothing.
	From, Until string
	// When is the confidence that a temporal signal was really there, and
	// Cite the exact words it was read from.
	When float64
	Cite string
}

Link is a relation as the model stated it: endpoints named by text, not yet bound to any entity.

func (*Link) UnmarshalJSON

func (k *Link) UnmarshalJSON(b []byte) error

UnmarshalJSON reads a relation as a model stated it, endpoints still named by text. The temporal fields are read whether or not they were asked for; a model that volunteers them is not punished for it.

type Mention

type Mention struct {
	Text    string
	Start   int
	End     int
	Pronoun bool
	Label   string // the entity label, for a mention that came from an entity
	Of      string // what this mention refers to, once Refer has resolved it
}

Mention is one reference to a thing in a text: a name the entity pass found, or a pronoun standing in for one.

func Mentions

func Mentions(text string, known []Entity) []Mention

Mentions finds every reference in text: the pronouns it contains, plus the entities already found, ordered by position.

type Model

type Model interface {
	Complete(ctx context.Context, prompt string, schema any) (string, error)
}

Model is the completion this package needs and does not provide. The schema argument is the Kind being asked for; an adapter may turn Kind.JSON into whatever structured-output format its API wants, or ignore it and let the prompt do the work.

type Names

type Names []string

Names is a domain or range constraint. Generators write it as a bare string, a list of strings, or an object carrying a name, so it reads all three.

func (*Names) UnmarshalJSON

func (n *Names) UnmarshalJSON(b []byte) error

UnmarshalJSON reads a constraint written as a string, a list, or an object.

type Ontology

type Ontology struct {
	Classes    []Class    `json:"classes"`
	Properties []Property `json:"properties"`
}

Ontology is the vocabulary a Schema reads. It is the shape an ontology generator emits: named classes, and named properties that may name the classes they join.

type Predicate

type Predicate struct {
	Name          string
	Domain, Range []string // sorted; empty means unconstrained
}

Predicate is an allowed predicate and the concepts it may join. An empty Domain or Range means any concept, following OWL: a property with no rdfs:domain restricts nothing.

type Property

type Property struct {
	Name   string `json:"name"`
	Label  string `json:"label"`
	Domain Names  `json:"domain"`
	Range  Names  `json:"range"`
}

Property is one predicate and the concepts it joins.

type Ref

type Ref struct {
	Pronoun string
	Of      string
}

Ref is a pronoun and the mention it was resolved to.

func Refer

func Refer(ms []Mention) []Ref

Refer resolves each pronoun to the nearest preceding name whose label the pronoun admits, and to the nearest preceding name of any label when none does — a wrong antecedent of the right shape is worth more to a reader than no antecedent, and the label is on the chain for a caller who wants to check. It records what it settled on each pronoun mention, which is what Chains reads, and returns the pairs.

type Relation

type Relation struct {
	Subject   Entity
	Predicate string
	Object    Entity
	Score     float64
	Context   string
	Meta      map[string]any
}

Relation joins two entities with a predicate. Context is the surrounding text the relation was read from, which is what makes it checkable later.

type Report

type Report struct {
	OK      bool
	Score   float64
	Errs    []string
	Warns   []string
	Counts  map[string]int
	Unknown []string // labels a Schema did not recognise
}

Report is what a check found: whether the extraction passed, how much of it held up as a share in [0,1], the reasons it failed, milder remarks that did not fail it, and the counts behind all of them.

func (Report) Err

func (r Report) Err() error

Err is nil when the report passed, and otherwise an error naming every reason it did not. It wraps ErrInvalid, so a caller can tell a rejected extraction from a transport failure.

type Rules

type Rules struct {
	// Patterns maps an entity label to the regexp that finds it. A nil map
	// uses the built-in set. The first capturing group, when there is one, is
	// the entity text.
	Patterns map[string]*regexp.Regexp

	// Names is a gazetteer: a surface form to the label it carries. Matching
	// is case-insensitive and whole-word. A gazetteer hit outranks a pattern
	// hit over the same span, since the caller stated it and the pattern only
	// guessed.
	Names map[string]string

	// Min drops anything scoring below it. Zero keeps everything.
	Min float64
}

Rules extracts without a model. Entities come from a gazetteer of known names and from regexes over the shape of the text; relations come from patterns that read a verb phrase between two entities already found. Every answer is a function of the input, so it is reproducible and testable offline, and it is the sensible floor under an LLM extractor rather than a replacement for it.

The zero Rules works: it uses the built-in patterns, no gazetteer, and keeps everything it finds.

func (Rules) Entities

func (r Rules) Entities(text string) []Entity

Entities finds every entity in text. Overlapping finds are resolved in favour of the more certain and then the longer, so no two returned entities cover the same character. When nothing matches at all it falls back to capitalised words labelled UNKNOWN, which is worth more to a downstream stage than an empty answer.

func (Rules) Extract

func (r Rules) Extract(_ context.Context, c semantic.Chunk) ([]semantic.Triple, error)

Extract makes Rules a pipeline stage.

func (Rules) Find

func (r Rules) Find(text string) Set

Find returns everything Rules can say about a text.

func (Rules) Relations

func (r Rules) Relations(text string, known []Entity) []Relation

Relations reads the relation patterns over text, joining only entities the caller already found. Requiring both endpoints to be known entities is what keeps a pattern from matching a long run of prose that merely ends in the right verb.

type Schema

type Schema struct {
	Concepts   []string // sorted
	Predicates map[string]Predicate
}

Schema is a read-only view over a domain ontology: the concepts an entity label may take and the predicates a relation may use, with the concepts each predicate joins. It is what makes extraction schema-guided — the deterministic half of ontology-based information extraction, needing no model.

Names match exactly. An ontology generator that writes concepts in PascalCase and predicates in camelCase expects labels in the same convention, so a schema built from one rejects "person" where it allows "Person".

The zero Schema has no concepts and no predicates, so it allows nothing.

func NewSchema

func NewSchema(o Ontology) Schema

NewSchema builds a Schema from an ontology. Concepts come from the classes and from every type a property names as an endpoint, so a type that appears only as a range is still known — a class-frequency cutoff during induction should not make a property's own range off-vocabulary.

func ReadSchema

func ReadSchema(r io.Reader) (Schema, error)

ReadSchema builds a Schema from an ontology written as JSON.

func (Schema) Allows

func (s Schema) Allows(subject, predicate, object string) bool

Allows reports whether a relation conforms: both endpoints are known concepts, the predicate is known, and the endpoints satisfy its domain and range. Membership is exact — subClassOf is not followed, so a subclass endpoint does not satisfy a superclass domain.

func (Schema) Check

func (s Schema) Check(x Set) Report

Check reports how much of an extraction conforms to the schema: every entity label must be a concept, and every relation must satisfy Allows.

func (Schema) Concept

func (s Schema) Concept(name string) bool

Concept reports whether name is an allowed entity label.

func (Schema) Keep

func (s Schema) Keep(x Set) Set

Keep returns the conforming subset: entities whose label is a concept, and relations that satisfy Allows.

func (Schema) Pred

func (s Schema) Pred(name string) bool

Pred reports whether name is an allowed predicate.

type Set

type Set struct {
	Entities  []Entity
	Relations []Relation
}

Set is one pass over a text: the entities found and the relations among them. It is what both extractors return before the pipeline flattens it to triples, and what both checks read.

func (Set) Triples

func (s Set) Triples(c semantic.Chunk) []semantic.Triple

Triples flattens the relations into pipeline triples, attributing each to the chunk it came from.

type Test

type Test interface {
	Check(Set) Report
	Keep(Set) Set
}

Test is a check over an extraction. Schema and Floor are the two, and they are orthogonal: one asks whether the extraction is in the vocabulary, the other whether it is sure enough and structurally sound. A caller that wants both runs both, in either order.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL