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 ¶
- Variables
- func JSON(reply string) ([]byte, error)
- func Loose(t semantic.Triple, known []Entity, min float64) []string
- func Near(text string, candidates []string) (int, float64)
- func Ratio(a, b string) float64
- func Similar(text string, candidates []string) float64
- func Weigh(label string, score float64, want []string, text string) float64
- type Chain
- type Class
- type Entity
- type Floor
- type Gap
- type Kind
- type LLM
- func (l LLM) Entities(ctx context.Context, text string) ([]Entity, error)
- func (l LLM) Extract(ctx context.Context, c semantic.Chunk) ([]semantic.Triple, error)
- func (l LLM) Find(ctx context.Context, text string) (Set, error)
- func (l LLM) Relations(ctx context.Context, text string, known []Entity) ([]Relation, error)
- func (l LLM) Triples(ctx context.Context, c semantic.Chunk) ([]semantic.Triple, error)
- type Link
- type Mention
- type Model
- type Names
- type Ontology
- type Predicate
- type Property
- type Ref
- type Relation
- type Report
- type Rules
- type Schema
- type Set
- type Test
Constants ¶
This section is empty.
Variables ¶
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.
var ErrParse = errors.New("no JSON in model reply")
ErrParse reports that a model reply held no usable JSON.
Functions ¶
func JSON ¶
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 ¶
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 ¶
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 ¶
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 ¶
Similar is how alike text and the closest candidate are, in [0,1], for a caller that wants the score without the candidate.
Types ¶
type Chain ¶
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.
type Entity ¶
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 ¶
Bind returns the entity that best matches text, or false when none reaches min. An exact, case-insensitive hit always wins.
func Narrow ¶
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 ¶
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 ¶
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.
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.
type Kind ¶
type Kind string
Kind is which extraction a prompt asks for. Its value is the JSON key the reply must use.
The three extractions a prompt can ask for.
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) Relations ¶
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.
type Link ¶
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 ¶
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.
type Model ¶
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 ¶
UnmarshalJSON reads a constraint written as a string, a list, or an object.
type Ontology ¶
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 ¶
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 ¶
Ref is a pronoun and the mention it was resolved to.
func Refer ¶
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.
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 ¶
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.
type Schema ¶
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 ¶
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 ¶
ReadSchema builds a Schema from an ontology written as JSON.
func (Schema) Allows ¶
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 ¶
Check reports how much of an extraction conforms to the schema: every entity label must be a concept, and every relation must satisfy Allows.
type Set ¶
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.